ball2d 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -23
- package/dist/browser.js +3046 -2306
- package/dist/core.wasm +0 -0
- package/dist/licenses/native.json +6 -0
- package/dist/licenses/valibot.txt +9 -0
- package/dist/node.js +33 -33
- package/dist/stadiums/asphalt.ball2dstadium +515 -0
- package/dist/stadiums/{big_hockey.hbs → asphalt_arena.ball2dstadium} +118 -119
- package/dist/stadiums/{big.hbs → big.ball2dstadium} +16 -16
- package/dist/stadiums/{big_easy.hbs → big_easy.ball2dstadium} +16 -16
- package/dist/stadiums/{big_rounded.hbs → big_rounded.ball2dstadium} +20 -20
- package/dist/stadiums/{classic.hbs → classic.ball2dstadium} +16 -16
- package/dist/stadiums/courtyard.ball2dstadium +611 -0
- package/dist/stadiums/{easy.hbs → easy.ball2dstadium} +16 -16
- package/dist/stadiums/{huge.hbs → huge.ball2dstadium} +16 -16
- package/dist/stadiums/meadow.ball2dstadium +611 -0
- package/dist/stadiums/provenance.json +36 -20
- package/dist/stadiums/{rounded.hbs → rounded.ball2dstadium} +20 -20
- package/dist/stadiums/{small.hbs → small.ball2dstadium} +16 -16
- package/dist/stadiums/{hockey.hbs → street_five.ball2dstadium} +82 -83
- package/dist/stadiums/training_green.ball2dstadium +611 -0
- package/dist/types/browser.d.ts +6 -0
- package/dist/types/config.d.ts +3 -0
- package/dist/types/match-state.d.ts +8 -2
- package/dist/types/node.d.ts +2 -2
- package/dist/types/player.d.ts +2 -0
- package/dist/types/replay.d.ts +1 -1
- package/dist/types/room-geo.d.ts +6 -0
- package/dist/types/room.d.ts +6 -4
- package/package.json +2 -1
package/dist/node.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/promises";import{createRequire as n}from"module";import{createCipheriv as r,createDecipheriv as i,createHash as a,createHmac as o,createSign as s,randomBytes as c,randomUUID as l,timingSafeEqual as u,webcrypto as d}from"crypto";import{createSocket as f}from"dgram";import p from"node:process";import*as m from"node:os";import h from"node:os";import g from"node:tty";import*as _ from"node:net";import{connect as v,createServer as y,isIP as b,isIPv4 as x,isIPv6 as S}from"node:net";import*as C from"node:tls";import{isIPv4 as w}from"net";import*as T from"node:crypto";import{setTimeout as E}from"timers/promises";import{promises as D}from"node:dns";import*as O from"node:timers/promises";import{EventEmitter as k}from"node:events";import{performance as A}from"perf_hooks";var j=Object.create,M=Object.defineProperty,N=Object.getOwnPropertyDescriptor,P=Object.getOwnPropertyNames,F=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,L=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},R=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),z=(e,t)=>{let n={};for(var r in e)M(n,r,{get:e[r],enumerable:!0});return t||M(n,Symbol.toStringTag,{value:`Module`}),n},B=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=P(t),a=0,o=i.length,s;a<o;a++)s=i[a],!I.call(e,s)&&s!==n&&M(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=N(t,s))||r.enumerable});return e},V=(e,t,n)=>(n=e==null?{}:j(F(e)),B(t||!e||!e.__esModule||!I.call(e,`default`)?M(n,`default`,{value:e,enumerable:!0}):n,e)),ee=e=>I.call(e,`module.exports`)?e[`module.exports`]:B(M({},`__esModule`,{value:!0}),e),te=e(import.meta.url),ne=`/api/v1`,re={rooms:`${ne}/rooms`,sdkRooms:`${ne}/sdk/rooms`,account:`${ne}/account`,accountConfig:`${ne}/account/config`,profile:`${ne}/account/profile`,notifications:`${ne}/account/notifications`,keys:`${ne}/account/keys`,signal:e=>`${ne}/rooms/${encodeURIComponent(e)}/signal`,lease:e=>`${ne}/sdk/rooms/${encodeURIComponent(e)}/lease`};function ie(e){if(!e||typeof e!=`object`)throw Error(`Invalid room authorization response`);let t=e;if(typeof t.leaseId!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t.leaseId)||typeof t.expiresAt!=`number`||!Number.isSafeInteger(t.expiresAt)||typeof t.validForMs!=`number`||!Number.isFinite(t.validForMs)||t.validForMs<=0||t.validForMs>9e4)throw Error(`Invalid room authorization response`);return t}var ae=class{origin;apiKey;roomId;expired;grant;deadline=0;expiry;renewal;abort=new AbortController;pending=Promise.resolve();stopped;failures=0;started=!1;constructor(e,t,n,r,i,a){if(this.origin=e,this.apiKey=t,this.roomId=n,this.expired=a,!/^[0-9a-f]{10}$/.test(n))throw Error(`Invalid room authorization response`);this.grant=ie(r),this.accept(this.grant,i)}accept(e,t){if(e.leaseId!==this.grant.leaseId)throw Error(`Room authorization changed unexpectedly`);let n=t+e.validForMs;if(performance.now()>=n)throw Error(`Room authorization expired during the request`);this.grant=e,this.deadline=n,clearTimeout(this.expiry),this.expiry=setTimeout(()=>this.end(`Room authorization expired.`),Math.max(0,n-performance.now()))}start(){this.started||this.abort.signal.aborted||(this.started=!0,this.pending=this.refresh())}end(e){clearTimeout(this.expiry),clearTimeout(this.renewal),this.abort.abort(),this.expired(e)}async refresh(){let e=performance.now(),t=!1;try{let n=await fetch(new URL(re.lease(this.roomId),this.origin),{method:`POST`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.any([this.abort.signal,AbortSignal.timeout(8e3)])});if(!n.ok)throw t=[400,401,403,404,409,410].includes(n.status),await n.body?.cancel(),Error(`Room authorization could not be renewed.`);let r=await n.json();t=!0;let i=ie(r.lease);if(this.abort.signal.aborted)return;if(performance.now()>=this.deadline)throw Error(`Room authorization expired.`);this.accept(i,e),this.failures=0}catch{if(this.abort.signal.aborted)return;if(t){this.end(`Room authorization ended.`);return}this.failures++}if(!this.abort.signal.aborted){let e=this.failures?Math.min(5e3*2**Math.min(this.failures-1,3),3e4):3e4;this.renewal=setTimeout(()=>{this.pending=this.refresh()},Math.max(0,Math.min(e,this.deadline-performance.now())))}}stop(){return this.stopped?this.stopped:(clearTimeout(this.expiry),clearTimeout(this.renewal),this.abort.abort(),this.stopped=(async()=>{await this.pending;try{await(await fetch(new URL(re.lease(this.roomId),this.origin),{method:`DELETE`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.timeout(3e3)})).body?.cancel()}catch{}})(),this.stopped)}},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
|
|
3
|
-
`:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),
|
|
4
|
-
`:case`\r`:case`\u2028`:case`\u2029`:H(),
|
|
5
|
-
`:case`\r`:throw
|
|
6
|
-
`;case`r`:return H(),`\r`;case`t`:return H(),` `;case`v`:return H(),`\v`;case`0`:if(H(),
|
|
7
|
-
`:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),
|
|
8
|
-
`&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw
|
|
1
|
+
import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/promises";import{createRequire as n}from"module";import{createCipheriv as r,createDecipheriv as i,createHash as a,createHmac as o,createSign as s,randomBytes as c,randomUUID as l,timingSafeEqual as u,webcrypto as d}from"crypto";import{createSocket as f}from"dgram";import p from"node:process";import*as m from"node:os";import h from"node:os";import g from"node:tty";import*as _ from"node:net";import{connect as v,createServer as y,isIP as b,isIPv4 as x,isIPv6 as S}from"node:net";import*as C from"node:tls";import{isIPv4 as w}from"net";import*as T from"node:crypto";import{setTimeout as E}from"timers/promises";import{promises as D}from"node:dns";import*as O from"node:timers/promises";import{EventEmitter as k}from"node:events";import{performance as A}from"perf_hooks";var j=Object.create,M=Object.defineProperty,N=Object.getOwnPropertyDescriptor,P=Object.getOwnPropertyNames,F=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,L=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},R=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),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`,profileVisibility:`${ne}/account/profile/visibility`,publicProfile:(e,t)=>`${ne}/community/${e}/${encodeURIComponent(t)}`,notifications:`${ne}/account/notifications`,keys:`${ne}/account/keys`,signal:e=>`${ne}/rooms/${encodeURIComponent(e)}/signal`,liveness:e=>`${ne}/rooms/${encodeURIComponent(e)}/liveness`,lease:e=>`${ne}/sdk/rooms/${encodeURIComponent(e)}/lease`},ie={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function ae(e){return e?{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}:ie}function oe(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function se(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??oe(a),c={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind===`schema`,u=i?.message??e.message??(e.reference,c.lang,void 0)??(l?(c.lang,void 0):null)??r.message??(c.lang,void 0);u!==void 0&&(c.message=typeof u==`function`?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function ce(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}function le(e){return e[`~standard`]={version:1,vendor:`valibot`,validate:t=>e[`~run`]({value:t},ae())},e}function ue(e,t){return{kind:`validation`,type:`check`,reference:ue,async:!1,expects:null,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&se(this,`input`,e,t),e}}}function de(e){return{kind:`validation`,type:`finite`,reference:de,async:!1,expects:null,requirement:Number.isFinite,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&se(this,`finite`,e,t),e}}}function fe(e,t){return{kind:`validation`,type:`gt_value`,reference:fe,async:!1,expects:`>${e instanceof Date?e.toJSON():oe(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value>this.requirement)&&se(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():oe(e.value)}),e}}}function pe(e,t){return{kind:`validation`,type:`max_length`,reference:pe,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length>this.requirement&&se(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function me(e,t){return{kind:`validation`,type:`max_value`,reference:me,async:!1,expects:`<=${e instanceof Date?e.toJSON():oe(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value<=this.requirement)&&se(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():oe(e.value)}),e}}}function he(e,t){return{kind:`validation`,type:`min_length`,reference:he,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length<this.requirement&&se(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function ge(e,t){return{kind:`validation`,type:`regex`,reference:ge,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&se(this,`format`,e,t),e}}}function _e(e){return{kind:`validation`,type:`safe_integer`,reference:_e,async:!1,expects:null,requirement:Number.isSafeInteger,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&se(this,`safe integer`,e,t),e}}}var ve={abortEarly:!0};function ye(e,t,n){return typeof e.fallback==`function`?e.fallback(t,n):e.fallback}function be(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function xe(e,t){return!e[`~run`]({value:t},ve).issues}function Se(e){return le({kind:`schema`,type:`boolean`,reference:Se,expects:`boolean`,async:!1,message:e,"~run"(e,t){return typeof e.value==`boolean`?e.typed=!0:se(this,`type`,e,t),e}})}function Ce(e,t){return le({kind:`schema`,type:`custom`,reference:Ce,expects:`unknown`,async:!1,check:e,message:t,"~run"(e,t){return this.check(e.value)?e.typed=!0:se(this,`type`,e,t),e}})}function we(e){return le({kind:`schema`,type:`number`,reference:we,expects:`number`,async:!1,message:e,"~run"(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:se(this,`type`,e,t),e}})}function Te(e,t){return le({kind:`schema`,type:`object`,reference:Te,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:be(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=ye(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(se(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}}else se(this,`type`,e,t);return e}})}function Ee(e,t){return le({kind:`schema`,type:`optional`,reference:Ee,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(e,t){return e.value===void 0&&(this.default!==void 0&&(e.value=be(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}})}function De(e,t){return le({kind:`schema`,type:`picklist`,reference:De,expects:ce(e.map(oe),`|`),async:!1,options:e,message:t,"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:se(this,`type`,e,t),e}})}function Oe(e,t){return le({kind:`schema`,type:`strict_object`,reference:Oe,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:be(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=ye(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(se(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}if(!e.issues||!t.abortEarly){for(let r in n)if(!Object.prototype.hasOwnProperty.call(this.entries,r)){se(this,`key`,e,t,{input:r,expected:`never`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]});break}}}else se(this,`type`,e,t);return e}})}function ke(e){return le({kind:`schema`,type:`string`,reference:ke,expects:`string`,async:!1,message:e,"~run"(e,t){return typeof e.value==`string`?e.typed=!0:se(this,`type`,e,t),e}})}function Ae(){return le({kind:`schema`,type:`unknown`,reference:Ae,expects:`unknown`,async:!1,"~run"(e){return e.typed=!0,e}})}function je(...e){return le({...e[0],pipe:e,"~run"(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r[`~run`](t,n))}return t}})}function Me(e,t,n){let r=e[`~run`]({value:t},ae(n));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}var Ne=je(ke(),ge(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)),Pe=je(we(),_e()),Fe=e=>je(Ce(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),e),Ie=e=>Fe(Oe(e));Ie({password:Ae()}),Ie({password:Ae(),verifier:Ae()}),Ie({verifier:Ae()}),Ie({verified:Se()});var Le=Te({leaseId:Ne,expiresAt:Pe,validForMs:je(we(),de(),fe(0),me(9e4))}),Re=Te({error:je(ke(),pe(300),ue(e=>e.trim()!==``),ue(e=>!/[<>]/.test(e)),ue(e=>!/[\u0000-\u001f\u007f]/.test(e)))});function ze(e){let t=Me(Le,e);if(!t.success)throw Error(`Invalid room authorization response`);return t.output}var Be=class{origin;apiKey;roomId;stopped;grant;constructor(e,t,n,r,i){if(this.origin=e,this.apiKey=t,this.roomId=n,!/^[0-9a-f]{10}$/.test(n))throw Error(`Invalid room authorization response`);if(this.grant=ze(r),performance.now()>=i+this.grant.validForMs)throw Error(`Room authorization expired during the request`)}get leaseId(){return this.grant.leaseId}stop(){return this.stopped||=(async()=>{try{await(await fetch(new URL(re.lease(this.roomId),this.origin),{method:`DELETE`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.timeout(3e3)})).body?.cancel()}catch{}})(),this.stopped}};function Ve(e,t,n,r){let i=e.find(e=>e.id===t),a=e.find(e=>e.id===n);return!i||i.muted||!a||a.bot||t===n||!r.trim()||r.length>200?null:{type:`directChat`,fromId:i.id,fromName:i.name,toId:a.id,toName:a.name,text:r}}function He(e,t,n){let r=e.indexOf(t);return r<0||t.team===n?!1:(t.team=n,e.splice(r,1),e.push(t),!0)}function Ue(e,t){let n=e.filter(e=>e.team===0),r=e.filter(e=>e.team===1).length,i=e.filter(e=>e.team===2).length;if(!n.length||r===i&&n.length<2)return[];let a=()=>n.splice(t?Math.floor(t()*n.length):0,1)[0];return r<i?[{player:a(),team:1}]:i<r?[{player:a(),team:2}]:[{player:a(),team:1},{player:a(),team:2}]}function We(e,t){return(t?[t]:[2,1]).flatMap(t=>e.filter(e=>e.team===t))}function Ge(e,t,n){return t!==void 0&&(e.admin||!n&&t===e)}function Ke(e,t,n){return t!==void 0&&e.admin&&t!==e&&!n(t)}function qe(e,t,n){switch(t.action){case`team`:{let r=t.slot===void 0?e:n.players().find(e=>e.slot===t.slot);return Ge(e,r,n.locked())&&n.move(r,t.team),!0}case`teamsLock`:return e.admin&&n.lock(t.locked),!0;case`autoTeams`:case`resetTeams`:{if(!e.admin)return!0;let r=t.action===`resetTeams`?We(n.players(),t.team).map(e=>({player:e,team:0})):Ue(n.players());for(let{player:i,team:a}of r){if(!n.current()||!n.players().includes(e)||!e.admin||t.action===`resetTeams`&&!n.stopped())break;n.players().includes(i)&&((t.action===`autoTeams`?i.team!==0:i.team===0)||n.move(i,a))}return!0}default:return!1}}function Je(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 Ye(e){return e===null||typeof e==`string`&&Array.from(e).length<=2&&!/[\p{Cc}\p{Cf}]/u.test(e)}function Xe(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 Ze(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:Xe(e.angle,e.textColor,e.colors))}var Qe=[15035990,5671397];function $e(e){return e===0||e===1||e===2}function et(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t}function tt(e){let{score:t,minutes:n,locked:r,kickRate:i}=e;return!et(t,99)||!et(n,99)||typeof r!=`boolean`||i!==void 0&&!et(i,6619135)?null:{score:t,minutes:n,locked:r,kickRate:i}}function nt(e,t){switch(e){case`typing`:return typeof t.active==`boolean`?{action:e,active:t.active}:null;case`directChat`:return typeof t.recipientId==`string`&&t.recipientId.length>0&&t.recipientId.length<=128&&typeof t.text==`string`&&t.text.trim()&&t.text.length<=200?{action:e,recipientId:t.recipientId,text:t.text}:null;case`chat`:return typeof t.text==`string`&&t.text.trim()&&t.text.length<=200?{action:e,text:t.text}:null;case`avatar`:return Ye(t.avatar)?{action:e,avatar:t.avatar}:null;case`autoTeams`:case`clearBans`:case`start`:case`stop`:return{action:e};case`teamsLock`:return typeof t.locked==`boolean`?{action:e,locked:t.locked}:null;case`resetTeams`:return t.team===void 0||t.team===1||t.team===2?{action:e,team:t.team}:null;case`team`:return $e(t.team)&&(t.slot===void 0||et(t.slot,31))?{action:e,team:t.team,slot:t.slot}:null;case`defaultStadium`:return typeof t.name==`string`?{action:e,name:t.name}:null;case`customStadium`:return typeof t.source==`string`?{action:e,source:t.source}:null;case`ban`:case`kick`:case`admin`:return et(t.slot,31)?{action:e,slot:t.slot}:null;case`mute`:return et(t.slot,31)&&typeof t.muted==`boolean`?{action:e,slot:t.slot,muted:t.muted}:null;case`teamColors`:{if(t.team!==1&&t.team!==2)return null;if(t.palette===null)return{action:e,team:t.team,palette:null};let n=t.palette;if(!n||typeof n!=`object`||Array.isArray(n))return null;let{angle:r,textColor:i,colors:a}=n;if(typeof r!=`number`||typeof i!=`number`||!Array.isArray(a))return null;try{return{action:e,team:t.team,palette:Xe(r,i,a)}}catch{return null}}case`pause`:return t.paused===void 0||typeof t.paused==`boolean`?{action:e,paused:t.paused}:null;case`kickRate`:return et(t.value,6619135)?{action:e,value:t.value}:null;case`settings`:{let n=tt(t);return n?{action:e,...n}:null}default:return null}}var rt=2,it=40;function at(e,t){return e!==t&&e-t>>>0<2147483648}function ot(e){if(e.byteLength!==10)throw Error(`Input length`);let t=new DataView(e);if(t.getUint8(0)!==1||t.getUint8(1)!==rt||t.getUint8(6)>31||t.getUint8(7))throw Error(`Input format`);return{seq:t.getUint32(2,!0),keys:t.getUint8(6),epoch:t.getUint16(8,!0)}}function st(e,t,n=0){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(40+r.length*it),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),o.setUint8(36,e.lastTouch?.slot??255),o.setUint8(37,e.lastTouch?.team??0),o.setUint8(38,e.goalTouch?.slot??255),o.setUint8(39,e.goalTouch?.team??0),r.forEach((t,n)=>{let r=t*18,i=40+n*it;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.setFloat64(i+4+t*8,e.discs[r+t],!0);o.setUint16(i+36,e.discs[r+15],!0),e.discs[r+12]>0&&o.setUint16(i+38,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,rt),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}function ct(e,t,n=0){if(!t.length)return[];let r=st(e,t[0],n),i=[r];for(let e=1;e<t.length;e++){let n=r.map(e=>e.slice(0));new DataView(n[0]).setUint32(36,t[e],!0),i.push(n)}return i}var lt=32768;function ut(e,t,n,r){let i=[...e.peers.values()].filter(e=>e.fast?.readyState===`open`&&e.fast.bufferedAmount<lt);if(!i.length)return;let a=ct(t,i.map(e=>r.acknowledgment(e.id)),n);for(let t=0;t<i.length;t++){let n=i[t],r=a[t],o=r.reduce((e,t)=>e+t.byteLength,0);if(!(n.fast?.readyState!==`open`||n.fast.bufferedAmount+o>lt))for(let t of r)e.fast(n,t)}}function dt(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 ft=class extends Error{status;retryAfterSeconds;constructor(e,t,n=null){super(e),this.status=t,this.retryAfterSeconds=n,this.name=`RoomAdmissionError`}};async function pt(e,t){let n=`Room creation failed (${e.status})`,r=e.status===429?e.headers.get(`Retry-After`):null,i=r&&/^\d+$/.test(r)&&Number.isSafeInteger(Number(r))?Number(r):null,a=t=>new ft(t,e.status,i),o=e.body?.getReader();if(!o)return a(n);let s=()=>{o.cancel().catch(()=>{})};t.addEventListener(`abort`,s,{once:!0});try{if(t.throwIfAborted(),e.status<400||e.status>=500||e.headers.get(`content-type`)?.split(`;`)[0].trim()!==`application/json`)return a(n);let r=new Uint8Array(2048),i=0;for(;;){let e=await o.read();if(t.throwIfAborted(),e.done)break;if(i+e.value.byteLength>r.length)return a(n);r.set(e.value,i),i+=e.value.byteLength}let s=Me(Re,JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(r.subarray(0,i))));return s.success?a(`${s.output.error.trim()} (${e.status})`):a(n)}catch{return t.throwIfAborted(),a(n)}finally{t.removeEventListener(`abort`,s),s(),o.releaseLock()}}var mt=class{stream;sequence=0;pending=[];lastSent=-1/0;phase=`lobby`;lastContactTick=-1/0;constructor(e=crypto.randomUUID()){this.stream=e}checkpoint(){return{stream:this.stream,sequence:this.sequence}}capture(e,t,n=this.phase){let r=(e.ballKicks??[]).map(n=>({kind:`kick`,sequence:++this.sequence,tick:e.tick,epoch:t,slot:n,x:e.data[0],y:e.data[1]})),i=e.ballContact;if(i&&!r.length&&e.phase===`playing`&&(e.tick<this.lastContactTick||e.tick-this.lastContactTick>=6)){let n=i.disc*18,a=i.disc>0&&e.data[n+5]===0&&e.stadium.goals.some(({p0:t,p1:r})=>[t,r].some(([t,r])=>Math.hypot(e.data[n]-t,e.data[n+1]-r)<=e.data[n+4]));r.push({kind:a?`post`:`impact`,sequence:++this.sequence,tick:e.tick,epoch:t,slot:0,x:e.data[0],y:e.data[1]}),this.lastContactTick=e.tick}if(e.phase!==n){let i=e.phase===`goal`?`goal`:e.phase===`playing`?`start`:e.phase===`finished`||e.phase===`lobby`&&n!==`finished`?`end`:void 0;i&&r.push({kind:i,sequence:++this.sequence,tick:e.tick,epoch:t,slot:0,x:0,y:0})}for(this.phase=e.phase,this.pending.push(...r);this.pending.length>8;){let e=this.pending.findIndex(e=>[`kick`,`impact`,`post`].includes(e.kind));this.pending.splice(Math.max(0,e),1)}return r}drain(e){if(!this.pending.length||e-this.lastSent<50)return;this.lastSent=e;let t=this.pending;return this.pending=[],{type:`match-sounds`,stream:this.stream,events:t}}};function ht(e,t){if(t)for(let n of e.peers.values())n.control?.readyState===`open`&&n.control.bufferedAmount<16384&&e.control(n,t)}function gt(e,t,n,r){let i=Math.ceil(2*Math.SQRT2*100/Math.max(.5,Math.min(10,r))),a=e+32;if(a*(2*t+a+2*n)*i*13>26e6)throw Error(`Stadium collision complexity exceeds the room budget`)}var _t=[[`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 vt(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid disc property update`);let t=e,n={};for(let e=0;e<_t.length;e++){let[r,,i,a]=_t[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 yt=`d340289099e582d13be0`,bt={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]/},xt={isSpaceSeparator(e){return typeof e==`string`&&bt.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||bt.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===``||bt.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)}},St,Ct,wt,Tt,Et,Dt,Ot,kt,At,jt=function(e,t){St=String(e),Ct=`start`,wt=[],Tt=0,Et=1,Dt=0,Ot=void 0,kt=void 0,At=void 0;do Ot=Rt(),Kt[Ct]();while(Ot.type!==`eof`);return typeof t==`function`?Mt({"":At},``,t):At};function Mt(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=Mt(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=Mt(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 Nt,Pt,Ft,It,Lt;function Rt(){for(Nt=`default`,Pt=``,Ft=!1,It=1;;){Lt=zt();let e=Bt[Nt]();if(e)return e}}function zt(){if(St[Tt])return String.fromCodePoint(St.codePointAt(Tt))}function H(){let e=zt();return e===`
|
|
2
|
+
`?(Et++,Dt=0):e?Dt+=e.length:Dt++,e&&(Tt+=e.length),e}var Bt={default(){switch(Lt){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
|
|
3
|
+
`:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),Nt=`comment`;return;case void 0:return H(),Vt(`eof`)}if(xt.isSpaceSeparator(Lt)){H();return}return Bt[Ct]()},comment(){switch(Lt){case`*`:H(),Nt=`multiLineComment`;return;case`/`:H(),Nt=`singleLineComment`;return}throw Yt(H())},multiLineComment(){switch(Lt){case`*`:H(),Nt=`multiLineCommentAsterisk`;return;case void 0:throw Yt(H())}H()},multiLineCommentAsterisk(){switch(Lt){case`*`:H();return;case`/`:H(),Nt=`default`;return;case void 0:throw Yt(H())}H(),Nt=`multiLineComment`},singleLineComment(){switch(Lt){case`
|
|
4
|
+
`:case`\r`:case`\u2028`:case`\u2029`:H(),Nt=`default`;return;case void 0:return H(),Vt(`eof`)}H()},value(){switch(Lt){case`{`:case`[`:return Vt(`punctuator`,H());case`n`:return H(),Ht(`ull`),Vt(`null`,null);case`t`:return H(),Ht(`rue`),Vt(`boolean`,!0);case`f`:return H(),Ht(`alse`),Vt(`boolean`,!1);case`-`:case`+`:H()===`-`&&(It=-1),Nt=`sign`;return;case`.`:Pt=H(),Nt=`decimalPointLeading`;return;case`0`:Pt=H(),Nt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Pt=H(),Nt=`decimalInteger`;return;case`I`:return H(),Ht(`nfinity`),Vt(`numeric`,1/0);case`N`:return H(),Ht(`aN`),Vt(`numeric`,NaN);case`"`:case`'`:Ft=H()===`"`,Pt=``,Nt=`string`;return}throw Yt(H())},identifierNameStartEscape(){if(Lt!==`u`)throw Yt(H());H();let e=Gt();switch(e){case`$`:case`_`:break;default:if(!xt.isIdStartChar(e))throw Zt()}Pt+=e,Nt=`identifierName`},identifierName(){switch(Lt){case`$`:case`_`:case``:case``:Pt+=H();return;case`\\`:H(),Nt=`identifierNameEscape`;return}if(xt.isIdContinueChar(Lt)){Pt+=H();return}return Vt(`identifier`,Pt)},identifierNameEscape(){if(Lt!==`u`)throw Yt(H());H();let e=Gt();switch(e){case`$`:case`_`:case``:case``:break;default:if(!xt.isIdContinueChar(e))throw Zt()}Pt+=e,Nt=`identifierName`},sign(){switch(Lt){case`.`:Pt=H(),Nt=`decimalPointLeading`;return;case`0`:Pt=H(),Nt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Pt=H(),Nt=`decimalInteger`;return;case`I`:return H(),Ht(`nfinity`),Vt(`numeric`,It*(1/0));case`N`:return H(),Ht(`aN`),Vt(`numeric`,NaN)}throw Yt(H())},zero(){switch(Lt){case`.`:Pt+=H(),Nt=`decimalPoint`;return;case`e`:case`E`:Pt+=H(),Nt=`decimalExponent`;return;case`x`:case`X`:Pt+=H(),Nt=`hexadecimal`;return}return Vt(`numeric`,It*0)},decimalInteger(){switch(Lt){case`.`:Pt+=H(),Nt=`decimalPoint`;return;case`e`:case`E`:Pt+=H(),Nt=`decimalExponent`;return}if(xt.isDigit(Lt)){Pt+=H();return}return Vt(`numeric`,It*Number(Pt))},decimalPointLeading(){if(xt.isDigit(Lt)){Pt+=H(),Nt=`decimalFraction`;return}throw Yt(H())},decimalPoint(){switch(Lt){case`e`:case`E`:Pt+=H(),Nt=`decimalExponent`;return}if(xt.isDigit(Lt)){Pt+=H(),Nt=`decimalFraction`;return}return Vt(`numeric`,It*Number(Pt))},decimalFraction(){switch(Lt){case`e`:case`E`:Pt+=H(),Nt=`decimalExponent`;return}if(xt.isDigit(Lt)){Pt+=H();return}return Vt(`numeric`,It*Number(Pt))},decimalExponent(){switch(Lt){case`+`:case`-`:Pt+=H(),Nt=`decimalExponentSign`;return}if(xt.isDigit(Lt)){Pt+=H(),Nt=`decimalExponentInteger`;return}throw Yt(H())},decimalExponentSign(){if(xt.isDigit(Lt)){Pt+=H(),Nt=`decimalExponentInteger`;return}throw Yt(H())},decimalExponentInteger(){if(xt.isDigit(Lt)){Pt+=H();return}return Vt(`numeric`,It*Number(Pt))},hexadecimal(){if(xt.isHexDigit(Lt)){Pt+=H(),Nt=`hexadecimalInteger`;return}throw Yt(H())},hexadecimalInteger(){if(xt.isHexDigit(Lt)){Pt+=H();return}return Vt(`numeric`,It*Number(Pt))},string(){switch(Lt){case`\\`:H(),Pt+=Ut();return;case`"`:if(Ft)return H(),Vt(`string`,Pt);Pt+=H();return;case`'`:if(!Ft)return H(),Vt(`string`,Pt);Pt+=H();return;case`
|
|
5
|
+
`:case`\r`:throw Yt(H());case`\u2028`:case`\u2029`:Qt(Lt);break;case void 0:throw Yt(H())}Pt+=H()},start(){switch(Lt){case`{`:case`[`:return Vt(`punctuator`,H())}Nt=`value`},beforePropertyName(){switch(Lt){case`$`:case`_`:Pt=H(),Nt=`identifierName`;return;case`\\`:H(),Nt=`identifierNameStartEscape`;return;case`}`:return Vt(`punctuator`,H());case`"`:case`'`:Ft=H()===`"`,Nt=`string`;return}if(xt.isIdStartChar(Lt)){Pt+=H(),Nt=`identifierName`;return}throw Yt(H())},afterPropertyName(){if(Lt===`:`)return Vt(`punctuator`,H());throw Yt(H())},beforePropertyValue(){Nt=`value`},afterPropertyValue(){switch(Lt){case`,`:case`}`:return Vt(`punctuator`,H())}throw Yt(H())},beforeArrayValue(){if(Lt===`]`)return Vt(`punctuator`,H());Nt=`value`},afterArrayValue(){switch(Lt){case`,`:case`]`:return Vt(`punctuator`,H())}throw Yt(H())},end(){throw Yt(H())}};function Vt(e,t){return{type:e,value:t,line:Et,column:Dt}}function Ht(e){for(let t of e){if(zt()!==t)throw Yt(H());H()}}function Ut(){switch(zt()){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(),xt.isDigit(zt()))throw Yt(H());return`\0`;case`x`:return H(),Wt();case`u`:return H(),Gt();case`
|
|
7
|
+
`:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),zt()===`
|
|
8
|
+
`&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw Yt(H());case void 0:throw Yt(H())}return H()}function Wt(){let e=``,t=zt();if(!xt.isHexDigit(t)||(e+=H(),t=zt(),!xt.isHexDigit(t)))throw Yt(H());return e+=H(),String.fromCodePoint(parseInt(e,16))}function Gt(){let e=``,t=4;for(;t-->0;){let t=zt();if(!xt.isHexDigit(t))throw Yt(H());e+=H()}return String.fromCodePoint(parseInt(e,16))}var Kt={start(){if(Ot.type===`eof`)throw Xt();qt()},beforePropertyName(){switch(Ot.type){case`identifier`:case`string`:kt=Ot.value,Ct=`afterPropertyName`;return;case`punctuator`:Jt();return;case`eof`:throw Xt()}},afterPropertyName(){if(Ot.type===`eof`)throw Xt();Ct=`beforePropertyValue`},beforePropertyValue(){if(Ot.type===`eof`)throw Xt();qt()},beforeArrayValue(){if(Ot.type===`eof`)throw Xt();if(Ot.type===`punctuator`&&Ot.value===`]`){Jt();return}qt()},afterPropertyValue(){if(Ot.type===`eof`)throw Xt();switch(Ot.value){case`,`:Ct=`beforePropertyName`;return;case`}`:Jt()}},afterArrayValue(){if(Ot.type===`eof`)throw Xt();switch(Ot.value){case`,`:Ct=`beforeArrayValue`;return;case`]`:Jt()}},end(){}};function qt(){let e;switch(Ot.type){case`punctuator`:switch(Ot.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=Ot.value}if(At===void 0)At=e;else{let t=wt[wt.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,kt,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)wt.push(e),Ct=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{let e=wt[wt.length-1];Ct=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}}function Jt(){wt.pop();let e=wt[wt.length-1];Ct=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function Yt(e){return en(e===void 0?`JSON5: invalid end of input at ${Et}:${Dt}`:`JSON5: invalid character '${$t(e)}' at ${Et}:${Dt}`)}function Xt(){return en(`JSON5: invalid end of input at ${Et}:${Dt}`)}function Zt(){return Dt-=5,en(`JSON5: invalid identifier character at ${Et}:${Dt}`)}function Qt(e){console.warn(`JSON5: '${$t(e)}' in strings is not valid ECMAScript; consider escaping`)}function $t(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 en(e){let t=SyntaxError(e);return t.lineNumber=Et,t.columnNumber=Dt,t}var tn={parse:jt,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(xt.isDigit(e[i+1])){r+=`\\x00`;continue}}if(n[a]){r+=n[a];continue}if(a<` `){let e=a.charCodeAt(0).toString(16);r+=`\\x`+(`00`+e).substring(e.length);continue}r+=a}let i=c||Object.keys(t).reduce((e,n)=>t[e]<t[n]?e:n);return r=r.replace(new RegExp(i,`g`),n[i]),i+r+i}function d(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);let t=i;i+=s;let n=a||Object.keys(e),o=[];for(let t of n){let n=l(t,e);if(n!==void 0){let e=f(t)+`:`;s!==``&&(e+=` `),e+=n,o.push(e)}}let c;if(o.length===0)c=`{}`;else{let e;if(s===``)e=o.join(`,`),c=`{`+e+`}`;else{let n=`,
|
|
9
9
|
`+i;e=o.join(n),c=`{
|
|
10
10
|
`+i+e+`,
|
|
11
|
-
`+t+`}`}}return r.pop(),i=t,c}function f(e){if(e.length===0)return u(e,!0);let t=String.fromCodePoint(e.codePointAt(0));if(!
|
|
11
|
+
`+t+`}`}}return r.pop(),i=t,c}function f(e){if(e.length===0)return u(e,!0);let t=String.fromCodePoint(e.codePointAt(0));if(!xt.isIdStartChar(t))return u(e,!0);for(let n=t.length;n<e.length;n++)if(!xt.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}}},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(`
|
|
14
|
+
`+t+`]`}return r.pop(),i=t,a}}},nn={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},rn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Expected an object`);return e},an=(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},on=(e,t=[0,0])=>{if(e===void 0)return[...t];if(!Array.isArray(e)||e.length!==2)throw Error(`Expected [x, y]`);return[an(e[0],0),an(e[1],0)]},sn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)throw Error(`Array limit: ${t}`);return e};function cn(e,t){return e===void 0?t:typeof e==`number`?an(e,t,-2147483648,4294967295)|0:sn(e,16).reduce((e,t)=>{if(typeof t!=`string`||!Object.hasOwn(nn,t))throw Error(`Unknown collision flag`);return e|nn[t]},0)}function ln(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(an(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 un=Object.fromEntries(Object.entries({root:`version physicsMode name width height maxViewWidth cameraFollow spawnDistance canBeStored kickOffReset bg traits vertexes segments goals discs planes joints redSpawnPoints blueSpawnPoints playerPhysics ballPhysics`,bg:`type width height kickOffRadius cornerRadius color`,vertexes:`trait x y bCoef cMask cGroup`,segments:`trait v0 v1 bCoef cMask cGroup curve curveF bias color vis`,discs:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color`,planes:`trait normal dist bCoef cMask cGroup`,goals:`trait p0 p1 team`,joints:`trait d0 d1 length strength color`,playerPhysics:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color acceleration kickingAcceleration kickingDamping kickStrength kickback`}).map(([e,t])=>[e,new Set(t.split(` `))])),dn=new Set([`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`,`playerPhysics`].flatMap(e=>[...un[e]]));function fn(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,un.root,`$`),r(e.bg,un.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,un[t],`$.${t}[${n}]`)})}if(r(e.ballPhysics,un.discs,`$.ballPhysics`),r(e.playerPhysics,un.playerPhysics,`$.playerPhysics`),e.traits&&typeof e.traits==`object`&&!Array.isArray(e.traits))for(let[t,i]of Object.entries(e.traits))r(i,dn,n(`$.traits`,t));return t}function pn(e){if(new TextEncoder().encode(e).length>262144)throw Error(`Stadium exceeds 256 KB`);let t=rn(tn.parse(e));if(t.physicsMode!==void 0&&t.physicsMode!==`stadium`&&t.physicsMode!==`substeps`)throw Error(`Invalid physics mode`);let n=t.physicsMode===`substeps`?`substeps`:`stadium`;if(t.version!==void 0&&t.version!==1)throw Error(`Unsupported stadium version`);let r=t.traits===void 0?{}:rn(t.traits),i=e=>{let t=rn(e);if(t.trait===void 0)return t;if(typeof t.trait!=`string`||!Object.hasOwn(r,t.trait))throw Error(`Unknown trait`);return{...rn(r[t.trait]),...t}},a=(e,t=!1)=>({pos:on(e.pos),speed:on(e.speed),gravity:on(e.gravity),radius:an(e.radius,10,.5,100),invMass:an(e.invMass,1,0,8192),damping:an(e.damping,.99,0,8192),bCoef:an(e.bCoef,.5,-1,8192),cGroup:cn(e.cGroup,t?193:63),cMask:cn(e.cMask,63),color:ln(e.color)}),o=sn(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=sn(t.vertexes,1024).map(e=>i(e)),c=[],l=[],u=fn(t);for(let e of s)c.push({a:[an(e.x,0),an(e.y,0)],b:[an(e.x,0),an(e.y,0)],bCoef:an(e.bCoef,1,-1,8192),cGroup:cn(e.cGroup,32),cMask:cn(e.cMask,63),bias:0,color:`transparent`,vis:!1});let d=[...c];for(let e of sn(t.segments,1024)){let t=i(e),n=an(t.v0,-1,0,s.length-1),r=an(t.v1,-1,0,s.length-1);if(!Number.isInteger(n)||!Number.isInteger(r))throw Error(`Vertex indices must be integers`);let a=[an(s[n].x,0),an(s[n].y,0)],o=[an(s[r].x,0),an(s[r].y,0)],u={bCoef:an(t.bCoef,1,-1,8192),cGroup:cn(t.cGroup,32),cMask:cn(t.cMask,63),bias:an(t.bias,0,-100,100),color:ln(t.color,`000000`),vis:t.vis!==!1},f=t.curveF===void 0?an(t.curve,0,-359,359):2*Math.atan2(1,an(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:an(f.acceleration,.1,-8192,8192),kickingAcceleration:an(f.kickingAcceleration,.07,-8192,8192),kickingDamping:an(f.kickingDamping,.96,0,8192),kickStrength:an(f.kickStrength,5,-8192,8192),kickback:an(f.kickback,0,-8192,8192)};gt(o.length,c.length,sn(t.planes,64).length+sn(t.joints,128).length,Math.min(p.radius,...o.map(e=>e.radius)));let m=t.bg===void 0?{}:rn(t.bg);if(m.type!==void 0&&m.type!==`grass`&&m.type!==`asphalt`&&m.type!==`none`)throw Error(`Unsupported stadium background type`);return{version:1,physicsMode:n,name:typeof t.name==`string`?t.name.slice(0,64):`Untitled stadium`,canBeStored:t.canBeStored!==!1,width:an(t.width,520,100,2048),height:an(t.height,300,80,2048),maxViewWidth:an(t.maxViewWidth,0,0,4096),cameraFollow:t.cameraFollow===`player`?`player`:`ball`,bg:{type:m.type===`grass`||m.type===`asphalt`?m.type:`none`,cornerRadius:an(m.cornerRadius,0,0,500),width:an(m.width,0,0,2048),height:an(m.height,0,0,2048),color:ln(m.color,`718C5A`),kickOffRadius:an(m.kickOffRadius,0,0,500)},discs:o,segments:c,arcs:l,colliders:d,player:p,spawnDistance:an(t.spawnDistance,200,0,1500),kickOffReset:t.kickOffReset===`full`?`full`:`partial`,redSpawnPoints:sn(t.redSpawnPoints,32).map(e=>on(e)),blueSpawnPoints:sn(t.blueSpawnPoints,32).map(e=>on(e)),warnings:u,planes:sn(t.planes,64).map(e=>{let t=i(e),n=on(t.normal);if(Math.hypot(...n)<1e-6)throw Error(`Plane normal is zero`);return{normal:n,dist:an(t.dist,0),bCoef:an(t.bCoef,1,-1,8192),cGroup:cn(t.cGroup,32),cMask:cn(t.cMask,63)}}),goals:sn(t.goals,16).map(e=>{let t=i(e);if(t.team!==`red`&&t.team!==`blue`)throw Error(`Invalid goal team`);let n=on(t.p0),r=on(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:sn(t.joints,128).map(e=>{let t=i(e),n=an(t.d0,-1,0,o.length-1),r=an(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]:on(t.length);return{d0:n,d1:r,min:an(s[0],0,0),max:an(s[1],0,0),strength:t.strength===void 0||t.strength===`rigid`?`rigid`:an(t.strength,0,-8192,8192),color:ln(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`]}:{cMask:[`ball`]}})),segments:[...[[0,1],[2,3],[0,4],[5,2],[1,6],[7,3],[4,8],[8,9],[9,5],[6,10],[10,11],[11,7]].map(([e,t],n)=>({v0:e,v1:t,cMask:[`ball`],color:n<6?`FFFFFF`:`C7D2CA`,bCoef:n<6?.8:.15})),{v0:12,v1:13,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:15,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:-180,vis:!1,cGroup:[`redKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:180,vis:!1,cGroup:[`blueKO`],cMask:[`red`,`blue`]}],planes:[{normal:[0,1],dist:-n-40},{normal:[0,-1],dist:-n-40},{normal:[1,0],dist:-t-50},{normal:[-1,0],dist:-t-50}],goals:[{p0:[-t,-70],p1:[-t,70],team:`red`},{p0:[t,-70],p1:[t,70],team:`blue`}],discs:[...[-t,t].flatMap(e=>[-70,70].map(t=>({pos:[e,t],radius:6,invMass:0,color:`FFFFFF`,bCoef:.5})))],ballPhysics:{radius:9,damping:.991,bCoef:.6},playerPhysics:{radius:15,acceleration:.11,damping:.96,kickStrength:5.5}},null,2)}var hn=60,gn=`ball2d-core/1/${yt}`,_n=class e{core;stadium;source=``;colors=[];tick=0;elapsed=0;ballKicks=[];ballContact;red=0;blue=0;phase=`lobby`;paused=!1;resumeTicks=0;countdown=0;kickoff=1;kickoffActive=!0;scoreLimit=5;timeLimit=300;lastGoal=0;lastTouch=null;goalTouch=null;kickRate=2;setKickRateLimit(e,t,n){this.kickRate=Je(e,t,n),this.core.kick_limits(this.kickRate&255,this.kickRate>>>8&255,this.kickRate>>>16)}constructor(e){this.core=e.exports}static async create(t,n){let r=t??await(await fetch(`/core.wasm?v=d340289099e582d13be0`,{signal:n})).arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,r))).map(e=>e.toString(16).padStart(2,`0`)).join(``)!==`105f5ccfb67900e11f5d8a36b86125d085a1b1ece88bb20e6690eb376b836fdb`)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.colors=[],this.core.physics_mode(+(this.stadium.physicsMode===`substeps`)),this.tick=0,this.elapsed=0,this.red=this.blue=0,this.lastTouch=this.goalTouch=null,this.phase=`lobby`,this.paused=!1,this.resumeTicks=0,this.countdown=0,this.kickoffActive=!0;for(let e of this.stadium.discs)this.add(e);for(let e=0;e<32;e++)this.add(this.stadium.player,e+1);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){this.lastTouch?.slot===e&&(this.lastTouch=null),this.goalTouch?.slot===e&&(this.goalTouch=null);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=vt(t),i=!1;for(let[t,a]of _t){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]));gt(this.stadium.discs.length,this.stadium.segments.length,this.stadium.planes.length+this.stadium.joints.length,t)}for(let[t,i]of _t){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||n===2?Qe[n-1]: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,this.lastTouch=null;let t=this.data;for(let n=0;n<this.stadium.discs.length;n++){let r=this.stadium.discs[n];(e||n===0||this.stadium.kickOffReset===`full`)&&(this.restoreDiscProperties(n,r),t[n*18]=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.goalTouch=null,this.phase=`playing`,this.paused=!1,this.resumeTicks=0,this.kickoff=1,this.countdown=0,this.resetPositions(!0))}stop(){this.lastTouch=this.goalTouch=null,this.phase=`lobby`,this.paused=!1,this.resumeTicks=0}setPaused(e){this.phase!==`lobby`&&(e=!!e,this.paused!==e&&(this.paused=e,this.resumeTicks=e?0:119))}finish(){this.phase=`finished`,this.countdown=300}canFinishDraw(){return this.phase===`playing`&&!this.paused&&this.timeLimit>0&&this.red===this.blue&&this.elapsed>=(this.timeLimit+60)*hn}finishDraw(){return this.canFinishDraw()?(this.finish(),!0):!1}step(){if(this.ballKicks.length=0,this.ballContact=void 0,this.tick++,this.paused||this.phase===`lobby`)return;if(this.resumeTicks>0){this.resumeTicks--;return}let e=this.data;if(this.core.step(),this.phase===`playing`){let t=this.core.ball_touch_slot();if(t>=0&&t<32){let n=e[this.index(t)*18+13];(n===1||n===2)&&(this.lastTouch={slot:t,team:n})}}let t=this.core.ball_contact_speed();t>=1&&(this.ballContact={disc:this.core.ball_contact_disc(),speed:t});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*hn&&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 n=this.core.goal_event();if(n===1||n===2){n===1?this.red++:this.blue++,this.kickoff=n===1?2:1,this.phase=`goal`,this.countdown=330,this.goalTouch=this.lastTouch?{...this.lastTouch}:null,this.lastGoal=this.tick;return}this.timeLimit>0&&this.elapsed>=this.timeLimit*hn&&this.red!==this.blue&&this.finish()}snapshot(){return{lastTouch:this.lastTouch?{...this.lastTouch}:null,goalTouch:this.goalTouch?{...this.goalTouch}:null,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,330)||!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 of[e.lastTouch,e.goalTouch])if(n!=null&&(typeof n!=`object`||!t(n.slot,31)||![1,2].includes(n.team)))throw Error(`Invalid goal attribution`);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]);gt(this.stadium.discs.length,this.stadium.segments.length,this.stadium.planes.length+this.stadium.joints.length,n),this.setKickRateLimit(e.kickRate&255,e.kickRate>>>8&255,e.kickRate>>>16),this.lastTouch=e.lastTouch?{...e.lastTouch}:null,this.goalTouch=e.goalTouch?{...e.goalTouch}:null,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]}},vn=n(`/`),yn;try{yn=vn(`worker_threads`),yn.Worker,yn.isMarkedAsUntransferable}catch{}var bn=Uint8Array,xn=Uint16Array,Sn=Int32Array,Cn=new bn([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]),wn=new bn([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]),Tn=new bn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),En=function(e,t){for(var n=new xn(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Sn(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}},yn=En(Cn,2),Dn=yn.b,On=yn.r;Dn[28]=258,On[258]=28;for(var kn=En(wn,0),An=kn.b,jn=kn.r,Mn=new xn(32768),Nn=0;Nn<32768;++Nn){var Pn=(Nn&43690)>>1|(Nn&21845)<<1;Pn=(Pn&52428)>>2|(Pn&13107)<<2,Pn=(Pn&61680)>>4|(Pn&3855)<<4,Mn[Nn]=((Pn&65280)>>8|(Pn&255)<<8)>>1}for(var Fn=(function(e,t,n){for(var r=e.length,i=0,a=new xn(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new xn(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new xn(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[Mn[d]>>c]=l}else for(s=new xn(r),i=0;i<r;++i)e[i]&&(s[i]=Mn[o[e[i]-1]++]>>15-e[i]);return s}),In=new bn(288),Nn=0;Nn<144;++Nn)In[Nn]=8;for(var Nn=144;Nn<256;++Nn)In[Nn]=9;for(var Nn=256;Nn<280;++Nn)In[Nn]=7;for(var Nn=280;Nn<288;++Nn)In[Nn]=8;for(var Ln=new bn(32),Nn=0;Nn<32;++Nn)Ln[Nn]=5;var Rn=Fn(In,9,0),zn=Fn(In,9,1),Bn=Fn(Ln,5,0),Vn=Fn(Ln,5,1),Hn=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Un=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Wn=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Gn=function(e){return(e+7)/8|0},Kn=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new bn(e.subarray(t,n))},qn=[`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`],Jn=function(e,t,n){var r=Error(t||qn[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Jn),!n)throw r;return r},Yn=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new bn(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new bn(i*3));var l=function(e){var t=n.length;if(e>t){var r=new bn(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=Un(e,d,1);var v=Un(e,d+1,3);if(d+=3,!v){var y=Gn(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Jn(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=zn,m=Vn,h=9,g=5;else if(v==2){var S=Un(e,d,31)+257,C=Un(e,d+10,15)+4,w=S+Un(e,d+5,31)+1;d+=14;for(var T=new bn(w),E=new bn(19),D=0;D<C;++D)E[Tn[D]]=Un(e,d+D*3,7);d+=C*3;for(var O=Hn(E),k=(1<<O)-1,A=Fn(E,O,1),D=0;D<w;){var j=A[Un(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+Un(e,d,3),d+=2,M=T[D-1]):y==17?(N=3+Un(e,d,7),d+=3):y==18&&(N=11+Un(e,d,127),d+=7);N--;)T[D++]=M}}var P=T.subarray(0,S),F=T.subarray(S);h=Hn(P),g=Hn(F),p=Fn(P,h,1),m=Fn(F,g,1)}else Jn(1);if(d>_){c&&Jn(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,L=(1<<g)-1,R=d;;R=d){var M=p[Wn(e,d)&I],z=M>>4;if(d+=M&15,d>_){c&&Jn(0);break}if(M||Jn(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=Cn[D];B=Un(e,d,(1<<V)-1)+Dn[D],d+=V}var ee=m[Wn(e,d)&L],te=ee>>4;ee||Jn(3),d+=ee&15;var F=An[te];if(te>3){var V=wn[te];F+=Wn(e,d)&(1<<V)-1,d+=V}if(d>_){c&&Jn(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&&Jn(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?Kn(n,0,f):n.subarray(0,f)},Xn=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Zn=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},Qn=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:ar,l:0};if(i==1){var o=new bn(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 xn(f+1),m=$n(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 bn(p),l:m}},$n=function(e,t,n){return e.s==-1?Math.max($n(e.l,t,n+1),$n(e.r,t,n+1)):t[e.s]=n},er=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new xn(++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}},tr=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},nr=function(e,t,n){var r=n.length,i=Gn(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},rr=function(e,t,n,r,i,a,o,s,c,l,u){Xn(t,u++,n),++i[256];for(var d=Qn(i,15),f=d.t,p=d.l,m=Qn(a,15),h=m.t,g=m.l,_=er(f),v=_.c,y=_.n,b=er(h),x=b.c,S=b.n,C=new xn(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=Qn(C,7),E=T.t,D=T.l,O=19;O>4&&!E[Tn[O-1]];--O);var k=l+5<<3,A=tr(i,In)+tr(a,Ln)+o,j=tr(i,f)+tr(a,h)+o+14+3*O+tr(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&k<=A&&k<=j)return nr(t,u,e.subarray(c,c+l));var M,N,P,F;if(Xn(t,u,1+(j<A)),u+=2,j<A){M=Fn(f,p,0),N=f,P=Fn(h,g,0),F=h;var I=Fn(E,D,0);Xn(t,u,y-257),Xn(t,u+5,S-1),Xn(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Xn(t,u+3*w,E[Tn[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;Xn(t,u,I[B]),u+=E[B],B>15&&(Xn(t,u,z[w]>>5&127),u+=z[w]>>12)}}else M=Rn,N=In,P=Bn,F=Ln;for(var w=0;w<s;++w){var V=r[w];if(V>255){var B=V>>18&31;Zn(t,u,M[B+257]),u+=N[B+257],B>7&&(Xn(t,u,V>>23&31),u+=Cn[B]);var ee=V&31;Zn(t,u,P[ee]),u+=F[ee],ee>3&&(Zn(t,u,V>>5&8191),u+=wn[ee])}else Zn(t,u,M[V]),u+=N[V]}return Zn(t,u,M[256]),u+N[256]},ir=new Sn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ar=new bn(0),or=function(e,t,n,r,i,a){var o=a.z||e.length,s=new bn(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=ir[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new xn(32768),g=a.h||new xn(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Sn(25e3),x=new xn(288),S=new xn(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=rr(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|On[P]<<18|jn[F];var ie=On[P]&31,ae=jn[F]&31;w+=Cn[ie]+wn[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=rr(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=nr(c,u+1,e.subarray(T,oe))}a.i=o}return Kn(s,0,r+Gn(u)+i)},sr=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new bn(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return or(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 cr(e,t){return sr(e,t||{},0,0)}var lr=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 bn(32768),this.p=new bn(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||Jn(5),this.d&&Jn(4),!this.p.length)this.p=e;else if(e.length){var t=new bn(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=Yn(this.p,this.s,this.o);this.ondata(Kn(n,t,this.s.b),this.d),this.o=Kn(n,this.s.b-32768),this.s.b=this.o.length,this.p=Kn(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),ur=typeof TextDecoder<`u`&&new TextDecoder;try{ur.decode(ar,{stream:!0})}catch{}var dr=32768,fr=dr*3,pr=102400,mr=62258,hr=1,gr=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t,_r=e=>Math.max(-32768,Math.min(32767,Math.round(e*4))),vr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function yr(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function br(e,t){if(typeof e!=`string`||e.length>Math.ceil(t/3)*4||!vr.test(e))throw Error(`Invalid turf payload`);let n=atob(e);if(n.length!==t)throw Error(`Invalid turf atlas length`);return Uint8Array.from(n,e=>e.charCodeAt(0))}function xr(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function Sr(e){if(typeof e!=`string`||e.length>Math.ceil(pr/3)*4||!vr.test(e))throw Error(`Invalid turf surface payload`);let t=atob(e);if(!t.length||t.length>pr)throw Error(`Invalid turf surface length`);let n=Uint8Array.from(t,e=>e.charCodeAt(0)),r=new Uint8Array(fr),i=0,a=!1,o=new lr((e,t)=>{if(i+e.length>fr)throw Error(`Expanded turf surface exceeds size limit`);r.set(e,i),i+=e.length,a=t});for(let e=0;e<n.length;e+=256)o.push(n.subarray(e,e+256),e+256>=n.length);if(!a||i!==fr)throw Error(`Invalid turf surface length`);return r}function Cr(e){let t=2166136261;for(let n of e)t=Math.imul(t^n&255,16777619),t=Math.imul(t^n>>>8,16777619);return t>>>0}function wr(e,t,n,r,i,a,o,s,c,[l,u,d]){let f=Math.max(0,Math.floor((Math.min(t,r)-a+s)*256/(2*s))),p=Math.min(255,Math.ceil((Math.max(t,r)+a+s)*256/(2*s))),m=Math.max(0,Math.floor((Math.min(n,i)-a+c)*128/(2*c))),h=Math.min(127,Math.ceil((Math.max(n,i)+a+c)*128/(2*c)));if(p<f||h<m)return!1;let g=r-t,_=i-n,v=g*g+_*_;if(!v)return!1;let y=Math.sqrt(v),b=a*a,x=!1;for(let r=m;r<=h;r++){let i=(2*r+1-128)*c/128;for(let a=f;a<=p;a++){let c=(2*a+1-256)*s/256,f=Math.abs(c),p=Math.abs(i);if(f>l||p>u||d>0&&f>l-d&&p>u-d&&(f-l+d)**2+(p-u+d)**2>d**2)continue;let m=Math.max(0,Math.min(1,((c-t)*g+(i-n)*_)/v)),h=c-t-g*m,S=i-n-_*m,C=h*h+S*S;if(C>=b)continue;let w=r*256+a,T=Math.round(y*o*(1-C/b)*(1-e[w]/65535)/32);if(!T)continue;let E=Math.min(mr,e[w]+T);E!==e[w]&&(e[w]=E,x=!0)}}return x}var Tr=class{atlas=new Uint16Array(dr);image=new Uint8Array(dr);surfaceRgb;surfaceImage=new Uint8Array(dr*4);surfaceDirty=!0;imageDirty=!0;digestDirty=!0;digestValue=Cr(this.atlas);previous=new Map;stadium;lastTick=-1;lastElapsed=-1;lastPhase=`lobby`;generation=0;revision=0;field=[0,0];halfWidthQ=0;halfHeightQ=0;grassWidthQ=0;grassHeightQ=0;cornerQ=0;get digest(){return this.digestDirty&&=(this.digestValue=Cr(this.atlas),!1),this.digestValue}get hasPressure(){let e=this.surfaceRgb;if(!e)return!1;for(let t=0;t<fr;t+=3)if(e[t]!==0)return!0;return!1}pixels(){if(this.imageDirty){for(let e=0;e<dr;e++)this.image[e]=Math.round(this.atlas[e]*255/65535);this.imageDirty=!1}return this.image}surfacePixels(){if(this.surfaceDirty||this.imageDirty){let e=this.pixels(),t=this.surfaceRgb;for(let n=0;n<dr;n++){let r=n*4,i=n*3;this.surfaceImage[r]=t?t[i]:0,this.surfaceImage[r+1]=t?t[i+1]:128,this.surfaceImage[r+2]=t?t[i+2]:128,this.surfaceImage[r+3]=e[n]}this.surfaceDirty=!1}return this.surfaceImage}reset(e,t,n){this.atlas.fill(0),this.surfaceRgb=void 0,this.surfaceDirty=!0,this.previous.clear(),this.generation=this.generation+1>>>0,this.halfWidthQ=e,this.halfHeightQ=t,[this.grassWidthQ,this.grassHeightQ,this.cornerQ]=n,this.field=[e/4,t/4],this.imageDirty=!0,this.digestDirty=!0,this.revision++}capture(e){let t=e.stadium,n=Math.round((Math.max(t.width,t.bg.width)+32)*4),r=Math.round((Math.max(t.height,t.bg.height)+32)*4),i=Math.round(t.bg.width*4),a=Math.round(t.bg.height*4),o=Math.round(Math.min(t.bg.cornerRadius??0,t.bg.width,t.bg.height)*4);if(!gr(n,65535)||!gr(r,65535)||n===0||r===0||!gr(i,n)||!gr(a,r)||!gr(o,Math.min(i,a)))throw Error(`Invalid turf field`);if((this.stadium!==t||this.lastTick>e.tick||this.lastElapsed>0&&e.elapsed<this.lastElapsed||e.phase===`lobby`&&this.lastPhase!==`lobby`||this.halfWidthQ!==n||this.halfHeightQ!==r||this.grassWidthQ!==i||this.grassHeightQ!==a||this.cornerQ!==o)&&this.reset(n,r,[i,a,o]),this.stadium=t,this.lastTick=e.tick,this.lastElapsed=e.elapsed,this.lastPhase=e.phase,e.phase!==`playing`||e.paused||e.resumeTicks||t.bg.type!==`grass`){this.previous.clear();return}if(e.tick%6!=0)return;let s=new Set,c=e.data,l=0;for(let e=0;e<c.length/18;e++){let t=e*18;if(e!==0&&(!c[t+12]||c[t+13]===0))continue;let u=c[t],d=c[t+1],f=c[t+4];if(!Number.isFinite(u)||!Number.isFinite(d)||!Number.isFinite(f))continue;s.add(e);let p=this.previous.get(e);if(p&&l<33){let t=Math.hypot(u-p[0],d-p[1]);t>.1&&t<60&&(l++,wr(this.atlas,_r(p[0]),_r(p[1]),_r(u),_r(d),Math.max(1,Math.min(96,Math.round(Math.max(3.5,f*.78)*4))),e===0?31:255,n,r,[i,a,o])&&(this.imageDirty=!0,this.surfaceDirty=!0,this.digestDirty=!0,this.revision++))}this.previous.set(e,[u,d])}for(let e of this.previous.keys())s.has(e)||this.previous.delete(e)}seed(e){if(!(e instanceof Uint8Array)||e.length!==dr)throw Error(`Invalid turf seed`);for(let t=0;t<dr;t++)this.atlas[t]=Math.min(mr,Math.round(e[t]*65535/255));this.surfaceRgb=void 0,this.surfaceDirty=!0,this.imageDirty=!0,this.digestDirty=!0,this.revision++}seedSurface(e){if(!(e instanceof Uint8Array)||e.length!==dr*4)throw Error(`Invalid turf surface seed`);let t=new Uint8Array(fr);for(let n=0;n<dr;n++){let r=n*4,i=n*3;t[i]=e[r],t[i+1]=e[r+1],t[i+2]=e[r+2],this.atlas[n]=Math.min(mr,Math.round(e[r+3]*65535/255))}this.surfaceRgb=t,this.surfaceDirty=!0,this.imageDirty=!0,this.digestDirty=!0,this.revision++}checkpoint(){if(!this.halfWidthQ||!this.halfHeightQ)throw Error(`Turf field is not initialized`);let e=new Uint8Array(dr*2),t=new DataView(e.buffer);for(let e=0;e<dr;e++)t.setUint16(e*2,this.atlas[e],!0);let n={type:`turf-checkpoint`,version:hr,generation:this.generation,halfWidthQ:this.halfWidthQ,halfHeightQ:this.halfHeightQ,grassWidthQ:this.grassWidthQ,grassHeightQ:this.grassHeightQ,cornerQ:this.cornerQ,digest:this.digest,atlas:yr(e)};if(this.surfaceRgb){let e=cr(this.surfaceRgb,{level:1});if(e.length>pr)throw Error(`Compressed turf surface exceeds size limit`);n.surface=yr(e),n.surfaceDigest=xr(this.surfaceRgb)}return n}restore(e){if(!e||typeof e!=`object`)throw Error(`Invalid turf checkpoint`);let t=e;if(t.type!==`turf-checkpoint`||t.version!==hr||!gr(t.generation,4294967295)||!gr(t.halfWidthQ,65535)||!gr(t.halfHeightQ,65535)||!t.halfWidthQ||!t.halfHeightQ||!gr(t.grassWidthQ,t.halfWidthQ)||!gr(t.grassHeightQ,t.halfHeightQ)||!gr(t.cornerQ,Math.min(t.grassWidthQ,t.grassHeightQ))||!gr(t.digest,4294967295))throw Error(`Invalid turf checkpoint`);let n=br(t.atlas,dr*2),r=new DataView(n.buffer,n.byteOffset,n.byteLength),i=new Uint16Array(dr);for(let e=0;e<dr;e++)if(i[e]=r.getUint16(e*2,!0),i[e]>mr)throw Error(`Invalid turf wear`);if(Cr(i)!==t.digest)throw Error(`Turf checksum mismatch`);if(t.surface===void 0!=(t.surfaceDigest===void 0))throw Error(`Invalid turf surface envelope`);let a;if(t.surface!==void 0){if(!gr(t.surfaceDigest,4294967295))throw Error(`Invalid turf surface checksum`);if(a=Sr(t.surface),xr(a)!==t.surfaceDigest)throw Error(`Turf surface checksum mismatch`)}this.generation>t.generation&&this.generation-t.generation<2147483648||(this.atlas=i,this.surfaceRgb=a,this.surfaceDirty=!0,this.digestValue=t.digest,this.digestDirty=!1,this.generation=t.generation,this.halfWidthQ=t.halfWidthQ,this.halfHeightQ=t.halfHeightQ,this.grassWidthQ=t.grassWidthQ,this.grassHeightQ=t.grassHeightQ,this.cornerQ=t.cornerQ,this.field=[t.halfWidthQ/4,t.halfHeightQ/4],this.previous.clear(),this.imageDirty=!0,this.revision++)}};function Er(e){if(e===void 0)return;if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Geolocation must contain a country code, latitude and longitude.`);let{code:t,lat:n,lon:r}=e;if(typeof t!=`string`||!/^[a-z]{2}$/i.test(t)||typeof n!=`number`||!Number.isFinite(n)||n<-90||n>90||typeof r!=`number`||!Number.isFinite(r)||r<-180||r>180)throw TypeError(`Geolocation must contain a country code, latitude and longitude.`);return{code:t.toUpperCase(),lat:n===0?0:n,lon:r===0?0:r}}var Dr=new Set([`noPlayer`,`playerName`,`roomName`,`maxPlayers`,`password`,`public`,`stadium`,`geo`]);function Or(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(!Dr.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 a Ball2D stadium 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,...t.geo===void 0?{}:{geo:Er(t.geo)}}}function kr(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 Ar(e){let t=kr(e);if(!t)throw Error(`Invalid room code`);return`/r/${t}`}var jr=[`normal`,`bold`,`italic`,`small`,`small-bold`,`small-italic`];function Mr(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&&!jr.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 Nr(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 Pr(e){let t=new URL(e.assets);if(![`http:`,`https:`,`ball2d:`].includes(t.protocol)||!t.host||t.username||t.password||t.pathname!==`/`||t.search||t.hash)throw Error(`Expected a root asset origin`);let n=Nr(e.service),r=Nr(e.public);function i(e,t){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||[...e].some(e=>e.charCodeAt(0)<=32||e.charCodeAt(0)===127))throw Error(`Expected an absolute application path`);let n=decodeURIComponent(e.split(/[?#]/,1)[0]);if(n.includes(`\\`)||n.includes(`//`)||n.split(`/`).some(e=>e===`.`||e===`..`))throw Error(`Ambiguous application path`);let r=new URL(e,t),i=new URL(t);if(r.protocol!==i.protocol||r.host!==i.host||r.username||r.password)throw Error(`Application path escaped its runtime origin`);return r}return{serviceOrigin:n,publicOrigin:r,asset:e=>i(e,t.href),public:e=>i(e,r),api:e=>{let t=i(e,n);if(!t.pathname.startsWith(`${ne}/`)||t.hash)throw Error(`Expected a versioned application API path`);return t}}}function Fr(){let e=location.origin;return Pr({assets:e,service:e,public:e})}var Ir=null,Lr=null;function Rr(e){if(Object.keys(e).length!==2||e.bundlePolicy!==`max-bundle`)return!1;let t=e.iceServers;if(t?.length!==1)return!1;let n=t[0];return Object.keys(n).length===1&&n.urls===`stun:stun.l.google.com:19302`}function zr(){Lr?.removeEventListener(`pagehide`,Br),Lr=null}function Br(){let e=Ir;Ir=null,zr(),e?.close()}function Vr(e){let t={get label(){return e.label},get readyState(){return e.readyState},get ordered(){return e.ordered},get maxRetransmits(){return e.maxRetransmits},get maxPacketLifeTime(){return e.maxPacketLifeTime},get bufferedAmount(){return e.bufferedAmount},onopen:null,onclose:null,onmessage:null,send(t){e.send(t)},close(){e.close()}};return e.binaryType=`arraybuffer`,e.onopen=()=>t.onopen?.(),e.onclose=()=>t.onclose?.(),e.onmessage=({data:e})=>t.onmessage?.({data:e}),t}function Hr(e,t){let n={get connectionState(){return e.connectionState},get iceConnectionState(){return e.iceConnectionState},get signalingState(){return e.signalingState},get localDescription(){return e.localDescription},get remoteDescription(){return e.remoteDescription},onicecandidate:null,ondatachannel:null,onconnectionstatechange:null,oniceconnectionstatechange:null,createDataChannel:(t,n)=>Vr(e.createDataChannel(t,n)),createOffer:t=>e.createOffer(t),createAnswer:()=>e.createAnswer(),setLocalDescription:t=>e.setLocalDescription(t),setRemoteDescription:t=>e.setRemoteDescription(t),addIceCandidate:t=>e.addIceCandidate(t),getStats:()=>e.getStats(),close:t};return e.onicecandidate=({candidate:e})=>n.onicecandidate?.({candidate:e??null}),e.ondatachannel=({channel:e})=>n.ondatachannel?.({channel:Vr(e)}),e.onconnectionstatechange=()=>n.onconnectionstatechange?.(),e.oniceconnectionstatechange=()=>n.oniceconnectionstatechange?.(),n}function Ur(e){let t;return Ir&&Rr(e)?(t=Ir,Ir=null,zr(),t.signalingState===`closed`&&(t=new RTCPeerConnection(e))):t=new RTCPeerConnection(e),Hr(t,()=>t.close())}function Wr(e=Fr()){return{serviceOrigin:e.serviceOrigin,createWebSocket:(e,t)=>new WebSocket(e,t),createPeerConnection:Ur}}var Gr=[[`classic`,`Classic`],[`easy`,`Easy`],[`small`,`Small`],[`big`,`Big`],[`rounded`,`Rounded`],[`big_easy`,`Big Easy`],[`big_rounded`,`Big Rounded`],[`huge`,`Huge`],[`asphalt`,`Asphalt`],[`meadow`,`Meadow`],[`training_green`,`Training Green`],[`courtyard`,`Courtyard`],[`street_five`,`Street Five`],[`asphalt_arena`,`Asphalt Arena`]];function Kr(e){let t=new Map;return async n=>{let r=Gr.find(([e,t])=>e===n||t===n);if(!r)throw Error(`Unknown default stadium`);let i=t.get(r[0]);return i||(i=(async()=>{let t=await e(`/stadiums/${r[0]}.ball2dstadium`);if(!t.ok)throw Error(`Could not load stadium`);let n=await t.text();return pn(n),n})(),t.set(r[0],i),i.catch(()=>t.delete(r[0]))),i}}function qr(e=Fr()){let t=Wr(e),n=(e,t)=>fetch(e,t);return{network:t,publicOrigin:e.publicOrigin,request:n,loadEngine:async t=>{let r=await n(e.asset(`/core.wasm?v=${yt}`),{signal:t});if(!r.ok)throw Error(`Could not load bundled physics engine`);return _n.create(await r.arrayBuffer(),t)},loadStadium:Kr(t=>n(e.asset(t)))}}var Jr={message:{burst:240,perSecond:160},action:{burst:12,perSecond:6},chat:{burst:4,perSecond:1},typing:{burst:6,perSecond:3},feedback:{burst:1,perSecond:.5}},Yr=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}=Jr[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()}},Xr=33554432,Zr=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function Qr(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function $r(e){if(e.length>33554432)throw Error(`Replay exceeds 32 MB`);let t=cr(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,Qr(e),!0),n.set(t,16),n}function ei(e){if(typeof e==`string`){if(Zr.encode(e).length>33554432)throw Error(`Replay exceeds 32 MB`);return Zr.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 lr((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||Qr(i)!==n.getUint32(12,!0))throw Error(`Compressed replay integrity failure`);return i}var ti=[`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`,`finishDraw`],ni=new TextEncoder,ri=new TextDecoder(`utf-8`,{fatal:!0});function ii(e){return $r(ai(e))}function ai(e){let{commands:t,...n}=e,r=0,i=e.checkpoints.map(e=>{let t=e.state.discs;if(!Array.isArray(t)||t.length>1728||t.some(e=>!Number.isFinite(e)))throw Error(`Invalid checkpoint discs`);return r+=t.length*8,{...e,state:{...e.state,discs:t.length}}});if(i.length>721)throw Error(`Too many replay checkpoints`);let a=ni.encode(JSON.stringify({...n,checkpoints:i}));if(t.length>5e5||a.length+16>33554432)throw Error(`Replay exceeds bounds`);let o=t.length*12+t.filter(e=>e.kind===`disc`).length*106,s=new Uint8Array(Math.min(Xr,o)),c=new DataView(s.buffer),l=e=>{if(u+e>s.length)throw Error(`Replay exceeds bounds`)},u=0,d=e.initial.tick,f=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`Invalid replay integer`);do{l(1);let t=Math.floor(e/128);s[u++]=e%128|(t?128:0),e=t}while(e)};for(let e of t){let t=ti.indexOf(e.kind);if((e.kind===`join`||e.kind===`finishDraw`)&&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)||e.kind===`finishDraw`&&e.slot!==0)throw Error(`Invalid replay command`);if(f(e.tick-d),l(1),s[u++]=t,f(e.slot),f(e.value),e.kind===`disc`){let t=vt(e.properties),n=0;_t.forEach(([e],r)=>{t[e]!==void 0&&(n|=1<<r)}),f(n);for(let[e]of _t){let n=t[e];n!==void 0&&(l(8),c.setFloat64(u,n,!0),u+=8)}}d=e.tick}let p=16+a.length+r+u;if(p>33554432)throw Error(`Replay exceeds 32 MB`);let m=new Uint8Array(p),h=new DataView(m.buffer);m.set([66,50,68,49,1,0,0,0]),h.setUint32(8,a.length,!0),h.setUint32(12,t.length,!0),m.set(a,16);let g=16+a.length;for(let t of e.checkpoints)for(let e of t.state.discs)h.setFloat64(g,e,!0),g+=8;return m.set(s.subarray(0,u),g),m}function oi(e){let t=ei(e);if(t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==49){if(t[0]===66&&t[1]===50&&t[2]===68)throw Error(`Unsupported packed replay format`);return JSON.parse(ri.decode(t))}if(t.length<16||t[4]!==1||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(ri.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(!Array.isArray(a.checkpoints)||a.checkpoints.length>721)throw Error(`Invalid packed checkpoints`);let c=0;for(let e of a.checkpoints){let t=e?.state?.discs;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>1728)throw Error(`Invalid checkpoint disc count`);c+=t*8}if(c>t.length-o-i*3)throw Error(`Truncated checkpoint discs`);for(let e of a.checkpoints){let t=e.state.discs,r=Array(t);for(let e=0;e<t;e++){let t=n.getFloat64(o,!0);if(!Number.isFinite(t))throw Error(`Nonfinite checkpoint disc`);r[e]=t,o+=8}e.state.discs=r}let l=()=>{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+=l(),!Number.isSafeInteger(s)||o>=t.length)throw Error(`Invalid replay tick`);let e=ti[t[o++]];if(!e)throw Error(`Unknown replay command`);let r=l(),i=l();if(e===`disc`){let c=l();if(c>8191)throw Error(`Invalid disc property mask`);let u={};_t.forEach(([e],r)=>{if(c&1<<r){if(o+8>t.length)throw Error(`Truncated disc properties`);u[e]=n.getFloat64(o,!0),o+=8}}),a.commands.push({tick:s,kind:e,slot:r,value:i,properties:vt(u)});continue}a.commands.push({tick:s,kind:e,slot:r,value:i})}if(o!==t.length)throw Error(`Trailing replay command data`);return a}function si(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 ci(e,t){switch(t.kind){case`disc`:if(!t.properties)throw Error(`Missing replay disc properties`);e.applyDiscProperties(t.slot,t.properties);break;case`input`:e.input(t.slot,t.value);break;case`join`:e.joinPlayer(t.slot);break;case`team`:e.setTeam(t.slot,t.value);break;case`start`:e.start();break;case`stop`:e.stop();break;case`finishDraw`:e.finishDraw();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 li=class{replay;playerOrder=[];lastInputs=new Map;bytes=0;full=!1;canRecord(e){return!this.full&&e.tick-this.replay.initial.tick<hn*3600}constructor(e,t=[],n=[null,null]){let r=e.snapshot();this.playerOrder=t.map(e=>e.slot),this.replay={magic:`B2DR`,version:1,engine:gn,stadium:e.source,initial:r,commands:[],checkpoints:[],roster:t.map(e=>({...e,tick:r.tick})),styles:[{tick:r.tick,teams:Ze(n)}],orders:[{tick:r.tick,slots:[...this.playerOrder]}],end:r.tick,finalHash:si(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:Ze(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:vt(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%(hn*5)==0){let t=e.snapshot(),n={tick:e.tick,state:t,hash:si(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=si(e.snapshot()),ai(this.replay)}finish(e){return this.replay.end=e.tick,this.replay.finalHash=si(e.snapshot()),new Blob([ii(this.replay)],{type:`application/x-ball2d-replay`})}};async function ui(e){if(e.size>33554432)throw Error(`Replay exceeds 32 MB`);return di(await e.arrayBuffer())}function di(e){let t=oi(e);if(t.magic!==`B2DR`||t.version!==1||t.engine!==gn)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>hn*3600)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`,`finishDraw`].includes(e.kind)||!Number.isInteger(e.slot)||e.slot<0||e.slot>(e.kind===`disc`?95:31)||e.kind===`finishDraw`&&e.slot!==0||!Number.isInteger(e.value)||e.value<0||e.value>(e.kind===`finishDraw`||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`?1:31))throw Error(`Invalid replay command`);e.kind===`disc`&&(e.properties=vt(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>=32||e.name!==null&&(typeof e.name!=`string`||e.name.length>24)||e.avatar!==void 0&&!Ye(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=Ze(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>=32)||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 fi=class{engine;onRecordingComplete;recorder;closed=!1;completing=!1;constructor(e,t){this.engine=e,this.onRecordingComplete=t}assertOpen(){if(this.closed)throw Error(`Room is closed`)}get recording(){return!!this.recorder}command(e,t=0,n=0,r){this.assertOpen();let i={tick:this.engine.tick,kind:e,slot:t,value:n};r&&(i.properties=r),this.recorder&&(!this.recorder.canRecord(this.engine)||!this.recorder.command(i))&&this.finishRecording(`Recording limit reached`),this.assertOpen(),ci(this.engine,i)}checkRecordingLimit(){this.recorder&&!this.recorder.canRecord(this.engine)&&this.finishRecording(`Recording limit reached`)}step(){this.assertOpen(),this.engine.step(),this.recorder?.step(this.engine)}recordPlayer(e,t,n){this.recorder?.player(this.engine.tick,e,t,n)}recordStyles(e){this.recorder?.style(this.engine.tick,e)}recordOrder(e){this.recorder?.order(this.engine.tick,e)}startRecording(e,t){if(this.assertOpen(),this.completing)throw Error(`Recording completion is in progress`);if(this.recorder)throw Error(`Recording is already active`);this.recorder=new li(this.engine,e,t)}stopRecording(){if(!this.recorder)return null;let e=this.recorder.pack(this.engine);return this.recorder=void 0,e}finishRecording(e){let t=this.stopRecording();if(t){this.completing=!0;try{this.onRecordingComplete(t,e)}finally{this.completing=!1}}}discardRecording(){this.recorder=void 0}close(e=`Room closed`){this.closed||(this.closed=!0,this.finishRecording(e))}},pi=class{match;now;peers=new Map;closed=!1;constructor(e,t=()=>performance.now()){this.match=e,this.now=t}accept(e,t,n,r){if(this.closed)return;let i=ot(n);if(i.epoch!==r)return;let a=this.peers.get(e);if(!a||at(i.seq,a.seq))return this.peers.set(e,{seq:i.seq,received:this.now(),keys:i.keys}),this.match.command(`input`,t,i.keys),i.keys!==(a?.keys??0)}expire(e,t,n=this.now()){if(this.closed)return;let r=this.peers.get(e),i=this.match.engine;r&&n-r.received>250&&i.data[i.index(t)*18+14]!==0&&this.match.command(`input`,t,0)}acknowledgment(e){return this.peers.get(e)?.seq??0}remove(e){this.peers.delete(e)}reset(){this.peers.clear()}close(){this.closed=!0,this.reset()}},mi=je(Te({id:je(ke(),he(1)),hostId:je(ke(),he(1)),role:De([`host`,`guest`]),generation:Ee(Ne),requireVerification:Ee(Ae()),locked:Ee(Ae())}),ue(e=>e.role===`host`==(e.id===e.hostId))),hi=Te({roomId:ke(),siteKey:je(ke(),ge(/^[A-Za-z0-9_-]{1,100}$/))}),gi=524288,_i=16384,vi=12;function yi(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>gi)throw Error(`Control message exceeds 512 KB`);if(r.length<=_i)return[n];let i=Math.ceil(r.length/_i),a=[];for(let e=0;e<i;e++){let n=r.subarray(e*_i,(e+1)*_i),o=new ArrayBuffer(vi+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,vi).set(n),a.push(o)}return a}var bi=class{partial;push(e,t=performance.now()){if(typeof e==`string`){if(this.partial||new TextEncoder().encode(e).length>_i)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-vi,o.bytes>gi)throw Error(`Control size limit`);if(o.parts.push(new Uint8Array(e.slice(vi))),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))}},xi=class{admission;assembler;constructor(e){this.admission=e}clear(){this.assembler=void 0}read(e){if(typeof e!=`string`&&!(e instanceof ArrayBuffer))throw Error(`Invalid control type`);let t=typeof e!=`string`||new TextEncoder().encode(e).length>4096,n=this.admission.fromGuest();if(n&&t&&!this.admission.canUploadStadium())throw Error(`Guest control size or permission`);this.assembler??=new bi;let r=this.assembler.push(e);if(r!==void 0&&n&&t&&(!r||typeof r!=`object`||!(`type`in r)||r.type!==`action`||!(`action`in r)||r.action!==`customStadium`))throw Error(`Invalid bulk action`);return r}},Si=e=>e?.match(/(?:^|\r?\n)a=ice-ufrag:([^\s]+)/)?.[1],Ci=e=>e.usernameFragment??e.candidate?.match(/(?:^| )ufrag ([^ ]+)/)?.[1];function wi(e){let t=e.pc.localDescription;if(!t?.sdp)throw Error(`Local peer description is unavailable`);return t.sdp}function Ti(e,t,n){if(n()){if(e.candidates.length>=128)throw Error(`Too many pending ICE candidates`);e.candidates.push(t)}}async function Ei(e,t){let n=e.candidates.splice(0);for(let r of n){if(!t.current())return;if(!t.versioned||e.remoteIceUfrag&&Ci(r)===e.remoteIceUfrag)try{await e.pc.addIceCandidate(r)}catch{}}}async function Di(e,t,n){let r=await e.pc.createOffer(n);return!t.current()||(e.localIceUfrag=Si(r.sdp),await e.pc.setLocalDescription(r),!t.current())?!1:(t.publish({type:`offer`,sdp:wi(e)}),!0)}async function Oi(e,t,n){if(await e.pc.setRemoteDescription({type:`offer`,sdp:t}),!n.current()||(await Ei(e,n),!n.current()))return;let r=await e.pc.createAnswer();n.current()&&(e.localIceUfrag=Si(r.sdp),await e.pc.setLocalDescription(r),n.current()&&n.publish({type:`answer`,sdp:wi(e)}))}async function ki(e,t,n){return await e.pc.setRemoteDescription({type:`answer`,sdp:t}),n.current()?(await Ei(e,n),!0):!1}async function Ai(e,t,n){if(!(n.versioned&&(!Ci(t)||e.remoteIceUfrag&&Ci(t)!==e.remoteIceUfrag))){if(!e.pc.remoteDescription)Ti(e,t,n.current);else try{await e.pc.addIceCandidate(t)}catch{Ti(e,t,n.current)}}}var ji=class extends Error{},Mi=class{messages;unconfirmed;sequence=0;pending;constructor(e,t=e=>Error(e)){this.messages=e,this.unconfirmed=t}matches(e){return!!this.pending&&this.pending.id===e}start(e){return this.pending?Promise.reject(Error(this.messages.pending)):new Promise((t,n)=>{let r=++this.sequence,i=setTimeout(()=>this.fail(this.messages.timeout),1e4);this.pending={id:r,resolve:t,reject:n,timer:i};try{e(r)}catch{this.fail(this.messages.send)}})}resolve(e){this.take()?.resolve(e)}fail(e,t=!1){let n=this.take();n&&n.reject(t?Error(e):this.unconfirmed(e))}take(){let e=this.pending;return this.pending=void 0,e&&clearTimeout(e.timer),e}},Ni=class{available;send;verification=null;verificationRequest=new Mi({pending:`A verification update is already pending.`,timeout:`Verification update was not confirmed.`,send:`Verification update could not be sent.`},e=>(this.verification=null,Error(e)));passwordRequest=new Mi({pending:`A password update is already pending.`,timeout:`Password update was not confirmed.`,send:`Password update could not be sent.`});banRequest=new Mi({pending:`A ban operation is already pending.`,timeout:`Ban operation was not confirmed.`,send:`Ban operation could not be sent.`},e=>new ji(e));constructor(e,t){this.available=e,this.send=t}setRequireVerification(e){return typeof e==`boolean`?this.available()?this.verificationRequest.start(t=>this.send({type:`setVerification`,required:e,requestId:t})):Promise.reject(Error(`An active room-owner connection is required.`)):Promise.reject(Error(`Expected a boolean.`))}setPassword(e){return e!==null&&(typeof e!=`string`||e.length>64)?Promise.reject(Error(`Password must contain at most 64 characters.`)):this.available()?this.passwordRequest.start(t=>this.send({type:`setPassword`,requestId:t,password:e??``})):Promise.reject(Error(`An active room-owner connection is required.`))}updateBan(e,t,n){return this.available()?this.banRequest.start(r=>this.send({type:e,id:t,requestId:r,...e===`ban`&&n!==void 0?{reason:n}:{}})):Promise.reject(Error(`An active room-owner connection is required.`))}accept(e){if(e.type===`verificationUpdated`&&this.verificationRequest.matches(e.requestId))return e.ok!==!0||typeof e.required!=`boolean`?this.verificationRequest.fail(typeof e.error==`string`?e.error:`Verification update failed.`,e.ok===!1):(this.verification=e.required,this.verificationRequest.resolve(e.required)),!0;if(e.type===`passwordUpdated`&&this.passwordRequest.matches(e.requestId)){if(e.ok===!1)return this.passwordRequest.fail(typeof e.error==`string`?e.error:`Password update failed.`),!0;if(typeof e.locked==`boolean`)return this.passwordRequest.resolve(e.locked),!0}return e.type===`banResult`&&this.banRequest.matches(e.requestId)?(e.ok===!0?this.banRequest.resolve():this.banRequest.fail(typeof e.error==`string`?e.error:`Ban operation failed.`,!0),!0):!1}cancel(e){let t=e===`closed`?`Room closed`:`Signaling disconnected`;this.verificationRequest.fail(`${t} before verification confirmation.`),this.banRequest.fail(`${t} before ban confirmation.`),this.passwordRequest.fail(`${t} before password confirmation.`),e===`closed`&&(this.verification=null)}};function Pi(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 Fi=6e4,Ii=class{roomId;hostToken;runtime;socket;retry;handshake;stopped=!1;admitted=!1;lastAcknowledgedAt;lastPulseAt;constructor(e,t,n){this.roomId=e,this.hostToken=t,this.runtime=n,this.connect()}acknowledged(){this.stopped||(this.lastAcknowledgedAt=performance.now(),this.admitted&&this.socket?.readyState===1&&this.pulse(this.socket))}pulse(e){let t=performance.now();this.lastPulseAt!==void 0&&t-this.lastPulseAt<Fi||(e.send(`hb`),this.lastPulseAt=t)}connect(){if(this.stopped)return;let e=new URL(re.liveness(this.roomId),Nr(this.runtime.serviceOrigin));e.protocol=e.protocol===`https:`?`wss:`:`ws:`;let t;try{t=this.runtime.createWebSocket(e)}catch{this.retry=setTimeout(()=>this.connect(),5e3);return}this.socket=t,this.admitted=!1,this.lastPulseAt=void 0,this.handshake=setTimeout(()=>t.close(),1e4),t.onopen=()=>{!this.stopped&&t===this.socket&&t.send(JSON.stringify({type:`hello`,hostToken:this.hostToken}))},t.onmessage=({data:e})=>{this.stopped||t!==this.socket||(e===`ready`&&!this.admitted?(this.admitted=!0,clearTimeout(this.handshake),this.lastAcknowledgedAt!==void 0&&performance.now()-this.lastAcknowledgedAt<1e4&&this.pulse(t)):e!==`ok`&&t.close())},t.onclose=()=>{clearTimeout(this.handshake),t===this.socket&&(this.socket=void 0,this.admitted=!1,this.stopped||(this.retry=setTimeout(()=>this.connect(),5e3)))},t.onerror=()=>t.close()}close(){this.stopped||(this.stopped=!0,clearTimeout(this.retry),clearTimeout(this.handshake),this.socket?.close(1e3,`Host left`),this.socket=void 0)}},Li=1,Ri=e=>typeof e==`string`&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e),zi=class{room;credentials;hooks;runtime;ws;peers=new Map;id=``;host=!1;hostId=``;closed=!1;timer;bytesSent=0;bytesReceived=0;pollingStats=!1;socketSerial=0;generation=null;lockedState=null;get locked(){return this.lockedState}get signalingReady(){return!this.closed&&!!this.id&&this.ws.readyState===Li}ownerRequests=new Ni(()=>this.host&&this.signalingReady,e=>this.signal(e));challenge;get requireVerification(){return this.ownerRequests.verification}setRequireVerification(e){return this.ownerRequests.setRequireVerification(e)}setPassword(e){return this.ownerRequests.setPassword(e)}updateBan(e,t,n){return this.ownerRequests.updateBan(e,t,n)}get rtt(){let e=[...this.peers.values()].filter(e=>e.connected&&e.lostAt===void 0).map(e=>e.rtt).filter(e=>typeof e==`number`);return e.length?Math.max(...e):null}get roomGeneration(){return this.generation}signalQueue=Promise.resolve();lastHeartbeat=0;hostMonitor;controlId=0;constructor(e,t,n,r=Wr()){if(this.room=e,this.credentials=t,this.hooks=n,this.runtime=r,t.matchEntry&&(t.hostToken||!/^[a-f0-9]{64}$/.test(t.matchEntry.token)||!Ri(t.matchEntry.generation)))throw Error(`Invalid match entry credentials.`);this.credentials={hostToken:t.hostToken,password:t.password,...t.matchEntry?{matchEntry:{...t.matchEntry}}:{}};let i=new URL(re.signal(e),Nr(r.serviceOrigin));i.protocol=i.protocol===`https:`?`wss:`:`ws:`,this.ws=r.createWebSocket(i),this.attachSocket(this.ws,()=>{this.signal({type:`hello`,...this.helloCredentials()})}),this.timer=setInterval(()=>{this.host&&this.signalingReady&&performance.now()-this.lastHeartbeat>=3e4&&(this.signal({type:`heartbeat`}),this.lastHeartbeat=performance.now());for(let e of this.peers.values()){if(!e.connected&&performance.now()-e.created>2e4){n.status(`Could not connect directly to this room. Try another network or room.`,`error`),this.remove(e.id);continue}e.lostAt!==void 0&&(performance.now()-e.lostAt>2e4?(n.status(`The direct connection could not be recovered. Rejoin the room.`,`error`),this.remove(e.id)):this.host&&performance.now()-e.lastRestart>5e3&&this.restartPeer(e.id))}},5e3)}attachSocket(e,t){let n=++this.socketSerial,r=()=>!this.closed&&this.ws===e&&this.socketSerial===n;e.onopen=()=>{r()&&t()},e.onmessage=e=>{r()&&(this.signalQueue=this.signalQueue.then(async()=>{r()&&await this.message(JSON.parse(e.data),n)}).catch(()=>{r()&&this.hooks.status(`Connection negotiation failed. Try another room or network.`,`error`)}))},e.onclose=e=>{r()&&(this.socketSerial++,this.challenge?.abort(),this.ownerRequests.cancel(`disconnected`),this.end(e.reason===`Host left`?`The host left. Return to Rooms and join again.`:[1001,1008,1009,1011,1013].includes(e.code)&&e.reason?e.reason:`Room connection ended. Return to Rooms and join again.`))},e.onerror=()=>{r()&&this.hooks.status(`Room service is unavailable.`,`error`)}}signal(e){!this.closed&&this.ws.readyState===Li&&this.ws.send(JSON.stringify(e))}async message(e,t=this.socketSerial){if(this.closed||t!==this.socketSerial)return;if(e.type===`terminal`){this.end(typeof e.reason==`string`&&e.reason.length<=123?e.reason:`Room connection ended.`);return}if(this.ownerRequests.accept(e))return;if(e.type===`heartbeat`&&this.host){this.hostMonitor?.acknowledged();return}if(e.type===`verificationRequired`){if(this.closed||this.id||this.credentials.hostToken||this.challenge||!xe(hi,e)||e.roomId!==this.room)return;if(!this.hooks.verify){this.end(`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!==Li)return;if(typeof n!=`string`||n.length===0||n.length>2048)throw Error(`Invalid verification response.`);this.signal({type:`hello`,...this.helloCredentials(),verificationToken:n})}catch(e){this.closed||this.end(e instanceof Error?e.message:`Room verification failed.`)}finally{this.challenge===t&&(this.challenge=void 0)}return}if(e.type===`passwordUpgradeRequired`&&this.host){this.hooks.status(`Update the room password or explicitly unlock it to allow new guests.`,`error`);return}if(e.type===`ready`){if(this.id)return;if(!xe(mi,e)||this.credentials.matchEntry&&(e.role!==`guest`||!Ri(e.id)||!Ri(e.hostId)||e.generation!==this.credentials.matchEntry.generation)){this.end(`Invalid room admission.`);return}this.id=e.id,this.host=e.role===`host`,this.host&&this.credentials.hostToken&&(this.hostMonitor=new Ii(this.room,this.credentials.hostToken,this.runtime),this.hostMonitor.acknowledged()),this.hostId=e.hostId,this.generation=e.generation??null,delete this.credentials.matchEntry,this.ownerRequests.verification=typeof e.requireVerification==`boolean`?e.requireVerification:null,this.lockedState=typeof e.locked==`boolean`?e.locked:null,this.hooks.ready(this.id,this.host);return}if(e.type===`peer`||e.type===`leave`){if(typeof e.id!=`string`||!e.id||e.id===this.id)return;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`||typeof e.from!=`string`||!e.from)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)}let r=this.negotiationScope(n,t);if(e.signal.type===`offer`){if(this.host)throw Error(`Only the host can offer`);await Oi(n,e.signal.sdp,r)}else if(e.signal.type===`answer`){if(!this.host)throw Error(`Only guests can answer`);await ki(n,e.signal.sdp,r)&&this.noteHealthy(n)}else e.signal.type===`candidate`&&e.signal.candidate&&await Ai(n,e.signal.candidate,r)}peerSignal(e,t){this.signal({type:`signal`,to:e.id,signal:t})}async offerPeer(e,t){let n=this.make(e);this.bind(n,n.pc.createDataChannel(`control`,{ordered:!0})),this.bind(n,n.pc.createDataChannel(`realtime`,{ordered:!1,maxRetransmits:0})),await Di(n,this.negotiationScope(n,t))}negotiationScope(e,t){return{current:()=>this.current(e)&&t===this.socketSerial&&this.ws.readyState===Li,versioned:!1,publish:t=>this.peerSignal(e,t)}}current(e){return!this.closed&&this.peers.get(e.id)===e}noteHealthy(e){if(!this.current(e)||e.pc.connectionState!==`connected`||![`connected`,`completed`].includes(e.pc.iceConnectionState))return;let t=e.lostAt!==void 0;e.lostAt=void 0,e.restarts=0,t&&this.hooks.status(`Direct connection restored.`,`info`)}async restartPeer(e){let t=this.peers.get(e);if(this.closed||!this.host||!t||t.restarting||t.restarts>=2||t.pc.signalingState!==`stable`||this.ws.readyState!==Li)return!1;let n=this.socketSerial;t.restarting=!0,t.lastRestart=performance.now(),t.lostAt??=t.lastRestart,t.restarts++;try{return await Di(t,this.negotiationScope(t,n),{iceRestart:!0})}catch{return!this.closed&&this.peers.get(e)===t&&this.hooks.status(`Direct connection recovery is still pending.`,`info`),!1}finally{t.restarting=!1}}make(e){let t=this.runtime.createPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}],bundlePolicy:`max-bundle`}),n={id:e,pc:t,connected:!1,created:performance.now(),candidates:[],lastRestart:0,restarts:0,restarting:!1};this.peers.set(e,n),t.onicecandidate=e=>{if(!this.current(n)||!e.candidate||this.ws.readyState!==Li)return;let t=e.candidate.toJSON();this.peerSignal(n,{type:`candidate`,candidate:t})},t.ondatachannel=e=>this.bind(n,e.channel);let r=()=>{this.closed||this.peers.get(e)!==n||(t.connectionState===`closed`?(this.hooks.status(`A peer disconnected.`,`info`),this.remove(e)):t.connectionState===`connected`&&[`connected`,`completed`].includes(t.iceConnectionState)?this.noteHealthy(n):([`failed`,`disconnected`].includes(t.connectionState)||[`failed`,`disconnected`].includes(t.iceConnectionState))&&(n.lostAt??=performance.now(),this.hooks.status(`Direct connection interrupted. Attempting recovery…`,`info`)))};return t.onconnectionstatechange=r,t.oniceconnectionstatechange=r,n}bind(e,t){if(this.closed||this.peers.get(e.id)!==e||![`control`,`realtime`].includes(t.label)){t.close();return}if(t.maxPacketLifeTime!==null||t.label===`control`&&(t.ordered!==!0||t.maxRetransmits!==null)||t.label===`realtime`&&(t.ordered!==!1||t.maxRetransmits!==0)||(t.label===`control`?e.control:e.fast)){t.close(),this.remove(e.id);return}t.label===`control`?(e.control=t,e.controlReader=new xi({fromGuest:()=>this.host,canUploadStadium:()=>this.hooks.allowStadiumUpload?.(e)??!1})):e.fast=t,t.onclose=()=>{!this.closed&&this.peers.get(e.id)===e&&(this.hooks.status(`A peer closed its game channel.`,`info`),this.remove(e.id))},t.onopen=()=>{this.closed||this.peers.get(e.id)!==e||e.control?.readyState===`open`&&e.fast?.readyState===`open`&&!e.connected&&(e.connected=!0,this.host&&(e.admissionTimer=setTimeout(()=>{this.closed||this.peers.get(e.id)!==e||(this.hooks.status(`A peer did not complete room admission.`,`error`),this.remove(e.id))},1e4)),this.hooks.open(e))},t.onmessage=n=>{if(!(this.closed||this.peers.get(e.id)!==e)){this.bytesReceived+=typeof n.data==`string`?n.data.length:n.data instanceof ArrayBuffer?n.data.byteLength:0;try{if(t.label===`control`){let t=e.controlReader?.read(n.data);t!==void 0&&this.hooks.control(e,t)}else if(n.data instanceof ArrayBuffer&&n.data.byteLength<=1200)this.hooks.fast(e,n.data);else throw Error()}catch{this.hooks.status(`Invalid peer message rejected.`,`error`),this.remove(e.id)}}}}admit(e){clearTimeout(e.admissionTimer),e.admissionTimer=void 0}control(e,t){if(e.control?.readyState!==`open`)return;let n=yi(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=Pi(t.values()))}catch{e.rtt=null}}))}finally{this.pollingStats=!1}}}hostCloseTimer;end(e){this.closed||(this.close(),this.hooks.ended?.(e))}remove(e,t=!0){if(this.closed)return;let n=this.peers.get(e);if(n){if(clearTimeout(n.admissionTimer),this.peers.delete(e),n.controlReader?.clear(),n.pc.close(),this.host&&t)try{this.signal({type:`evict`,id:e})}catch{}if(this.hooks.leave(e),!this.host){let e=this.signalingReady,t=()=>{this.end(e?`The host connection ended. Return to Rooms and join again.`:`Room connection ended. Return to Rooms and join again.`)};e?this.hostCloseTimer=setTimeout(t,1e3):t()}}}helloCredentials(){return{hostToken:this.credentials.hostToken,password:this.credentials.password,...this.credentials.matchEntry?{matchEntryToken:this.credentials.matchEntry.token}:{}}}close(){if(!this.closed){clearTimeout(this.hostCloseTimer),this.hostCloseTimer=void 0,this.socketSerial++,this.challenge?.abort(),this.ownerRequests.cancel(`closed`),this.closed=!0,this.hostMonitor?.close(),this.hostMonitor=void 0,this.credentials={},clearInterval(this.timer),this.ws.close(1e3,`Left room`);for(let e of this.peers.values())clearTimeout(e.admissionTimer),e.controlReader?.clear(),e.pc.close();this.peers.clear()}}},Bi=Object.freeze({...nn}),Vi=class e{runtime;engine;network;roomId=``;roomLink=``;roomName=``;epoch=0;soundStream=new mt;turfState=new Tr;stadiumSelection=0;players=[];nextPlayerId=0;bans=new Map;loop;linkNotification;last=performance.now();accumulator=0;match;closed=!1;assignedMatch=null;applyingAssignment=!1;closeController=new AbortController;signal=this.closeController.signal;lastRecording=null;onRecordingComplete;locked=!1;teamStyles=[null,null];inputs;traffic=new Yr;onRoomLink;onPlayerJoin;onPlayerTeamChange;onPlayerMuteChange;onPlayerAdminChange;onGameStart;onGameStop;onTeamVictory;onGameVictory;onGamePauseChange;onGamePause;onGameUnpause;onPlayerLeave;onPlayerKicked;onPlayerActivity;onPlayerInput;onPlayerChat;onPlayerDirectChat;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,this.match=new fi(e,(e,t)=>{let n=this.recordingBlob(e);this.lastRecording=n,this.invoke(`onRecordingComplete`,this.onRecordingComplete,n,t)}),this.inputs=new pi(this.match)}static async create(t,n=qr(),r){let i=Nr(n.network.serviceOrigin),a=Nr(n.publicOrigin??i);if(t=Or(t),t.noPlayer!==void 0&&typeof t.noPlayer!=`boolean`)throw Error(`Invalid noPlayer setting`);let o=t.noPlayer===!1,s=t.playerName??`Host`;if(o&&(typeof s!=`string`||!s.trim()||s.length>24))throw Error(`Invalid host player name`);let c=dt(r),l;try{c.signal.throwIfAborted();let r=await c.run(n.loadEngine(c.signal));r.load(t.stadium??mn()),l=new e(r,n);let u=l,d=await c.run(n.request(new URL(re.rooms,i),{signal:c.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t.roomName,maxPlayers:t.maxPlayers??16,password:t.password??``,private:t.public===!1,hostPlayer:o,...t.geo?{geo:t.geo}:{}})}));if(!d.ok)throw await c.run(pt(d,c.signal));let f=await c.run(d.json());u.roomId=f.id,u.roomName=t.roomName,u.roomLink=`${a}${Ar(f.id)}`;let p;try{await c.run(new Promise((e,t)=>{p=setTimeout(()=>t(Error(`Signaling timed out`)),12e3),u.network=new zi(f.id,{hostToken:f.hostToken},{ready:(n,r)=>{if(!r){t(Error(`Host authority was not granted`));return}o&&(u.players.push({id:u.nextPlayerId++,slot:0,peerId:n,name:s.trim(),team:0,admin:!0}),u.engine.joinPlayer(0)),clearTimeout(p),e()},allowStadiumUpload:e=>!!u.players.find(t=>t.peerId===e.id)?.admin&&[`lobby`,`finished`].includes(u.engine.phase)&&u.traffic.allow(e.id,`message`),open:()=>{},control:(e,t)=>u.control(e,t),fast:(e,t)=>u.fast(e,t),leave:e=>u.leave(e),status:(e,t)=>{t===`error`&&u.report(e)},ended:e=>{clearTimeout(p),t(Error(e)),u.close(),u.report(e)}},n.network)}))}catch(e){throw u.close(),e}finally{clearTimeout(p)}if(u.closed)throw Error(`Room closed during startup`);u.last=performance.now(),u.loop=setInterval(()=>u.advance(),1e3/hn);let m=u.roomLink;return u.linkNotification=setTimeout(()=>{u.linkNotification=void 0,u.invoke(`onRoomLink`,u.onRoomLink,m)},0),l}catch(e){throw l?.close(),e}finally{c.dispose()}}advance(){if(this.closed)return;let e=performance.now(),t=e-this.last;this.last=e,t>500&&this.engine.phase===`playing`&&!this.engine.paused&&(this.pauseGame(!0),this.report(`Host scheduler stalled; match paused.`)),this.accumulator+=Math.max(0,Math.min(t,500));let n=0;try{for(;!this.closed&&this.accumulator>=1e3/hn&&n++<32;){for(let t of this.players)this.inputs.expire(t.peerId,t.slot,e);if(this.match.checkRecordingLimit(),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.match.step(),this.turfState.capture(this.engine),this.soundStream.capture(this.engine,this.epoch),this.engine.phase!==r&&this.state();let i=r===`goal`&&this.engine.phase===`playing`,a=r===`finished`&&this.engine.phase===`lobby`,o=this.engine.red>t,s=this.engine.blue>n,c=this.engine.ballKicks.map(e=>{let t=this.players.find(t=>t.slot===e);return t?this.playerCopy(t):null}).filter(e=>!!e),l=r!==`finished`&&this.engine.phase===`finished`?this.getScores():null;a&&this.invoke(`onGameStop`,this.onGameStop,null),l&&(this.invoke(`onTeamVictory`,this.onTeamVictory,{...l}),this.invoke(`onGameVictory`,this.onGameVictory,{...l}));for(let e of c)this.invoke(`onPlayerBallKick`,this.onPlayerBallKick,e);if(o&&this.invoke(`onTeamGoal`,this.onTeamGoal,1),s&&this.invoke(`onTeamGoal`,this.onTeamGoal,2),i&&this.invoke(`onPositionsReset`,this.onPositionsReset),this.closed)break;this.engine.tick%(hn/30)==0&&ut(this.network,this.engine.snapshot(),this.epoch,this.inputs),this.accumulator-=1e3/hn}this.closed||ht(this.network,this.soundStream.drain(e))}catch(e){this.closed||(this.engine.setPaused(!0),this.report(String(e)))}}allowed(e){return this.traffic.allow(e.id,`message`)?!0:(this.network.remove(e.id),!1)}control(e,t){if(!this.allowed(e)||!t||typeof t!=`object`)return;let n=t,r=this.players.find(t=>t.peerId===e.id);if(n.type===`join`&&!r)return this.admitPlayer(e,n);if(!r||n.type!==`action`||n.action!==`chat`&&n.action!==`directChat`&&n.action!==`typing`&&!this.traffic.allow(e.id,`action`))return;let i=nt(n.action,n);i&&this.applyPlayerAction(e,r,i)}admitPlayer(e,t){if(t.version!==1||t.engine!==gn||typeof t.name!=`string`||!t.name.trim()||t.name.length>24){this.network.remove(e.id);return}let n=Array.from({length:32},(e,t)=>t).find(e=>!this.players.some(t=>t.slot===e));if(n===void 0){this.network.remove(e.id);return}let r={id:this.nextPlayerId++,slot:n,peerId:e.id,name:t.name.trim(),team:0,admin:!1};this.players.push(r),this.network.admit(e),this.match.recordPlayer(r.slot,r.name),this.command(`join`,n,0),this.turfState.capture(this.engine),this.network.control(e,{type:`welcome`,features:[`directChat`,`playerConversation`],...t.turfVersion===1?{turf:this.turfState.checkpoint()}:{},soundStream:this.soundStream.checkpoint(),epoch:this.epoch,roomName:this.roomName,engine:gn,slot:n,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))}applyPlayerAction(e,t,n){if(n.action===`typing`){if(!this.traffic.allow(e.id,`typing`))return;this.network.broadcast({type:`typing`,playerId:t.peerId,active:n.active&&!t.muted});return}if(n.action===`directChat`){if(t.muted||!this.traffic.allow(e.id,`chat`)){this.traffic.allow(e.id,`feedback`)&&this.network.control(e,{type:`chatError`,rejectedText:n.text,recipientId:n.action===`directChat`?n.recipientId:``,text:t.muted?`You are muted in this room.`:`Message not sent. Please wait a moment before sending again.`});return}let r=Ve(this.players.map(e=>({...e,id:e.peerId})),e.id,n.recipientId,n.text);if(!r){this.network.control(e,{type:`directChatError`,recipientId:n.recipientId,text:`This player is no longer available.`});return}let i=this.players.find(e=>e.peerId===r.toId);if(!i)return;let a=!1,o=this.invoke(`onPlayerDirectChat`,()=>{let e=this.onPlayerDirectChat?.(this.playerCopy(t),this.playerCopy(i),r.text);return a=!0,e});if(!a||o instanceof Promise||o===!1||this.closed||t.muted||!this.players.includes(t)||!this.players.includes(i))return;for(let e of[r.fromId,r.toId]){let t=this.network.peers.get(e);t&&this.network.control(t,r)}return}if(n.action===`chat`){if(t.muted||!this.traffic.allow(e.id,`chat`)){this.traffic.allow(e.id,`feedback`)&&this.network.control(e,{type:`chatError`,rejectedText:n.text,recipientId:``,text:t.muted?`You are muted in this room.`:`Message not sent. Please wait a moment before sending again.`});return}if(this.invoke(`onPlayerActivity`,this.onPlayerActivity,this.playerCopy(t)),this.closed||!this.players.includes(t))return;this.invoke(`onPlayerChat`,this.onPlayerChat,this.playerCopy(t),n.text)!==!1&&!this.closed&&this.players.includes(t)&&!t.muted&&this.network.broadcast({type:`chat`,playerId:t.peerId,name:t.name,text:n.text})}if(n.action===`avatar`){t.avatar=n.avatar,this.match.recordPlayer(t.slot,t.name,t.avatarOverride??t.avatar),this.sync();return}if(!qe(t,n,{players:()=>this.players,current:()=>!this.closed,stopped:()=>[`lobby`,`finished`].includes(this.engine.phase),locked:()=>this.locked,move:(e,n)=>this.changeTeam(e.id,n,t),lock:e=>this.changeTeamsLock(e,this.playerCopy(t))})){if(n.action===`defaultStadium`||n.action===`customStadium`){let r=n=>{!this.closed&&this.players.includes(t)&&this.network.control(e,{type:`stadiumResult`,text:n})};if(!t.admin||![`lobby`,`finished`].includes(this.engine.phase)){r(`Stadium change rejected: admin permission and a stopped match are required.`);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(t)){if(i!==this.stadiumSelection||!t.admin||![`lobby`,`finished`].includes(this.engine.phase)){r(`Stadium change cancelled: room state or permissions changed.`);return}this.changeStadium(e,this.playerCopy(t)),r(`Stadium applied.`)}}).catch(()=>r(`Stadium could not be loaded. Please try again.`));return}if(t.admin){if(n.action===`mute`){let e=this.players.find(e=>e.slot===n.slot);Ke(t,e,e=>e.peerId===this.network.hostId)&&this.changePlayerMuted(e.id,n.muted,this.playerCopy(t));return}if(n.action===`ban`||n.action===`clearBans`){let r=n.action===`ban`?this.players.find(e=>e.slot===n.slot):void 0;if(n.action===`ban`&&!Ke(t,r,e=>e.peerId===this.network.hostId))return;let i=t=>{!this.closed&&this.network.peers.has(e.id)&&this.network.control(e,{type:`moderationResult`,text:t})};if(n.action===`clearBans`){i(`Only the room owner can clear bans.`);return}if(!r)return;this.banPlayer(r.id,`Removed by admin`,this.playerCopy(t)).then(()=>i(`Player banned.`)).catch(e=>i(e instanceof Error?e.message:`Moderation failed.`));return}if(n.action===`teamColors`&&this.changeTeamColors(n.team,n.palette),n.action===`kickRate`){let e=n.value;this.changeKickRateLimit(e&255,e>>>8&255,e>>>16,this.playerCopy(t))}if(n.action===`start`&&this.beginGame(t),n.action===`stop`&&this.endGame(t),n.action===`pause`&&this.changePause(n.paused===void 0?!this.engine.paused:n.paused,this.playerCopy(t)),n.action===`settings`&&[`lobby`,`finished`].includes(this.engine.phase)){let e=n;if(this.setScoreLimit(e.score),this.setTimeLimit(e.minutes),this.changeTeamsLock(e.locked,this.playerCopy(t)),this.closed)return;if(e.kickRate!==void 0&&e.kickRate!==this.engine.kickRate){let n=e.kickRate;this.changeKickRateLimit(n&255,n>>>8&255,n>>>16,this.playerCopy(t))}}if(n.action===`kick`){let e=this.players.find(e=>e.slot===n.slot);Ke(t,e,e=>e.peerId===this.network.hostId)&&this.removePlayer(e.id,`Removed by host`,this.playerCopy(t))}}}}fast(e,t){if(!this.allowed(e))return;let n=this.players.find(t=>t.peerId===e.id);if(!n)return;let r=this.engine.index(n.slot)*18+14,i=this.engine.data[r],a=this.inputs.accept(e.id,n.slot,t,this.epoch);a!==void 0&&(this.engine.data[r]!==i&&this.invoke(`onPlayerInput`,this.onPlayerInput,this.playerCopy(n),i),a&&this.invoke(`onPlayerActivity`,this.onPlayerActivity,this.playerCopy(n)))}command(e,t=0,n=0){if(this.closed)throw Error(`Room is closed`);this.match.command(e,t,n),(e===`start`||e===`stop`)&&this.turfState.capture(this.engine)}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.match.recordPlayer(t.slot,null),this.command(`team`,t.slot,0),this.players=this.players.filter(t=>t.peerId!==e),this.inputs.remove(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,input:this.engine.data[t+14]}}getPlayerList(){return this.players.map(e=>this.playerCopy(e))}getPlayer(e){let t=this.players.find(t=>t.id===e);return t?this.playerCopy(t):null}setTeamColors(e,t,n,r){let i=Xe(t,n,r);i.angle=((256*t/360|0)&255)*(360/256),this.changeTeamColors(e,i)}changeTeamColors(e,t){if(this.closed)throw Error(`Room is closed`);if(e!==1&&e!==2)throw Error(`Invalid team`);JSON.stringify(this.teamStyles[e-1])!==JSON.stringify(t)&&(this.teamStyles[e-1]=t,this.match.recordStyles(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.match.recordOrder(a.map(e=>e.slot)),this.sync())}setPlayerAvatar(e,t){if(this.closed)throw Error(`Room is closed`);if(!Ye(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.match.recordPlayer(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&&He(this.players,r,t)&&(this.command(`team`,r.slot,t),this.match.recordOrder(this.players.map(e=>e.slot)),this.sync(),this.invoke(`onPlayerTeamChange`,this.onPlayerTeamChange,this.playerCopy(r),n?this.playerCopy(n):null))}setPlayerAdmin(e,t){if(this.closed)throw Error(`Room is closed`);let n=this.players.find(t=>t.id===e);n&&n.admin!==!!t&&(n.admin=!!t,this.sync(),this.invoke(`onPlayerAdminChange`,this.onPlayerAdminChange,this.playerCopy(n),null))}setPlayerMuted(e,t){this.changePlayerMuted(e,t,null)}changePlayerMuted(e,t,n){if(this.closed)throw Error(`Room is closed`);if(!Number.isInteger(e)||typeof t!=`boolean`)throw Error(`Invalid player mute`);let r=this.players.find(t=>t.id===e);r&&r.peerId!==this.network.hostId&&!!r.muted!==t&&(r.muted=t,this.sync(),this.invoke(`onPlayerMuteChange`,this.onPlayerMuteChange,this.playerCopy(r),n))}setTeamsLock(e){this.changeTeamsLock(e,null)}changeTeamsLock(e,t){if(this.closed)throw Error(`Room is closed`);this.locked!==!!e&&(this.locked=!!e,this.sync(),this.invoke(`onTeamsLockChange`,this.onTeamsLockChange,this.locked,t))}kickPlayer(e,t=`Removed by host`,n=!1){if(this.closed)throw Error(`Room is closed`);if(typeof n!=`boolean`)throw Error(`Invalid ban flag`);if(n)return this.banPlayer(e,t);this.removePlayer(e,t,null)}async banPlayer(e,t,n=null){if(typeof t!=`string`)throw Error(`Invalid kick reason`);let r=this.players.find(t=>t.id===e);if(!r||r.peerId===this.network.hostId)return;let i=this.playerCopy(r),a=t.slice(0,100);if(this.bans.size>=256&&!this.bans.has(e))throw Error(`Clear existing bans before adding more.`);try{await this.network.updateBan(`ban`,r.peerId,a)}catch(t){throw t instanceof ji&&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,...t==null?{playerId:n.peerId}:{}};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=Mr(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)}}startAssignedMatch(e){let{roomId:t,generation:n,matchId:r}=e,i=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;if(this.closed||this.applyingAssignment||this.assignedMatch||t!==this.roomId||n!==this.network.roomGeneration||!i.test(r)||!i.test(n))return!1;let a=e.players.map(e=>({...e}));if(a.length<2||a.length>22||new Set(a.map(e=>e.userId)).size!==a.length||new Set(a.map(e=>e.peerId)).size!==a.length||a.filter(e=>e.side===`red`).length*2!==a.length||a.some(e=>!i.test(e.userId)||!e.peerId||!i.test(e.peerId)||![`red`,`blue`].includes(e.side)||e.signalingAttached!==!0))return!1;let o=()=>!this.closed&&this.network.signalingReady&&this.engine.phase===`lobby`&&this.network.roomGeneration===n&&this.players.length===a.length&&a.every(e=>{let t=this.players.find(t=>t.peerId===e.peerId),n=e.peerId?this.network.peers.get(e.peerId):void 0;return t&&t.peerId!==this.network.hostId&&n?.connected===!0&&n.lostAt===void 0&&n.control?.readyState===`open`&&n.fast?.readyState===`open`});if(!o())return!1;this.applyingAssignment=!0;try{this.setTeamsLock(!0);for(let e of a){if(!o())return!1;let t=this.players.find(t=>t.peerId===e.peerId);if(!t||(this.setPlayerAdmin(t.id,!1),!o()))return!1;this.setPlayerTeam(t.id,e.side===`red`?1:2)}return!o()||!this.locked||!a.every(e=>{let t=this.players.find(t=>t.peerId===e.peerId);return t&&!t.admin&&t.team===(e.side===`red`?1:2)})?!1:(this.assignedMatch=r,this.beginGame(null),!this.closed&&this.engine.phase===`playing`)}finally{this.applyingAssignment=!1}}startGame(){this.beginGame(null)}static finishAssignedDraw(e){return!e.assignedMatch||!e.engine.canFinishDraw()?!1:(e.command(`finishDraw`),e.state(),!0)}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)))}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=Je(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)}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.match.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.reset(),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/hn,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 Bi}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=vt(t),r=this.readDisc(e);Object.entries(n).every(([e,t])=>r[e]===t)||(this.match.command(`disc`,e,0,n),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`);this.match.startRecording(this.players.map(e=>({slot:e.slot,name:e.name,avatar:e.avatarOverride??e.avatar})),this.teamStyles)}recordingBlob(e){return new Blob([$r(e)],{type:`application/x-ball2d-replay`})}stopRecording(){let e=this.match.stopRecording();return e?this.recordingBlob(e):null}close(){if(!this.closed){this.closed=!0,this.inputs.close(),this.closeController.abort();try{this.match.close()}finally{clearInterval(this.loop),clearTimeout(this.linkNotification),this.linkNotification=void 0,this.network?.close(),this.players=[],this.traffic.clear()}}}};function Hi(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 Or({...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 Ui=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`:``)}})),Wi=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=Ui(),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})),Gi=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=Wi()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Ki=z({createSupportsColor:()=>Zi,default:()=>ea});function qi(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 Ji(){if(!(`FORCE_COLOR`in Qi))return;if(Qi.FORCE_COLOR===`true`)return 1;if(Qi.FORCE_COLOR===`false`)return 0;if(Qi.FORCE_COLOR.length===0)return 1;let e=Math.min(Number.parseInt(Qi.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}function Yi(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Xi(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Ji();r!==void 0&&($i=r);let i=n?$i:r;if(i===0)return 0;if(n){if(qi(`color=16m`)||qi(`color=full`)||qi(`color=truecolor`))return 3;if(qi(`color=256`))return 2}if(`TF_BUILD`in Qi&&`AGENT_NAME`in Qi)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Qi.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 Qi)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Qi)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Qi)||Qi.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Qi)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Qi.TEAMCITY_VERSION);if(Qi.COLORTERM===`truecolor`||Qi.TERM===`xterm-kitty`||Qi.TERM===`xterm-ghostty`||Qi.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Qi){let e=Number.parseInt((Qi.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Qi.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Qi.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Qi.TERM)||`COLORTERM`in Qi?1:a}function Zi(e,t={}){return Yi(Xi(e,{streamIsTTY:e&&e.isTTY,...t}))}var Qi,$i,ea,ta=L((()=>{({env:Qi}=p),qi(`no-color`)||qi(`no-colors`)||qi(`color=false`)||qi(`color=never`)?$i=0:(qi(`color`)||qi(`colors`)||qi(`color=true`)||qi(`color=always`))&&($i=1),ea={stdout:Zi({isTTY:g.isatty(1)}),stderr:Zi({isTTY:g.isatty(2)})}})),na=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=(ta(),ee(Ki));t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
15
15
|
`).join(`
|
|
16
16
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
17
|
-
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=
|
|
18
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),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(`
|
|
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=Wi()(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)}})),ra=R(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?Gi():na()})),ia=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`)})),aa=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||{})})),oa=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}}})),sa=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}})),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(`
|
|
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}})),ca=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=oa(),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}})),la=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=oa().BufferVisitor,e.PEM=sa().PEM;var t=ca();e.ASN1=t.ASN1,e.Class=t.Class,e.Tag=t.Tag,e.BitString=t.BitString})),ua=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=aa(),i=la(),a=ia();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))})})),da=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=la(),i=ia(),a=ua(),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}})),fa=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ia();e.bytesFromIP=t.bytesFromIP,e.bytesToIP=t.bytesToIP,e.getOID=t.getOID,e.getOIDName=t.getOIDName;var n=ua();e.PublicKey=n.PublicKey,e.PrivateKey=n.PrivateKey,e.RSAPublicKey=n.RSAPublicKey,e.RSAPrivateKey=n.RSAPrivateKey;var r=da();e.Certificate=r.Certificate,e.DistinguishedName=r.DistinguishedName})),pa=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||={})})),ma=V(ra(),1),ha=fa();pa();var ga=`[object ArrayBuffer]`,U=class e{static isArrayBuffer(e){return Object.prototype.toString.call(e)===ga}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}},_a=`string`,va=/^[0-9a-f\s]+$/i,ya=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ba=/^[a-zA-Z0-9-_]+$/,xa=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))}},Sa=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}},Ca=class e{static isHex(e){return typeof e===_a&&va.test(e)}static isBase64(e){return typeof e===_a&&ya.test(e)}static isBase64Url(e){return typeof e===_a&&ba.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 Sa.toString(n,!0);case`utf16`:case`utf16be`:return Sa.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 Sa.fromString(e,!0);case`utf16`:case`utf16be`:return Sa.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 xa.fromString(t);case`utf16`:case`utf16be`:return Sa.fromString(t);case`utf16le`:case`usc2`:return Sa.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 xa.toString(t);case`utf16`:case`utf16be`:return Sa.toString(t);case`utf16le`:case`usc2`:return Sa.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 Sa.toString(e,t)}static FromUtf16String(e,t=!1){return Sa.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,``)||``}};Ca.DEFAULT_UTF8_ENCODING=`utf8`;function wa(...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 Ta(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 Ea(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 Da(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 Oa(...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 ka(){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=Ea(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,Ea(a,8)-r}function Aa(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=Da(n-t,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=Da(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 ja(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 Ma(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 Na=z({Any:()=>nc,BaseBlock:()=>so,BaseStringBlock:()=>lo,BitString:()=>Wo,BmpString:()=>bs,Boolean:()=>Ro,CharacterString:()=>Vs,Choice:()=>rc,Constructed:()=>Ao,DATE:()=>qs,DEFAULT_MAX_CONTENT_LENGTH:()=>ho,DEFAULT_MAX_DEPTH:()=>100,DEFAULT_MAX_NODES:()=>mo,DateTime:()=>Zs,Duration:()=>$s,EndOfContent:()=>No,Enumerated:()=>$o,GeneralString:()=>zs,GeneralizedTime:()=>Gs,GraphicString:()=>Fs,HexBlock:()=>no,IA5String:()=>Ns,Integer:()=>Zo,Null:()=>Fo,NumericString:()=>Ts,ObjectIdentifier:()=>rs,OctetString:()=>Vo,Primitive:()=>po,PrintableString:()=>Ds,RawData:()=>ac,RelativeObjectIdentifier:()=>ss,Repeated:()=>ic,Sequence:()=>ls,Set:()=>ds,TIME:()=>tc,TeletexString:()=>ks,TimeOfDay:()=>Ys,UTCTime:()=>Us,UniversalString:()=>Cs,Utf8String:()=>_s,ValueBlock:()=>io,VideotexString:()=>js,ViewWriter:()=>La,VisibleString:()=>Ls,compareSchema:()=>oc,fromBER:()=>Eo,verifySchema:()=>sc});function Pa(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function Fa(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 Ia(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 La=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Fa(this.items)}},Ra=[new Uint8Array([1])],za=`0123456789`,Ba=`name`,Va=`valueHexView`,Ha=`isHexOnly`,Ua=`idBlock`,Wa=`tagClass`,Ga=`tagNumber`,Ka=`isConstructed`,qa=`fromBER`,Ja=`toBER`,Ya=`local`,Xa=``,Za=new ArrayBuffer(0),Qa=new Uint8Array,$a=`EndOfContent`,eo=`OCTET STRING`,to=`BIT STRING`;function no(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):Qa}fromBER(e,t,n,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Ia(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`,Za)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ca.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var ro=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=Xa,warnings:n=[],valueBeforeDecode:r=Qa}={}){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:Ca.ToHex(this.valueBeforeDecodeView)}}};ro.NAME=`baseBlock`;var io=class extends ro{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'`)}};io.NAME=`valueBlock`;var ao=class extends no(ro){constructor({idBlock:e={}}={}){super(),e?(this.isHexOnly=e.isHexOnly??!1,this.valueHexView=e.valueHex?U.toUint8Array(e.valueHex):Qa,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`,Za}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=Da(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(!Ia(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=Ea(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}}};ao.NAME=`identificationBlock`;var oo=class extends ro{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(!Ia(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=Ea(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=Da(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,Za;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}}};oo.NAME=`lengthBlock`;var W={},so=class extends ro{constructor({name:e=Xa,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ao(r),this.lenBlock=new oo(r),this.valueBlock=i?new i(r):new io(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 La;t||co(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?Za: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():Ca.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Ca.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&ja(this.toBER(),e.toBER())}};so.NAME=`BaseBlock`;function co(e){if(e instanceof W.Constructed)for(let t of e.valueBlock.value)co(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var lo=class extends so{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Xa,...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}'`}};lo.NAME=`BaseStringBlock`;var uo=class extends no(io){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};uo.NAME=`PrimitiveValueBlock`;var fo,po=class extends so{constructor(e={}){super(e,uo),this.idBlock.isConstructed=!1}};fo=po,W.Primitive=fo,po.NAME=`PRIMITIVE`;var mo=1e4,ho=16777216,go=`Maximum ASN.1 nesting depth exceeded`,_o=`Maximum ASN.1 node count exceeded`,vo=`Maximum ASN.1 content length exceeded`;function yo(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??mo,maxContentLength:e.maxContentLength??ho}}function bo(e){let t=new so({},io);return t.error=e,{offset:-1,result:t}}function xo(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return _o}function So(e,t){if(e>t.maxContentLength)return vo}function Co(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return bo(go);r.depth=i;try{return To(e,t,n,r)}finally{--r.depth}}function wo(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 To(e,t=0,n=e.length,r=yo()){let i=t,a=new so({},io),o=new ro;if(!Ia(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=xo(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=So(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=so;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=wo(a,d),c=a.fromBER(e,t,l,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:c,result:a}}function Eo(e,t={}){if(!e.byteLength){let e=new so({},io);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return To(U.toUint8Array(e).slice(),0,e.byteLength,yo(t))}function Do(e,t){return e?1:t}var Oo=class extends io{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??yo();if(!Ia(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(;Do(this.isIndefiniteForm,n)>0;){let e=Co(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===$a)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===$a?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),o}toBER(e,t){let n=t||new La;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?Za:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Oo.NAME=`ConstructedValueBlock`;var ko,Ao=class extends so{constructor(e={}){super(e,Oo),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} :`}};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
|
|
26
|
+
`)}`:`${t} :`}};ko=Ao,W.Constructed=ko,Ao.NAME=`CONSTRUCTED`;var jo=class extends io{fromBER(e,t,n){return t}toBER(e){return Za}};jo.override=`EndOfContentValueBlock`;var Mo,No=class extends so{constructor(e={}){super(e,jo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Mo=No,W.EndOfContent=Mo,No.NAME=$a;var Po,Fo=class extends so{constructor(e={}){super(e,io),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}`}};Po=Fo,W.Null=Po,Fo.NAME=`NULL`;var Io=class extends no(io){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 Ia(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,ka.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Io.NAME=`BooleanValueBlock`;var Lo,Ro=class extends so{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Io),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Lo=Ro,W.Boolean=Lo,Ro.NAME=`BOOLEAN`;var zo=class extends no(Oo){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=Oo.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===$a){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==eo)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?Oo.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};zo.NAME=`OctetStringValueBlock`;var Bo,Vo=class extends so{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},zo),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??yo(),t=Co(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?Ao.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Ca.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 Bo&&e.push(t.valueBlock.valueHexView);return U.concat(e)}};Bo=Vo,W.OctetString=Bo,Vo.NAME=eo;var Ho=class extends no(Oo){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=Oo.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===$a){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==to)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(!Ia(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??yo(),i=Co(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 Oo.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}}};Ho.NAME=`BitStringValueBlock`;var Uo,Wo=class extends so{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ho),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 Ao.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)}`}}};Uo=Wo,W.BitString=Uo,Wo.NAME=to;var Go;function Ko(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=Oa(new Uint8Array([l%10]),a);break;default:a[o-d]=l%10}}return n[0]>0&&(a=Oa(n,a)),a}function qo(e){if(e>=Ra.length)for(let t=Ra.length;t<=e;t++){let e=new Uint8Array([0]),n=Ra[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=Oa(e,n)),Ra.push(n)}return Ra[e]}function Jo(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 Yo=class extends no(io){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=ka.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(Aa(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=Jo(qo(n),t),a=`-`;break;default:t=Ko(t,qo(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=za.charAt(t[e]));return o===!1&&(a+=za.charAt(0)),a}};Go=Yo,Yo.NAME=`IntegerValueBlock`,Object.defineProperty(Go.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Xo,Zo=class extends so{constructor(e={}){super(e,Yo),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Pa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Pa();let t=BigInt(e),n=new La,r=t.toString(16).replace(/^-/,``),i=new Uint8Array(Ca.FromHex(r));if(t<0){let e=new Uint8Array(i.length+(i[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${Ca.ToHex(e)}`)+t,a=U.toUint8Array(Ca.FromHex(r.toString(16)));a[0]|=128,n.write(a)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Xo({valueHex:n.final()})}convertToDER(){let e=new Xo({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Xo({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Xo=Zo,W.Integer=Xo,Zo.NAME=`INTEGER`;var Qo,$o=class extends Zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Qo=$o,W.Enumerated=Qo,$o.NAME=`ENUMERATED`;var es=class extends no(io){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(!Ia(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=Ea(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){Pa();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=Da(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Za;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=Ca.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}}};es.NAME=`sidBlock`;var ts=class extends io{constructor({value:e=Xa,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new es;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,Za;t.push(r)}return Fa(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 es;if(r>2**53-1)Pa(),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}};ts.NAME=`ObjectIdentifierValueBlock`;var ns,rs=class extends so{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ts),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};ns=rs,W.ObjectIdentifier=ns,rs.NAME=`OBJECT IDENTIFIER`;var is=class extends no(ro){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(!Ia(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=Ea(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=Da(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Za;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?Ca.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};is.NAME=`relativeSidBlock`;var as=class extends io{constructor({value:e=Xa,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new is;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,Za;n.push(r)}return Fa(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 is;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}};as.NAME=`RelativeObjectIdentifierValueBlock`;var os,ss=class extends so{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,as),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};os=ss,W.RelativeObjectIdentifier=os,ss.NAME=`RelativeObjectIdentifier`;var cs,ls=class extends Ao{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};cs=ls,W.Sequence=cs,ls.NAME=`SEQUENCE`;var us,ds=class extends Ao{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};us=ds,W.Set=us,ds.NAME=`SET`;var fs=class extends no(io){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Xa}toJSON(){return{...super.toJSON(),value:this.value}}};fs.NAME=`StringValueBlock`;var ps=class extends fs{};ps.NAME=`SimpleStringValueBlock`;var ms=class extends lo{constructor({...e}={}){super(e,ps)}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}};ms.NAME=`SIMPLE STRING`;var hs=class extends ms{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=Ca.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Ca.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ca.FromUtf8String(e)),this.valueBlock.value=e}};hs.NAME=`Utf8StringValueBlock`;var gs,_s=class extends hs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};gs=_s,W.Utf8String=gs,_s.NAME=`UTF8String`;var vs=class extends ms{fromBuffer(e){this.valueBlock.value=Ca.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ca.FromUtf16String(e))}};vs.NAME=`BmpStringValueBlock`;var ys,bs=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};ys=bs,W.BmpString=ys,bs.NAME=`BMPString`;var xs=class extends ms{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=Da(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}};xs.NAME=`UniversalStringValueBlock`;var Ss,Cs=class extends xs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Ss=Cs,W.UniversalString=Ss,Cs.NAME=`UniversalString`;var ws,Ts=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ws=Ts,W.NumericString=ws,Ts.NAME=`NumericString`;var Es,Ds=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Es=Ds,W.PrintableString=Es,Ds.NAME=`PrintableString`;var Os,ks=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Os=ks,W.TeletexString=Os,ks.NAME=`TeletexString`;var As,js=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};As=js,W.VideotexString=As,js.NAME=`VideotexString`;var Ms,Ns=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Ms=Ns,W.IA5String=Ms,Ns.NAME=`IA5String`;var Ps,Fs=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ps=Fs,W.GraphicString=Ps,Fs.NAME=`GraphicString`;var Is,Ls=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Is=Ls,W.VisibleString=Is,Ls.NAME=`VisibleString`;var Rs,zs=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Rs=zs,W.GeneralString=Rs,zs.NAME=`GeneralString`;var Bs,Vs=class extends ms{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Bs=Vs,W.CharacterString=Bs,Vs.NAME=`CharacterString`;var Hs,Us=class extends Ls{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]=Ma(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Ma(this.month,2),e[2]=Ma(this.day,2),e[3]=Ma(this.hour,2),e[4]=Ma(this.minute,2),e[5]=Ma(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}}};Hs=Us,W.UTCTime=Hs,Us.NAME=`UTCTime`;var Ws,Gs=class extends Us{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(Ma(this.year,4)),e.push(Ma(this.month,2)),e.push(Ma(this.day,2)),e.push(Ma(this.hour,2)),e.push(Ma(this.minute,2)),e.push(Ma(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(Ma(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Ws=Gs,W.GeneralizedTime=Ws,Gs.NAME=`GeneralizedTime`;var Ks,qs=class extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ks=qs,W.DATE=Ks,qs.NAME=`DATE`;var Js,Ys=class extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Js=Ys,W.TimeOfDay=Js,Ys.NAME=`TimeOfDay`;var Xs,Zs=class extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Xs=Zs,W.DateTime=Xs,Zs.NAME=`DateTime`;var Qs,$s=class extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Qs=$s,W.Duration=Qs,$s.NAME=`Duration`;var ec,tc=class extends _s{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ec=tc,W.TIME=ec,tc.NAME=`TIME`;var nc=class{constructor({name:e=Xa,optional:t=!1}={}){this.name=e,this.optional=t}},rc=class extends nc{constructor({value:e=[],...t}={}){super(t),this.value=e}},ic=class extends nc{constructor({value:e=new nc,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},ac=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=Qa}={}){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 oc(e,t,n){if(n instanceof rc){for(let r of n.value)if(oc(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(Ba)&&(e.name=n.name),e}}if(n instanceof nc)return n.hasOwnProperty(Ba)&&(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)||!(Ua in n)||!(qa in n.idBlock)||!(Ja 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(Wa)===!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(Ga)===!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(Ka)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Ha 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(!(Va 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,Xa),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 ic&&(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,Xa),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,Xa),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof ic){if(i=oc(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,Xa),n.name&&delete e[n.name]),i}if(Ba in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=Ya 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=oc(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,Xa),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,Xa),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&Va in t.valueBlock){let r=To(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,Xa),n.name&&(delete e[n.name],t.name=n.name)),t}return oc(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function sc(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=To(U.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:oc(n.result,n.result,t)}var cc=`[object ArrayBuffer]`,lc=`[object SharedArrayBuffer]`;function uc(e){return Object.prototype.toString.call(e)}function dc(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`&&mc(t.buffer)}function fc(e){return uc(e)===cc}function pc(e){return typeof SharedArrayBuffer<`u`&&uc(e)===lc}function mc(e){return fc(e)||pc(e)}function hc(e){return dc(e)}function gc(e){return mc(e)||hc(e)}function _c(e){if(!gc(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function vc(e){return _c(e),mc(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function yc(e){if(_c(e),fc(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(vc(e)),t}function bc(e,t,n={}){let r=vc(e),i=vc(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 xc(e){let t=vc(e),n=``;for(let e of t)n+=String.fromCharCode(e);return n}function Sc(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function Cc(e){return typeof e==`string`}var wc=/^[0-9a-f]$/i,Tc=[` `,` `,`
|
|
27
|
+
`,`\r`,`:`,`-`,`.`];function Ec(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?Tc:e.separators}function Dc(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function Oc(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function kc(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function Ac(e){let t=/\r\n|\n/.exec(e);if(t)return t[0]===`\r
|
|
28
28
|
`?`\r
|
|
29
29
|
`:`
|
|
30
|
-
`}function
|
|
31
|
-
`,r=[];for(let n=0;n<i.length;n+=e)r.push(
|
|
30
|
+
`}function jc(e){return e.replace(/[^0-9a-f]/gi,``)}function Mc(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 Nc(e){let t=e.trim(),n=/^0x/i.test(t)?`0x`:``,r=n?t.slice(2):t,i=Ac(r),a=r.split(/\r\n|\n/).filter(e=>e.length>0),o=Mc(a[0]?.trim()??``),s={case:kc(t),prefix:n};if(o&&(s.group=o),i&&a.length>1){let e=jc(a[0]??``).length/2;e>0&&a.slice(0,-1).every(t=>jc(t).length/2===e)&&(s.line={bytesPerLine:e,separator:i})}return s}function Pc(e,t){let n=t.allowPrefix??!0,r=[...Ec(t)].sort((e,t)=>t.length-e.length);for(let e of r)Dc(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(wc.test(n)){a+=n,o=!1,e+=1;continue}let s=Oc(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 Fc(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 Ic(e,t={}){return Pc(e,t)}function Lc(e,t={}){if(typeof e!=`string`)return!1;try{return Ic(e,t),!0}catch{return!1}}function Rc(e,t={}){let n=vc(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(Fc(i.slice(n,n+e),t.group));a=r.join(n)}else a=Fc(i,t.group);return`${t.prefix??``}${a}`}function zc(e,t={}){let n=Ic(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 Bc(e,t={}){let n=Ic(e,t);return{bytes:zc(n),format:Nc(e),normalized:n}}function Vc(e,t){return Rc(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 Hc(e){return new TextEncoder().encode(e)}function Uc(e){return new TextDecoder(`utf-8`,{fatal:!1}).decode(vc(e))}function Wc(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 Gc(e,t={}){let n=yc(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 Kc=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function qc(){return globalThis.Buffer}function Jc(e){return e.replace(/[\n\r\t ]/g,``)}function Yc(e){let t=e.length%4;return t?e+`=`.repeat(4-t):e}function Xc(e){if(typeof e!=`string`)return!1;let t=Jc(e);return t===``||Kc.test(t)}function Zc(e,t){let n=vc(e),r=qc();return r?r.from(n).toString(`base64`):btoa(xc(n))}function Qc(e,t){let n=Jc(e);if(!Xc(n))throw TypeError(`Input is not valid Base64 text`);let r=qc();return r?new Uint8Array(r.from(n,`base64`)):Sc(atob(n))}var $c={encode:Zc,decode:Qc,is:Xc,normalize:Jc,pad:Yc},el=/^[A-Za-z0-9_-]*$/;function tl(e){return e.replace(/[\n\r\t ]/g,``)}function nl(e){return typeof e==`string`&&el.test(tl(e))}function rl(e,t){return $c.encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function il(e,t){let n=tl(e);if(!nl(n))throw TypeError(`Input is not valid Base64Url text`);return $c.decode($c.pad(n.replace(/-/g,`+`).replace(/_/g,`/`)))}var al=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,ol=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function sl(e){if(!al.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function cl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ll(e){let t=e.trim().replace(/\r\n/g,`
|
|
32
32
|
`).split(`
|
|
33
|
-
`).map(e=>e.trim()).filter(Boolean),n={},r=0;for(;r<t.length;r++){let e=t[r],i=e.indexOf(`:`);if(i<=0)break;n[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:t.slice(r),base64Text:t.slice(r).join(``)}}function
|
|
33
|
+
`).map(e=>e.trim()).filter(Boolean),n={},r=0;for(;r<t.length;r++){let e=t[r],i=e.indexOf(`:`);if(i<=0)break;n[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:t.slice(r),base64Text:t.slice(r).join(``)}}function ul(e){return/\r\n/.test(e)?`\r
|
|
34
34
|
`:`
|
|
35
|
-
`}function
|
|
36
|
-
`,a=[`-----BEGIN ${e}-----`];if(n.headers){for(let[e,t]of Object.entries(n.headers))a.push(`${e}: ${t}`);a.push(``)}return a.push(...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(`
|
|
35
|
+
`}function dl(e,t={}){let n=[],r=t.label,i;for(ol.lastIndex=0;i=ol.exec(e);){let e=i[1].trim();if(r&&e!==r)continue;sl(e);let t=ll(i[2]);n.push({label:e,data:$c.decode(t.base64Text),headers:t.headers,lineLength:t.base64Lines[0]?.length??64,newline:ul(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 fl(e,t,n={}){sl(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(...cl($c.encode(t),r)),a.push(`-----END ${e}-----`),`${a.join(i)}${i}`}function pl(e,t={}){return dl(e,t).map(({lineLength:e,newline:t,...n})=>n)}function ml(e,t){let[n]=pl(e,{label:t,strict:!0});return n.data}function hl(e,t={}){let[n]=dl(e,{...t,strict:!0}),r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:fl(n.label,n.data,r)}}function gl(e,t){return fl(t.label,e,t)}var _l={name:`pem`,encode:(e,t)=>{if(!t?.label)throw TypeError(`PEM label is required`);return fl(t.label,e,t)},decode:(e,t)=>ml(e,t?.label),format:gl,is:e=>typeof e==`string`&&/-----BEGIN [^-]+-----/.test(e),parse:hl};function vl(e){return e.trim().toLowerCase()}function yl(e){return e instanceof Error?e:Error(String(e))}function bl(e,t,n){for(let t of[n.name,...n.aliases??[]])e.delete(vl(t));t.delete(vl(n.name))}function xl(e,t,n){let r=e[n];if(typeof r!=`function`)throw Error(`Converter '${t}' does not support ${n}()`);return r}function Sl(e,t,n){let r=vl(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 Cl(e=[]){let t=new Map,n=new Set,r={register(e,r={}){if(!e.name||!vl(e.name))throw TypeError(`Converter name is required`);let i=[...new Set([e.name,...e.aliases??[]].map(vl))],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)bl(t,n,e);for(let n of i)t.set(n,e);return n.add(vl(e.name)),this},unregister(e){let r=t.get(vl(e));return r?(bl(t,n,r),!0):!1},has(e){return t.has(vl(e))},get(e){let n=t.get(vl(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:yl(e)}}},normalize(e,t,n){let r=this.get(e);return xl(r,e,`normalize`).call(r,t,n)},parse(e,t,n){let r=this.get(e);return xl(r,e,`parse`).call(r,t,n)},format(e,t,n){let r=this.get(e);return xl(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(vl(e))),r=new Map;for(let t of n){let n=this.get(t),i=Sl(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}Cl([{name:`binary`,aliases:[`latin1`],encode:xc,decode:Sc,is:Cc},{name:`hex`,encode:Rc,decode:zc,format:Vc,is:Lc,normalize:Ic,parse:Bc},{name:`base64`,aliases:[`b64`],encode:Zc,decode:Qc,is:Xc,normalize:Jc},{name:`base64url`,aliases:[`base64-url`,`b64url`],encode:rl,decode:il,is:nl,normalize:tl},{name:`utf8`,aliases:[`utf-8`],encode:e=>Uc(e),decode:e=>Hc(e),is:e=>typeof e==`string`},{name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>Gc(e),decode:e=>Wc(e),is:e=>typeof e==`string`},{name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>Gc(e,{littleEndian:!0}),decode:e=>Wc(e,{littleEndian:!0}),is:e=>typeof e==`string`},_l]);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 wl=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if(gc(e))this.unusedBits=t,this.value=yc(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof Wo))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=yc(e.valueBlock.valueHex),this}toASN(){return new Wo({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Wo({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}},Tl=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):gc(e)?yc(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Vo))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=yc(e.valueBlock.valueHex),this}toASN(){return new Vo({valueHex:this.buffer})}toSchema(e){return new Vo({name:e})}},El={fromASN:e=>e instanceof Fo?null:yc(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new Fo;let t=Eo(e);if(t.result.error)throw Error(t.result.error);return t.result}},Dl={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Zo({value:+e})},Ol={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new $o({value:e})},kl={fromASN:e=>yc(e.valueBlock.valueHexView),toASN:e=>new Zo({valueHex:e})},Al={fromASN:e=>yc(e.valueBlock.valueHexView),toASN:e=>new Wo({valueHex:e})},jl={fromASN:e=>e.valueBlock.toString(),toASN:e=>new rs({value:e})},Ml={fromASN:e=>e.valueBlock.toString(),toASN:e=>new ss({value:e})},Nl={fromASN:e=>e.valueBlock.value,toASN:e=>new Ro({value:e})},Pl={fromASN:e=>yc(e.valueBlock.valueHexView),toASN:e=>new Vo({valueHex:e})},Fl={fromASN:e=>new Tl(e.getValue()),toASN:e=>e.toASN()};function Il(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var Ll=Il(_s),Rl=Il(bs),zl=Il(Cs),Bl=Il(Ts),Vl=Il(Ds),Hl=Il(ks),Ul=Il(js),Wl=Il(Ns),Gl=Il(Fs),Kl=Il(Ls),ql=Il(zs),Jl=Il(Vs),Yl={fromASN:e=>e.toDate(),toASN:e=>new Us({valueDate:e})},Xl={fromASN:e=>e.toDate(),toASN:e=>new Gs({valueDate:e})},Zl={fromASN:()=>null,toASN:()=>new Fo};function Ql(e){switch(e){case K.Any:return El;case K.BitString:return Al;case K.BmpString:return Rl;case K.Boolean:return Nl;case K.CharacterString:return Jl;case K.Enumerated:return Ol;case K.GeneralString:return ql;case K.GeneralizedTime:return Xl;case K.GraphicString:return Gl;case K.IA5String:return Wl;case K.Integer:return Dl;case K.Null:return Zl;case K.NumericString:return Bl;case K.ObjectIdentifier:return jl;case K.RelativeObjectIdentifier:return Ml;case K.OctetString:return Pl;case K.PrintableString:return Vl;case K.TeletexString:return Hl;case K.UTCTime:return Yl;case K.UniversalString:return zl;case K.Utf8String:return Ll;case K.VideotexString:return Ul;case K.VisibleString:return Kl;default:return null}}function $l(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:$l(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function eu(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||eu(t)}return!1}function tu(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 nu=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=Na[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:a})}else $l(i.type)?o=new i.type().toSchema(a):i.optional?this.get(i.type).type===G.Choice?o=new nc({name:a}):(o=this.create(i.type,!1),o.name=a):o=new nc({name:a});let s=!!i.optional||i.defaultValue!==void 0;if(i.repeated&&(o.name=``,o=new(i.repeated===`set`?ds:ls)({name:``,value:[new ic({name:a,value:o})]})),i.context!==null&&i.context!==void 0){if(i.implicit){if(typeof i.type==`number`||$l(i.type)){let e=i.repeated?Ao:po;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 Ao({name:e?``:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}}else r.push(new Ao({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 ls({value:r,name:``});case G.Set:return new ds({value:r,name:``});case G.Choice:return new rc({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;nu.has(t)?n=nu.get(t):(n=nu.createDefault(t),nu.set(t,n)),Object.assign(n,e)},J=e=>(t,n)=>{let r;nu.has(t.constructor)?r=nu.get(t.constructor):(r=nu.createDefault(t.constructor),nu.set(t.constructor,r));let i=Object.assign({},e);if(typeof i.type==`number`&&!i.converter){let r=Ql(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},ru=class extends Error{schemas=[]},iu=class{static parse(e,t,n){let r=Eo(yc(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($l(t))return new t().fromASN(e);let r=nu.get(t);nu.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 eu(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof ru&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,r,i){if(e.constructor===Ao&&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`&&nu.has(a.type)){let t=nu.get(a.type);if(t&&t.type===G.Sequence){let t=new ls;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===Ao&&t.type!==G.Choice){let n=new Ao({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=oc({},e,r);if(!t.verified)throw new ru(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=oc({},e,r);if(!t.verified)throw new ru(`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=Ql(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=Ql(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`&&nu.has(e.type)&&nu.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 ru&&/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=Ql(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`||$l(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??($l(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`?ls:ds);i.valueBlock=e.valueBlock;let a=Eo(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($l(n))e=new n().toSchema(``);else{let t=K[n],r=Na[t];if(!r)throw Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=a.valueBlock,a=Eo(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 ru&&/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=nu.get(n);if(t.type===G.Sequence){let t=new ls;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 ds;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}},au=class e{static serialize(e){return e instanceof so?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&$l(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,r=nu.get(n);nu.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=Ql(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`&&tu(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`||$l(o.type))){let e={};e.valueHex=c instanceof Fo?yc(c.valueBeforeDecodeView):c.valueBlock.toBER(),i.push(new po({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else i.push(new Ao({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:c.valueBlock.value}))}else i.push(new Ao({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 ls({value:i});break;case G.Set:a=new ds({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`?ls:ds)({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`?ls:ds)({value:t})}else i=this.toASN(r);return i}},ou=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 au.serialize(e)}static parse(e,t,n){return iu.parse(e,t,n)}static toString(t,n){let r=Eo(gc(t)?yc(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 su(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 cu(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 lu=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(Rc(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}},uu,du,fu,pu=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})],pu.prototype,`teletexString`,void 0),X([J({type:K.PrintableString})],pu.prototype,`printableString`,void 0),X([J({type:K.UniversalString})],pu.prototype,`universalString`,void 0),X([J({type:K.Utf8String})],pu.prototype,`utf8String`,void 0),X([J({type:K.BmpString})],pu.prototype,`bmpString`,void 0),pu=X([q({type:G.Choice})],pu);var mu=class extends pu{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Rc(this.anyValue):super.toString())}};X([J({type:K.IA5String})],mu.prototype,`ia5String`,void 0),X([J({type:K.Any})],mu.prototype,`anyValue`,void 0),mu=X([q({type:G.Choice})],mu);var hu=class{type=``;value=new mu;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],hu.prototype,`type`,void 0),X([J({type:mu})],hu.prototype,`value`,void 0);var gu=uu=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,uu.prototype)}};gu=uu=X([q({type:G.Set,itemType:hu})],gu);var _u=du=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,du.prototype)}};_u=du=X([q({type:G.Sequence,itemType:gu})],_u);var vu=fu=class extends _u{constructor(e){super(e),Object.setPrototypeOf(this,fu.prototype)}};vu=fu=X([q({type:G.Sequence})],vu);var yu={fromASN:e=>lu.toString(Pl.fromASN(e)),toASN:e=>Pl.toASN(lu.fromString(e))},bu=class{typeId=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],bu.prototype,`typeId`,void 0),X([J({type:K.Any,context:0})],bu.prototype,`value`,void 0);var xu=class{nameAssigner;partyName=new pu;constructor(e={}){Object.assign(this,e)}};X([J({type:pu,optional:!0,context:0,implicit:!0})],xu.prototype,`nameAssigner`,void 0),X([J({type:pu,context:1,implicit:!0})],xu.prototype,`partyName`,void 0);var Su=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};X([J({type:bu,context:0,implicit:!0})],Su.prototype,`otherName`,void 0),X([J({type:K.IA5String,context:1,implicit:!0})],Su.prototype,`rfc822Name`,void 0),X([J({type:K.IA5String,context:2,implicit:!0})],Su.prototype,`dNSName`,void 0),X([J({type:K.Any,context:3,implicit:!0})],Su.prototype,`x400Address`,void 0),X([J({type:vu,context:4,implicit:!1})],Su.prototype,`directoryName`,void 0),X([J({type:xu,context:5})],Su.prototype,`ediPartyName`,void 0),X([J({type:K.IA5String,context:6,implicit:!0})],Su.prototype,`uniformResourceIdentifier`,void 0),X([J({type:K.OctetString,context:7,implicit:!0,converter:yu})],Su.prototype,`iPAddress`,void 0),X([J({type:K.ObjectIdentifier,context:8,implicit:!0})],Su.prototype,`registeredID`,void 0),Su=X([q({type:G.Choice})],Su);var Cu=`1.3.6.1.5.5.7`,wu=`${Cu}.1`,Tu=`${Cu}.2`,Eu=`${Cu}.3`,Du=`${Cu}.48`;`${Tu}`,`${Tu}`;var Ou=`${Du}.1`,ku=`${Du}.2`,Au=`${Du}.3`,ju=`${Du}.5`,Mu=`2.5.29`,Nu,Pu=`${wu}.1`,Fu=class{accessMethod=``;accessLocation=new Su;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Fu.prototype,`accessMethod`,void 0),X([J({type:Su})],Fu.prototype,`accessLocation`,void 0);var Iu=Nu=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Nu.prototype)}};Iu=Nu=X([q({type:G.Sequence,itemType:Fu})],Iu);var Lu=`${Mu}.35`,Ru=class extends Tl{},zu=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};X([J({type:Ru,context:0,optional:!0,implicit:!0})],zu.prototype,`keyIdentifier`,void 0),X([J({type:Su,context:1,optional:!0,implicit:!0,repeated:`sequence`})],zu.prototype,`authorityCertIssuer`,void 0),X([J({type:K.Integer,context:2,optional:!0,implicit:!0,converter:kl})],zu.prototype,`authorityCertSerialNumber`,void 0);var Bu=`${Mu}.19`,Vu=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Boolean,defaultValue:!1})],Vu.prototype,`cA`,void 0),X([J({type:K.Integer,optional:!0})],Vu.prototype,`pathLenConstraint`,void 0);var Hu,Uu=Hu=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};Uu=Hu=X([q({type:G.Sequence,itemType:Su})],Uu);var Wu;`${Mu}`;var Gu=Wu=class extends Uu{constructor(e){super(e),Object.setPrototypeOf(this,Wu.prototype)}};Gu=Wu=X([q({type:G.Sequence})],Gu);var Ku,qu=`${Mu}.32`;`${qu}`;var Ju=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})],Ju.prototype,`ia5String`,void 0),X([J({type:K.VisibleString})],Ju.prototype,`visibleString`,void 0),X([J({type:K.BmpString})],Ju.prototype,`bmpString`,void 0),X([J({type:K.Utf8String})],Ju.prototype,`utf8String`,void 0),Ju=X([q({type:G.Choice})],Ju);var Yu=class{organization=new Ju;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Ju})],Yu.prototype,`organization`,void 0),X([J({type:K.Integer,repeated:`sequence`})],Yu.prototype,`noticeNumbers`,void 0);var Xu=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};X([J({type:Yu,optional:!0})],Xu.prototype,`noticeRef`,void 0),X([J({type:Ju,optional:!0})],Xu.prototype,`explicitText`,void 0);var Zu=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};X([J({type:K.IA5String})],Zu.prototype,`cPSuri`,void 0),X([J({type:Xu})],Zu.prototype,`userNotice`,void 0),Zu=X([q({type:G.Choice})],Zu);var Qu=class{policyQualifierId=``;qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Qu.prototype,`policyQualifierId`,void 0),X([J({type:K.Any})],Qu.prototype,`qualifier`,void 0);var $u=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],$u.prototype,`policyIdentifier`,void 0),X([J({type:Qu,repeated:`sequence`,optional:!0})],$u.prototype,`policyQualifiers`,void 0);var ed=Ku=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Ku.prototype)}};ed=Ku=X([q({type:G.Sequence,itemType:$u})],ed),`${Mu}`;var td=class{value;constructor(e=0){this.value=e}};X([J({type:K.Integer})],td.prototype,`value`,void 0),td=X([q({type:G.Choice})],td),`${Mu}`;var nd=class extends td{};nd=X([q({type:G.Choice})],nd);var rd,id=`${Mu}.31`,ad;(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`})(ad||={});var od=class extends wl{toJSON(){let e=[],t=this.toNumber();return t&ad.aACompromise&&e.push(`aACompromise`),t&ad.affiliationChanged&&e.push(`affiliationChanged`),t&ad.cACompromise&&e.push(`cACompromise`),t&ad.certificateHold&&e.push(`certificateHold`),t&ad.cessationOfOperation&&e.push(`cessationOfOperation`),t&ad.keyCompromise&&e.push(`keyCompromise`),t&ad.privilegeWithdrawn&&e.push(`privilegeWithdrawn`),t&ad.superseded&&e.push(`superseded`),t&ad.unused&&e.push(`unused`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},sd=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:Su,context:0,repeated:`sequence`,implicit:!0})],sd.prototype,`fullName`,void 0),X([J({type:gu,context:1,implicit:!0})],sd.prototype,`nameRelativeToCRLIssuer`,void 0),sd=X([q({type:G.Choice})],sd);var cd=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:sd,context:0,optional:!0})],cd.prototype,`distributionPoint`,void 0),X([J({type:od,context:1,optional:!0,implicit:!0})],cd.prototype,`reasons`,void 0),X([J({type:Su,context:2,optional:!0,repeated:`sequence`,implicit:!0})],cd.prototype,`cRLIssuer`,void 0);var ld=rd=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,rd.prototype)}};ld=rd=X([q({type:G.Sequence,itemType:cd})],ld);var ud;`${Mu}`;var dd=ud=class extends ld{constructor(e){super(e),Object.setPrototypeOf(this,ud.prototype)}};dd=ud=X([q({type:G.Sequence,itemType:cd})],dd),`${Mu}`;var fd=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:sd,context:0,optional:!0})],fd.prototype,`distributionPoint`,void 0),X([J({type:K.Boolean,context:1,defaultValue:fd.ONLY,implicit:!0})],fd.prototype,`onlyContainsUserCerts`,void 0),X([J({type:K.Boolean,context:2,defaultValue:fd.ONLY,implicit:!0})],fd.prototype,`onlyContainsCACerts`,void 0),X([J({type:od,context:3,optional:!0,implicit:!0})],fd.prototype,`onlySomeReasons`,void 0),X([J({type:K.Boolean,context:4,defaultValue:fd.ONLY,implicit:!0})],fd.prototype,`indirectCRL`,void 0),X([J({type:K.Boolean,context:5,defaultValue:fd.ONLY,implicit:!0})],fd.prototype,`onlyContainsAttributeCerts`,void 0),`${Mu}`;var pd;(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`})(pd||={});var md=class{reason=pd.unspecified;constructor(e=pd.unspecified){this.reason=e}toJSON(){return pd[this.reason]}toString(){return this.toJSON()}};X([J({type:K.Enumerated})],md.prototype,`reason`,void 0),md=X([q({type:G.Choice})],md);var hd,gd=`${Mu}.37`,_d=hd=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,hd.prototype)}};_d=hd=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],_d),`${gd}`;var vd=`${Eu}.1`,yd=`${Eu}.2`,bd=`${Eu}.3`,xd=`${Eu}.4`,Sd=`${Eu}.8`,Cd=`${Eu}.9`;`${Mu}`;var wd=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};X([J({type:K.Integer,converter:kl})],wd.prototype,`value`,void 0),wd=X([q({type:G.Choice})],wd),`${Mu}`;var Td=class{value=new Date;constructor(e){e&&(this.value=e)}};X([J({type:K.GeneralizedTime})],Td.prototype,`value`,void 0),Td=X([q({type:G.Choice})],Td);var Ed,Dd=`${Mu}.18`,Od=Ed=class extends Uu{constructor(e){super(e),Object.setPrototypeOf(this,Ed.prototype)}};Od=Ed=X([q({type:G.Sequence})],Od);var kd=`${Mu}.15`,Ad;(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`})(Ad||={});var jd=class extends wl{toJSON(){let e=this.toNumber(),t=[];return e&Ad.cRLSign&&t.push(`crlSign`),e&Ad.dataEncipherment&&t.push(`dataEncipherment`),e&Ad.decipherOnly&&t.push(`decipherOnly`),e&Ad.digitalSignature&&t.push(`digitalSignature`),e&Ad.encipherOnly&&t.push(`encipherOnly`),e&Ad.keyAgreement&&t.push(`keyAgreement`),e&Ad.keyCertSign&&t.push(`keyCertSign`),e&Ad.keyEncipherment&&t.push(`keyEncipherment`),e&Ad.nonRepudiation&&t.push(`nonRepudiation`),t}toString(){return`[${this.toJSON().join(`, `)}]`}},Md;`${Mu}`;var Nd=class{base=new Su;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};X([J({type:Su})],Nd.prototype,`base`,void 0),X([J({type:K.Integer,context:0,defaultValue:0,implicit:!0})],Nd.prototype,`minimum`,void 0),X([J({type:K.Integer,context:1,optional:!0,implicit:!0})],Nd.prototype,`maximum`,void 0);var Pd=Md=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Md.prototype)}};Pd=Md=X([q({type:G.Sequence,itemType:Nd})],Pd);var Fd=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};X([J({type:Pd,context:0,optional:!0,implicit:!0})],Fd.prototype,`permittedSubtrees`,void 0),X([J({type:Pd,context:1,optional:!0,implicit:!0})],Fd.prototype,`excludedSubtrees`,void 0),`${Mu}`;var Id=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,implicit:!0,optional:!0,converter:kl})],Id.prototype,`requireExplicitPolicy`,void 0),X([J({type:K.Integer,context:1,implicit:!0,optional:!0,converter:kl})],Id.prototype,`inhibitPolicyMapping`,void 0);var Ld;`${Mu}`;var Rd=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Rd.prototype,`issuerDomainPolicy`,void 0),X([J({type:K.ObjectIdentifier})],Rd.prototype,`subjectDomainPolicy`,void 0);var zd=Ld=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Ld.prototype)}};zd=Ld=X([q({type:G.Sequence,itemType:Rd})],zd);var Bd,Vd=`${Mu}.17`,Hd=Bd=class extends Uu{constructor(e){super(e),Object.setPrototypeOf(this,Bd.prototype)}};Hd=Bd=X([q({type:G.Sequence})],Hd);var Ud=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ud.prototype,`type`,void 0),X([J({type:K.Any,repeated:`set`})],Ud.prototype,`values`,void 0);var Wd;`${Mu}`;var Gd=Wd=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Wd.prototype)}};Gd=Wd=X([q({type:G.Sequence,itemType:Ud})],Gd);var Kd=`${Mu}.14`,qd=class extends Ru{};`${Mu}`;var Jd=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime,context:0,implicit:!0,optional:!0})],Jd.prototype,`notBefore`,void 0),X([J({type:K.GeneralizedTime,context:1,implicit:!0,optional:!0})],Jd.prototype,`notAfter`,void 0);var Yd;(function(e){e[e.keyUpdateAllowed=1]=`keyUpdateAllowed`,e[e.newExtensions=2]=`newExtensions`,e[e.pKIXCertificate=4]=`pKIXCertificate`})(Yd||={});var Xd=class extends wl{toJSON(){let e=[],t=this.toNumber();return t&Yd.pKIXCertificate&&e.push(`pKIXCertificate`),t&Yd.newExtensions&&e.push(`newExtensions`),t&Yd.keyUpdateAllowed&&e.push(`keyUpdateAllowed`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},Zd=class{entrustVers=``;entrustInfoFlags=new Xd;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralString})],Zd.prototype,`entrustVers`,void 0),X([J({type:Xd})],Zd.prototype,`entrustInfoFlags`,void 0);var Qd;`${wu}`;var $d=Qd=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Qd.prototype)}};$d=Qd=X([q({type:G.Sequence,itemType:Fu})],$d);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&&bc(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 ef=class{algorithm=new Z;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],ef.prototype,`algorithm`,void 0),X([J({type:K.BitString})],ef.prototype,`subjectPublicKey`,void 0);var tf=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})],tf.prototype,`utcTime`,void 0),X([J({type:K.GeneralizedTime})],tf.prototype,`generalTime`,void 0),tf=X([q({type:G.Choice})],tf);var nf=class{notBefore=new tf(new Date);notAfter=new tf(new Date);constructor(e){e&&(this.notBefore=new tf(e.notBefore),this.notAfter=new tf(e.notAfter))}};X([J({type:tf})],nf.prototype,`notBefore`,void 0),X([J({type:tf})],nf.prototype,`notAfter`,void 0);var rf,af=class e{static CRITICAL=!1;extnID=``;critical=e.CRITICAL;extnValue=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],af.prototype,`extnID`,void 0),X([J({type:K.Boolean,defaultValue:af.CRITICAL})],af.prototype,`critical`,void 0),X([J({type:Tl})],af.prototype,`extnValue`,void 0);var of=rf=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,rf.prototype)}};of=rf=X([q({type:G.Sequence,itemType:af})],of);var sf;(function(e){e[e.v1=0]=`v1`,e[e.v2=1]=`v2`,e[e.v3=2]=`v3`})(sf||={});var cf=class{version=sf.v1;serialNumber=new ArrayBuffer(0);signature=new Z;issuer=new vu;validity=new nf;subject=new vu;subjectPublicKeyInfo=new ef;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,defaultValue:sf.v1})],cf.prototype,`version`,void 0),X([J({type:K.Integer,converter:kl})],cf.prototype,`serialNumber`,void 0),X([J({type:Z})],cf.prototype,`signature`,void 0),X([J({type:vu})],cf.prototype,`issuer`,void 0),X([J({type:nf})],cf.prototype,`validity`,void 0),X([J({type:vu})],cf.prototype,`subject`,void 0),X([J({type:ef})],cf.prototype,`subjectPublicKeyInfo`,void 0),X([J({type:K.BitString,context:1,implicit:!0,optional:!0})],cf.prototype,`issuerUniqueID`,void 0),X([J({type:K.BitString,context:2,implicit:!0,optional:!0})],cf.prototype,`subjectUniqueID`,void 0),X([J({type:of,context:3,optional:!0})],cf.prototype,`extensions`,void 0);var lf=class{tbsCertificate=new cf;tbsCertificateRaw;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:cf,raw:!0})],lf.prototype,`tbsCertificate`,void 0),X([J({type:Z})],lf.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],lf.prototype,`signatureValue`,void 0);var uf=class{userCertificate=new ArrayBuffer(0);revocationDate=new tf;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:kl})],uf.prototype,`userCertificate`,void 0),X([J({type:tf})],uf.prototype,`revocationDate`,void 0),X([J({type:af,optional:!0,repeated:`sequence`})],uf.prototype,`crlEntryExtensions`,void 0);var df=class{version;signature=new Z;issuer=new vu;thisUpdate=new tf;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],df.prototype,`version`,void 0),X([J({type:Z})],df.prototype,`signature`,void 0),X([J({type:vu})],df.prototype,`issuer`,void 0),X([J({type:tf})],df.prototype,`thisUpdate`,void 0),X([J({type:tf,optional:!0})],df.prototype,`nextUpdate`,void 0),X([J({type:uf,repeated:`sequence`,optional:!0})],df.prototype,`revokedCertificates`,void 0),X([J({type:af,optional:!0,context:0,repeated:`sequence`})],df.prototype,`crlExtensions`,void 0);var ff=class{tbsCertList=new df;tbsCertListRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:df,raw:!0})],ff.prototype,`tbsCertList`,void 0),X([J({type:Z})],ff.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],ff.prototype,`signature`,void 0);var pf=class{issuer=new vu;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:vu})],pf.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:kl})],pf.prototype,`serialNumber`,void 0);var mf=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:qd,context:0,implicit:!0})],mf.prototype,`subjectKeyIdentifier`,void 0),X([J({type:pf})],mf.prototype,`issuerAndSerialNumber`,void 0),mf=X([q({type:G.Choice})],mf);var hf;(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`})(hf||={});var gf=class extends Z{};gf=X([q({type:G.Sequence})],gf);var _f=class extends Z{};_f=X([q({type:G.Sequence})],_f);var vf=class extends Z{};vf=X([q({type:G.Sequence})],vf);var yf=class extends Z{};yf=X([q({type:G.Sequence})],yf);var bf=class extends Z{};bf=X([q({type:G.Sequence})],bf);var xf=class extends Z{};xf=X([q({type:G.Sequence})],xf);var Sf=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Sf.prototype,`attrType`,void 0),X([J({type:K.Any,repeated:`set`})],Sf.prototype,`attrValues`,void 0);var Cf,wf=class{version=hf.v0;sid=new mf;digestAlgorithm=new gf;signedAttrs;signedAttrsRaw;signatureAlgorithm=new _f;signature=new Tl;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],wf.prototype,`version`,void 0),X([J({type:mf})],wf.prototype,`sid`,void 0),X([J({type:gf})],wf.prototype,`digestAlgorithm`,void 0),X([J({type:Sf,repeated:`set`,context:0,implicit:!0,optional:!0,raw:!0})],wf.prototype,`signedAttrs`,void 0),X([J({type:_f})],wf.prototype,`signatureAlgorithm`,void 0),X([J({type:Tl})],wf.prototype,`signature`,void 0),X([J({type:Sf,repeated:`set`,context:1,implicit:!0,optional:!0})],wf.prototype,`unsignedAttrs`,void 0);var Tf=Cf=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Cf.prototype)}};Tf=Cf=X([q({type:G.Set,itemType:wf})],Tf);var Ef=class extends wf{};Ef=X([q({type:G.Sequence})],Ef);var Df=class extends tf{};Df=X([q({type:G.Choice})],Df);var Of=class{acIssuer=new Su;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Su})],Of.prototype,`acIssuer`,void 0),X([J({type:K.Integer})],Of.prototype,`acSerial`,void 0),X([J({type:Ud,repeated:`sequence`})],Of.prototype,`attrs`,void 0);var kf,Af=kf=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,kf.prototype)}};Af=kf=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],Af);var jf=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],jf.prototype,`pathLenConstraint`,void 0),X([J({type:Af,implicit:!0,context:0,optional:!0})],jf.prototype,`permittedAttrs`,void 0),X([J({type:Af,implicit:!0,context:1,optional:!0})],jf.prototype,`excludedAttrs`,void 0),X([J({type:K.Boolean,defaultValue:!0})],jf.prototype,`permitUnSpecified`,void 0);var Mf=class{issuer=new Uu;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Uu})],Mf.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:kl})],Mf.prototype,`serial`,void 0),X([J({type:K.BitString,optional:!0})],Mf.prototype,`issuerUID`,void 0);var Nf;(function(e){e[e.publicKey=0]=`publicKey`,e[e.publicKeyCert=1]=`publicKeyCert`,e[e.otherObjectTypes=2]=`otherObjectTypes`})(Nf||={});var Pf=class{digestedObjectType=Nf.publicKey;otherObjectTypeID;digestAlgorithm=new Z;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Enumerated})],Pf.prototype,`digestedObjectType`,void 0),X([J({type:K.ObjectIdentifier,optional:!0})],Pf.prototype,`otherObjectTypeID`,void 0),X([J({type:Z})],Pf.prototype,`digestAlgorithm`,void 0),X([J({type:K.BitString})],Pf.prototype,`objectDigest`,void 0);var Ff=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,optional:!0})],Ff.prototype,`issuerName`,void 0),X([J({type:Mf,context:0,implicit:!0,optional:!0})],Ff.prototype,`baseCertificateID`,void 0),X([J({type:Pf,context:1,implicit:!0,optional:!0})],Ff.prototype,`objectDigestInfo`,void 0);var If=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};X([J({type:Su,repeated:`sequence`})],If.prototype,`v1Form`,void 0),X([J({type:Ff,context:0,implicit:!0})],If.prototype,`v2Form`,void 0),If=X([q({type:G.Choice})],If);var Lf=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime})],Lf.prototype,`notBeforeTime`,void 0),X([J({type:K.GeneralizedTime})],Lf.prototype,`notAfterTime`,void 0);var Rf=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Mf,implicit:!0,context:0,optional:!0})],Rf.prototype,`baseCertificateID`,void 0),X([J({type:Uu,implicit:!0,context:1,optional:!0})],Rf.prototype,`entityName`,void 0),X([J({type:Pf,implicit:!0,context:2,optional:!0})],Rf.prototype,`objectDigestInfo`,void 0);var zf;(function(e){e[e.v2=1]=`v2`})(zf||={});var Bf=class{version=zf.v2;holder=new Rf;issuer=new If;signature=new Z;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Lf;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Bf.prototype,`version`,void 0),X([J({type:Rf})],Bf.prototype,`holder`,void 0),X([J({type:If})],Bf.prototype,`issuer`,void 0),X([J({type:Z})],Bf.prototype,`signature`,void 0),X([J({type:K.Integer,converter:kl})],Bf.prototype,`serialNumber`,void 0),X([J({type:Lf})],Bf.prototype,`attrCertValidityPeriod`,void 0),X([J({type:Ud,repeated:`sequence`})],Bf.prototype,`attributes`,void 0),X([J({type:K.BitString,optional:!0})],Bf.prototype,`issuerUniqueID`,void 0),X([J({type:of,optional:!0})],Bf.prototype,`extensions`,void 0);var Vf=class{acinfo=new Bf;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Bf})],Vf.prototype,`acinfo`,void 0),X([J({type:Z})],Vf.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Vf.prototype,`signatureValue`,void 0);var Hf;(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`})(Hf||={});var Uf=class extends wl{},Wf=class{type=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier,implicit:!0,context:0})],Wf.prototype,`type`,void 0),X([J({type:K.Any,implicit:!0,context:1})],Wf.prototype,`value`,void 0);var Gf=class{policyId=``;classList=new Uf(Hf.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Gf.prototype,`policyId`,void 0),X([J({type:Uf,defaultValue:new Uf(Hf.unclassified)})],Gf.prototype,`classList`,void 0),X([J({type:Wf,repeated:`set`})],Gf.prototype,`securityCategories`,void 0);var Kf=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};X([J({type:Tl})],Kf.prototype,`cotets`,void 0),X([J({type:K.ObjectIdentifier})],Kf.prototype,`oid`,void 0),X([J({type:K.Utf8String})],Kf.prototype,`string`,void 0);var qf=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,implicit:!0,context:0,optional:!0})],qf.prototype,`policyAuthority`,void 0),X([J({type:Kf,repeated:`sequence`})],qf.prototype,`values`,void 0),`${wu}`,`${wu}`,`${wu}`,`${Mu}`;var Jf=`${Cu}.10`;`${Jf}`,`${Jf}`,`${Jf}`,`${Jf}`,`${Jf}`;var Yf=`2.5.4`;`${Yf}`;var Xf,Zf=class{targetCertificate=new Mf;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Mf})],Zf.prototype,`targetCertificate`,void 0),X([J({type:Su,optional:!0})],Zf.prototype,`targetName`,void 0),X([J({type:Pf,optional:!0})],Zf.prototype,`certDigestInfo`,void 0);var Qf=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};X([J({type:Su,context:0,implicit:!0})],Qf.prototype,`targetName`,void 0),X([J({type:Su,context:1,implicit:!0})],Qf.prototype,`targetGroup`,void 0),X([J({type:Zf,context:2,implicit:!0})],Qf.prototype,`targetCert`,void 0),Qf=X([q({type:G.Choice})],Qf);var $f=Xf=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Xf.prototype)}};$f=Xf=X([q({type:G.Sequence,itemType:Qf})],$f);var ep,tp=ep=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,ep.prototype)}};tp=ep=X([q({type:G.Sequence,itemType:$f})],tp);var np=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,implicit:!0,context:0,optional:!0})],np.prototype,`roleAuthority`,void 0),X([J({type:Su,implicit:!0,context:1})],np.prototype,`roleName`,void 0);var rp=class{service=new Su;ident=new Su;authInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Su})],rp.prototype,`service`,void 0),X([J({type:Su})],rp.prototype,`ident`,void 0),X([J({type:Tl,optional:!0})],rp.prototype,`authInfo`,void 0);var ip,ap=class{otherCertFormat=``;otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ap.prototype,`otherCertFormat`,void 0),X([J({type:K.Any})],ap.prototype,`otherCert`,void 0);var op=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};X([J({type:lf})],op.prototype,`certificate`,void 0),X([J({type:Vf,context:2,implicit:!0})],op.prototype,`v2AttrCert`,void 0),X([J({type:ap,context:3,implicit:!0})],op.prototype,`other`,void 0),op=X([q({type:G.Choice})],op);var sp=ip=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,ip.prototype)}};sp=ip=X([q({type:G.Set,itemType:op})],sp);var cp=class{contentType=``;content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],cp.prototype,`contentType`,void 0),X([J({type:K.Any,context:0})],cp.prototype,`content`,void 0);var lp=class{single;any;constructor(e={}){Object.assign(this,e)}};X([J({type:Tl})],lp.prototype,`single`,void 0),X([J({type:K.Any})],lp.prototype,`any`,void 0),lp=X([q({type:G.Choice})],lp);var up=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],up.prototype,`eContentType`,void 0),X([J({type:lp,context:0,optional:!0})],up.prototype,`eContent`,void 0);var dp=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};X([J({type:Tl,context:0,implicit:!0,optional:!0})],dp.prototype,`value`,void 0),X([J({type:Tl,converter:Fl,context:0,implicit:!0,optional:!0,repeated:`sequence`})],dp.prototype,`constructedValue`,void 0),dp=X([q({type:G.Choice})],dp);var fp=class{contentType=``;contentEncryptionAlgorithm=new yf;encryptedContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],fp.prototype,`contentType`,void 0),X([J({type:yf})],fp.prototype,`contentEncryptionAlgorithm`,void 0),X([J({type:dp,optional:!0})],fp.prototype,`encryptedContent`,void 0);var pp=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],pp.prototype,`keyAttrId`,void 0),X([J({type:K.Any,optional:!0})],pp.prototype,`keyAttr`,void 0);var mp,hp=class{subjectKeyIdentifier=new qd;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:qd})],hp.prototype,`subjectKeyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],hp.prototype,`date`,void 0),X([J({type:pp,optional:!0})],hp.prototype,`other`,void 0);var gp=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:hp,context:0,implicit:!0,optional:!0})],gp.prototype,`rKeyId`,void 0),X([J({type:pf,optional:!0})],gp.prototype,`issuerAndSerialNumber`,void 0),gp=X([q({type:G.Choice})],gp);var _p=class{rid=new gp;encryptedKey=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:gp})],_p.prototype,`rid`,void 0),X([J({type:Tl})],_p.prototype,`encryptedKey`,void 0);var vp=mp=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,mp.prototype)}};vp=mp=X([q({type:G.Sequence,itemType:_p})],vp);var yp=class{algorithm=new Z;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],yp.prototype,`algorithm`,void 0),X([J({type:K.BitString})],yp.prototype,`publicKey`,void 0);var bp=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:qd,context:0,implicit:!0,optional:!0})],bp.prototype,`subjectKeyIdentifier`,void 0),X([J({type:yp,context:1,implicit:!0,optional:!0})],bp.prototype,`originatorKey`,void 0),X([J({type:pf,optional:!0})],bp.prototype,`issuerAndSerialNumber`,void 0),bp=X([q({type:G.Choice})],bp);var xp=class{version=hf.v3;originator=new bp;ukm;keyEncryptionAlgorithm=new vf;recipientEncryptedKeys=new vp;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],xp.prototype,`version`,void 0),X([J({type:bp,context:0})],xp.prototype,`originator`,void 0),X([J({type:Tl,context:1,optional:!0})],xp.prototype,`ukm`,void 0),X([J({type:vf})],xp.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:vp})],xp.prototype,`recipientEncryptedKeys`,void 0);var Sp=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:qd,context:0,implicit:!0})],Sp.prototype,`subjectKeyIdentifier`,void 0),X([J({type:pf})],Sp.prototype,`issuerAndSerialNumber`,void 0),Sp=X([q({type:G.Choice})],Sp);var Cp=class{version=hf.v0;rid=new Sp;keyEncryptionAlgorithm=new vf;encryptedKey=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Cp.prototype,`version`,void 0),X([J({type:Sp})],Cp.prototype,`rid`,void 0),X([J({type:vf})],Cp.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:Tl})],Cp.prototype,`encryptedKey`,void 0);var wp=class{keyIdentifier=new Tl;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Tl})],wp.prototype,`keyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],wp.prototype,`date`,void 0),X([J({type:pp,optional:!0})],wp.prototype,`other`,void 0);var Tp=class{version=hf.v4;kekid=new wp;keyEncryptionAlgorithm=new vf;encryptedKey=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Tp.prototype,`version`,void 0),X([J({type:wp})],Tp.prototype,`kekid`,void 0),X([J({type:vf})],Tp.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:Tl})],Tp.prototype,`encryptedKey`,void 0);var Ep=class{version=hf.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new vf;encryptedKey=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Ep.prototype,`version`,void 0),X([J({type:xf,context:0,optional:!0})],Ep.prototype,`keyDerivationAlgorithm`,void 0),X([J({type:vf})],Ep.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:Tl})],Ep.prototype,`encryptedKey`,void 0);var Dp=class{oriType=``;oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Dp.prototype,`oriType`,void 0),X([J({type:K.Any})],Dp.prototype,`oriValue`,void 0);var Op=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};X([J({type:Cp,optional:!0})],Op.prototype,`ktri`,void 0),X([J({type:xp,context:1,implicit:!0,optional:!0})],Op.prototype,`kari`,void 0),X([J({type:Tp,context:2,implicit:!0,optional:!0})],Op.prototype,`kekri`,void 0),X([J({type:Ep,context:3,implicit:!0,optional:!0})],Op.prototype,`pwri`,void 0),X([J({type:Dp,context:4,implicit:!0,optional:!0})],Op.prototype,`ori`,void 0),Op=X([q({type:G.Choice})],Op);var kp,Ap=kp=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,kp.prototype)}};Ap=kp=X([q({type:G.Set,itemType:Op})],Ap);var jp,Mp=`${Cu}.16`;`${Mp}`,`${Mp}`;var Np=class{otherRevInfoFormat=``;otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Np.prototype,`otherRevInfoFormat`,void 0),X([J({type:K.Any})],Np.prototype,`otherRevInfo`,void 0);var Pp=class{other=new Np;constructor(e={}){Object.assign(this,e)}};X([J({type:Np,context:1,implicit:!0})],Pp.prototype,`other`,void 0),Pp=X([q({type:G.Choice})],Pp);var Fp=jp=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,jp.prototype)}};Fp=jp=X([q({type:G.Set,itemType:Pp})],Fp);var Ip=class{certs;crls;constructor(e={}){Object.assign(this,e)}};X([J({type:sp,context:0,implicit:!0,optional:!0})],Ip.prototype,`certs`,void 0),X([J({type:Fp,context:1,implicit:!0,optional:!0})],Ip.prototype,`crls`,void 0);var Lp,Rp=Lp=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Lp.prototype)}};Rp=Lp=X([q({type:G.Set,itemType:Sf})],Rp);var zp=class{version=hf.v0;originatorInfo;recipientInfos=new Ap;encryptedContentInfo=new fp;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],zp.prototype,`version`,void 0),X([J({type:Ip,context:0,implicit:!0,optional:!0})],zp.prototype,`originatorInfo`,void 0),X([J({type:Ap})],zp.prototype,`recipientInfos`,void 0),X([J({type:fp})],zp.prototype,`encryptedContentInfo`,void 0),X([J({type:Rp,context:1,implicit:!0,optional:!0})],zp.prototype,`unprotectedAttrs`,void 0);var Bp=`1.2.840.113549.1.7.2`,Vp,Hp=Vp=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Vp.prototype)}};Hp=Vp=X([q({type:G.Set,itemType:gf})],Hp);var Up=class{version=hf.v0;digestAlgorithms=new Hp;encapContentInfo=new up;certificates;crls;signerInfos=new Tf;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Up.prototype,`version`,void 0),X([J({type:Hp})],Up.prototype,`digestAlgorithms`,void 0),X([J({type:up})],Up.prototype,`encapContentInfo`,void 0),X([J({type:sp,context:0,implicit:!0,optional:!0})],Up.prototype,`certificates`,void 0),X([J({type:Fp,context:1,implicit:!0,optional:!0})],Up.prototype,`crls`,void 0),X([J({type:Tf})],Up.prototype,`signerInfos`,void 0);var Wp=`1.2.840.10045.2.1`,Gp=`1.2.840.10045.4.1`,Kp=`1.2.840.10045.4.3.1`,qp=`1.2.840.10045.4.3.2`,Jp=`1.2.840.10045.4.3.3`,Yp=`1.2.840.10045.4.3.4`,Xp=`1.2.840.10045.3.1.7`,Zp=`1.3.132.0.34`,Qp=`1.3.132.0.35`;function $p(e){return new Z({algorithm:e})}var em=$p(Gp);$p(Kp);var tm=$p(qp),nm=$p(Jp),rm=$p(Yp),im=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],im.prototype,`fieldType`,void 0),X([J({type:K.Any})],im.prototype,`parameters`,void 0),im=X([q({type:G.Sequence})],im);var am=class extends Tl{},om=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};X([J({type:K.OctetString})],om.prototype,`a`,void 0),X([J({type:K.OctetString})],om.prototype,`b`,void 0),X([J({type:K.BitString,optional:!0})],om.prototype,`seed`,void 0),om=X([q({type:G.Sequence})],om);var sm;(function(e){e[e.ecpVer1=1]=`ecpVer1`})(sm||={});var cm=class{version=sm.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],cm.prototype,`version`,void 0),X([J({type:im})],cm.prototype,`fieldID`,void 0),X([J({type:om})],cm.prototype,`curve`,void 0),X([J({type:am})],cm.prototype,`base`,void 0),X([J({type:K.Integer,converter:kl})],cm.prototype,`order`,void 0),X([J({type:K.Integer,optional:!0})],cm.prototype,`cofactor`,void 0),cm=X([q({type:G.Sequence})],cm);var lm=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],lm.prototype,`namedCurve`,void 0),X([J({type:K.Null})],lm.prototype,`implicitCurve`,void 0),X([J({type:cm})],lm.prototype,`specifiedCurve`,void 0),lm=X([q({type:G.Choice})],lm);var um=class{version=1;privateKey=new Tl;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],um.prototype,`version`,void 0),X([J({type:Tl})],um.prototype,`privateKey`,void 0),X([J({type:lm,context:0,optional:!0})],um.prototype,`parameters`,void 0),X([J({type:K.BitString,context:1,optional:!0})],um.prototype,`publicKey`,void 0);var dm=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:kl})],dm.prototype,`r`,void 0),X([J({type:K.Integer,converter:kl})],dm.prototype,`s`,void 0);var fm=`1.2.840.113549.1.1`,pm=`${fm}.1`,mm=`${fm}.7`,hm=`${fm}.9`,gm=`${fm}.10`,_m=`${fm}.2`,vm=`${fm}.4`,ym=`${fm}.5`,bm=`${fm}.14`,xm=`${fm}.11`,Sm=`${fm}.12`,Cm=`${fm}.13`,wm=`${fm}.15`,Tm=`${fm}.16`,Em=`1.3.14.3.2.26`,Dm=`2.16.840.1.101.3.4.2.4`,Om=`2.16.840.1.101.3.4.2.1`,km=`2.16.840.1.101.3.4.2.2`,Am=`2.16.840.1.101.3.4.2.3`,jm=`2.16.840.1.101.3.4.2.5`,Mm=`2.16.840.1.101.3.4.2.6`,Nm=`1.2.840.113549.2.2`,Pm=`1.2.840.113549.2.5`,Fm=`${fm}.8`;function Im(e){return new Z({algorithm:e,parameters:null})}Im(Nm),Im(Pm);var Lm=Im(Em);Im(Dm),Im(Om),Im(km),Im(Am),Im(jm),Im(Mm);var Rm=new Z({algorithm:Fm,parameters:Y.serialize(Lm)}),zm=new Z({algorithm:hm,parameters:Y.serialize(Pl.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Im(pm),Im(_m),Im(vm),Im(ym),Im(wm),Im(Tm),Im(Sm),Im(Cm),Im(wm),Im(Tm);var Bm=class{hashAlgorithm=new Z(Lm);maskGenAlgorithm=new Z({algorithm:Fm,parameters:Y.serialize(Lm)});pSourceAlgorithm=new Z(zm);constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Lm})],Bm.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:Rm})],Bm.prototype,`maskGenAlgorithm`,void 0),X([J({type:Z,context:2,defaultValue:zm})],Bm.prototype,`pSourceAlgorithm`,void 0),new Z({algorithm:mm,parameters:Y.serialize(new Bm)});var Vm=class{hashAlgorithm=new Z(Lm);maskGenAlgorithm=new Z({algorithm:Fm,parameters:Y.serialize(Lm)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Lm})],Vm.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:Rm})],Vm.prototype,`maskGenAlgorithm`,void 0),X([J({type:K.Integer,context:2,defaultValue:20})],Vm.prototype,`saltLength`,void 0),X([J({type:K.Integer,context:3,defaultValue:1})],Vm.prototype,`trailerField`,void 0),new Z({algorithm:gm,parameters:Y.serialize(new Vm)});var Hm=class{digestAlgorithm=new Z;digest=new Tl;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Hm.prototype,`digestAlgorithm`,void 0),X([J({type:Tl})],Hm.prototype,`digest`,void 0);var Um,Wm=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:kl})],Wm.prototype,`prime`,void 0),X([J({type:K.Integer,converter:kl})],Wm.prototype,`exponent`,void 0),X([J({type:K.Integer,converter:kl})],Wm.prototype,`coefficient`,void 0);var Gm=Um=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Um.prototype)}};Gm=Um=X([q({type:G.Sequence,itemType:Wm})],Gm);var Km=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})],Km.prototype,`version`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`publicExponent`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`privateExponent`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`prime1`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`prime2`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`exponent1`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`exponent2`,void 0),X([J({type:K.Integer,converter:kl})],Km.prototype,`coefficient`,void 0),X([J({type:Gm,optional:!0})],Km.prototype,`otherPrimeInfos`,void 0);var qm=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:kl})],qm.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:kl})],qm.prototype,`publicExponent`,void 0);var Jm;(function(e){e[e.Transient=0]=`Transient`,e[e.Singleton=1]=`Singleton`,e[e.ResolutionScoped=2]=`ResolutionScoped`,e[e.ContainerScoped=3]=`ContainerScoped`})(Jm||={});var Ym=Jm,Xm=function(e,t){return Xm=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])},Xm(e,t)};function Zm(e,t){Xm(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Qm(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 $m(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 eh(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 th(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 nh(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(th(arguments[t]));return e}function rh(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 ih(e){return!!e.useClass}function ah(e){return!!e.useFactory}var oh=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,nh(t))}}),t},e}();function sh(e){return typeof e==`string`||typeof e==`symbol`}function ch(e){return typeof e==`object`&&`token`in e&&`multiple`in e}function lh(e){return typeof e==`object`&&`token`in e&&`transform`in e}function uh(e){return typeof e==`function`||e instanceof oh}function dh(e){return!!e.useToken}function fh(e){return e.useValue!=null}function ph(e){return ih(e)||fh(e)||dh(e)||ah(e)}var mh=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}(),hh=function(e){Zm(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(mh),gh=function(){function e(){this.scopedResolutions=new Map}return e}();function _h(e,t){return e===null?`at position #`+t:`"`+e.split(`,`)[t].trim()+`" at position #`+t}function vh(e,t,n){return n===void 0&&(n=` `),nh([e],t.message.split(`
|
|
37
37
|
`).map(function(e){return n+e})).join(`
|
|
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[
|
|
40
|
-
`).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return Y.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||
|
|
41
|
-
`)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:U.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r=
|
|
42
|
-
`)}};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(`
|
|
38
|
+
`)}function yh(e,t,n){var r=th(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return vh(`Cannot inject the dependency `+_h(r===void 0?null:r,t)+` of "`+e.name+`" constructor. Reason:`,n)}function bh(e){return!(typeof e.dispose!=`function`||e.dispose.length>0)}var xh=function(e){Zm(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(mh),Sh=function(e){Zm(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(mh),Ch=function(){function e(){this.preResolution=new xh,this.postResolution=new Sh}return e}(),wh=new Map,Th=new(function(){function e(e){this.parent=e,this._registry=new hh,this.interceptors=new Ch,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:Ym.Transient}),this.ensureNotDisposed();var r=ph(t)?t:{useClass:t};if(dh(r))for(var i=[e],a=r;a!=null;){var o=a.useToken;if(i.includes(o))throw Error(`Token registration cycle detected! `+nh(i,[o]).join(` -> `));i.push(o);var s=this._registry.get(o);a=s&&dh(s.provider)?s.provider:null}if((n.lifecycle===Ym.Singleton||n.lifecycle==Ym.ContainerScoped||n.lifecycle==Ym.ResolutionScoped)&&(fh(r)||ah(r)))throw Error(`Cannot use lifecycle "`+Ym[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(),sh(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(),sh(e)){if(sh(t))return this.register(e,{useToken:t},{lifecycle:Ym.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Ym.Singleton});throw Error(`Cannot register a type name as a singleton without a "to" token`)}var n=e;return t&&!sh(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:Ym.Singleton})},e.prototype.resolve=function(e,t,n){t===void 0&&(t=new gh),n===void 0&&(n=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&sh(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(uh(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=eh(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=eh(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===Ym.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===Ym.Singleton,r=e.options.lifecycle===Ym.ContainerScoped,i=n||r,a=fh(e.provider)?e.provider.useValue:dh(e.provider)?i?e.instance||=this.resolve(e.provider.useToken,t):this.resolve(e.provider.useToken,t):ih(e.provider)?i?e.instance||=this.construct(e.provider.useClass,t):this.construct(e.provider.useClass,t):ah(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t);return e.options.lifecycle===Ym.ResolutionScoped&&t.scopedResolutions.set(e,a),a},e.prototype.resolveAll=function(e,t,n){var r=this;t===void 0&&(t=new gh),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&sh(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=eh(this._registry.entries()),r=n.next();!r.done;r=n.next()){var i=th(r.value,2),a=i[0],o=i[1];this._registry.setAll(a,o.filter(function(e){return!fh(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=eh(this._registry.entries()),a=i.next();!a.done;a=i.next()){var o=th(a.value,2),s=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===Ym.ContainerScoped})&&r._registry.setAll(s,c.map(function(e){return e.options.lifecycle===Ym.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 Qm(this,void 0,void 0,function(){var e;return $m(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 oh)return e.createProxy(function(e){return n.resolve(e,t)});var r=(function(){var r=wh.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,nh([void 0],i)))})();return bh(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 ch(r)?lh(r)?r.multiple?(a=n.resolve(r.transform)).transform.apply(a,nh([n.resolveAll(r.token,new gh,r.isOptional)],r.transformArgs)):(o=n.resolve(r.transform)).transform.apply(o,nh([n.resolve(r.token,e,r.isOptional)],r.transformArgs)):r.multiple?n.resolveAll(r.token,new gh,r.isOptional):n.resolve(r.token,e,r.isOptional):lh(r)?(s=n.resolve(r.transform,e)).transform.apply(s,nh([n.resolve(r.token,e)],r.transformArgs)):n.resolve(r,e)}catch(e){throw Error(yh(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 Eh(e){return function(t){wh.set(t,rh(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){Th.register(e,t)}):Th.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 Dh,Oh=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};X([J({type:K.ObjectIdentifier})],Oh.prototype,`attrId`,void 0),X([J({type:K.Any,repeated:`set`})],Oh.prototype,`attrValues`,void 0);var kh=Dh=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Dh.prototype)}};kh=Dh=X([q({type:G.Sequence,itemType:Oh})],kh);var Ah,jh=Ah=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Ah.prototype)}};jh=Ah=X([q({type:G.Sequence,itemType:cp})],jh);var Mh=`1.2.840.113549.1.12`,Nh=`${Mh}.1`;`${Nh}`,`${Nh}`,`${Nh}`,`${Nh}`,`${Nh}`,`${Nh}`;var Ph=`${Mh}.10.1`;`${Ph}`,`${Ph}`,`${Ph}`,`${Ph}`,`${Ph}`,`${Ph}`;var Fh=`1.2.840.113549.1.9`,Ih=class{certId=``;certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ih.prototype,`certId`,void 0),X([J({type:K.Any,context:0})],Ih.prototype,`certValue`,void 0);var Lh=`${Fh}.22`;`${Lh}`,`${Lh}`;var Rh=class{crlId=``;crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Rh.prototype,`crlId`,void 0),X([J({type:K.Any,context:0})],Rh.prototype,`crltValue`,void 0),`${Fh}`;var zh=class extends Tl{},Bh=class{encryptionAlgorithm=new Z;encryptedData=new zh;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Bh.prototype,`encryptionAlgorithm`,void 0),X([J({type:zh})],Bh.prototype,`encryptedData`,void 0);var Vh,Hh;(function(e){e[e.v1=0]=`v1`})(Hh||={});var Uh=class extends Tl{},Wh=Vh=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Vh.prototype)}};Wh=Vh=X([q({type:G.Sequence,itemType:Ud})],Wh);var Gh=class{version=Hh.v1;privateKeyAlgorithm=new Z;privateKey=new Uh;attributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Gh.prototype,`version`,void 0),X([J({type:Z})],Gh.prototype,`privateKeyAlgorithm`,void 0),X([J({type:Uh})],Gh.prototype,`privateKey`,void 0),X([J({type:Wh,implicit:!0,context:0,optional:!0})],Gh.prototype,`attributes`,void 0);var Kh=class extends Gh{};Kh=X([q({type:G.Sequence})],Kh);var qh=class extends Bh{};qh=X([q({type:G.Sequence})],qh);var Jh=class{secretTypeId=``;secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Jh.prototype,`secretTypeId`,void 0),X([J({type:K.Any,context:0})],Jh.prototype,`secretValue`,void 0);var Yh=class{mac=new Hm;macSalt=new Tl;iterations=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Hm})],Yh.prototype,`mac`,void 0),X([J({type:Tl})],Yh.prototype,`macSalt`,void 0),X([J({type:K.Integer,defaultValue:1})],Yh.prototype,`iterations`,void 0);var Xh=class{version=3;authSafe=new cp;macData=new Yh;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Xh.prototype,`version`,void 0),X([J({type:cp})],Xh.prototype,`authSafe`,void 0),X([J({type:Yh,optional:!0})],Xh.prototype,`macData`,void 0);var Zh,Qh=class{bagId=``;bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Qh.prototype,`bagId`,void 0),X([J({type:K.Any,context:0})],Qh.prototype,`bagValue`,void 0),X([J({type:Oh,repeated:`set`,optional:!0})],Qh.prototype,`bagAttributes`,void 0);var $h=Zh=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Zh.prototype)}};$h=Zh=X([q({type:G.Sequence,itemType:Qh})],$h);var eg,tg,ng,rg=`1.2.840.113549.1.9`;`${rg}`;var ig=`${rg}.24`,ag=`${rg}.25`,og=`${rg}.26`,sg=`${rg}.27`;`${ig}`,`${ig}`,`${rg}`,`${rg}`,`${rg}`,`${rg}`,`${rg}`,`${rg}`;var cg=`${rg}.7`;`${rg}`,`${rg}`,`${rg}`;var lg=`${rg}.14`;`${rg}`,`${rg}`,`${rg}`,`${ag}`,`${ag}`,`${ag}`,`${ag}`,`${ag}`;var ug=`1.3.6.1.5.5.7.9`;`${ug}`,`${ug}`,`${ug}`,`${ug}`,`${ug}`,`${og}`,`${og}`,`${sg}`,`${sg}`,`${rg}`,`${rg}`,`${rg}`,`${Yf}`;var dg=class extends pu{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};X([J({type:K.IA5String})],dg.prototype,`ia5String`,void 0),dg=X([q({type:G.Choice})],dg);var fg=class extends cp{};fg=X([q({type:G.Sequence})],fg);var pg=class extends Xh{};pg=X([q({type:G.Sequence})],pg);var mg=class extends Bh{};mg=X([q({type:G.Sequence})],mg);var hg=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.IA5String})],hg.prototype,`value`,void 0),hg=X([q({type:G.Choice})],hg);var gg=class extends dg{};gg=X([q({type:G.Choice})],gg);var _g=class extends pu{};_g=X([q({type:G.Choice})],_g);var vg=class{value;constructor(e=new Date){this.value=e}};X([J({type:K.GeneralizedTime})],vg.prototype,`value`,void 0),vg=X([q({type:G.Choice})],vg);var yg=class extends pu{};yg=X([q({type:G.Choice})],yg);var bg=class{value;constructor(e=`M`){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],bg.prototype,`value`,void 0),bg=X([q({type:G.Choice})],bg);var xg=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],xg.prototype,`value`,void 0),xg=X([q({type:G.Choice})],xg);var Sg=class extends xg{};Sg=X([q({type:G.Choice})],Sg);var Cg=class extends pu{};Cg=X([q({type:G.Choice})],Cg);var wg=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.ObjectIdentifier})],wg.prototype,`value`,void 0),wg=X([q({type:G.Choice})],wg);var Tg=class extends tf{};Tg=X([q({type:G.Choice})],Tg);var Eg=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};X([J({type:K.Integer})],Eg.prototype,`value`,void 0),Eg=X([q({type:G.Choice})],Eg);var Dg=class extends wf{};Dg=X([q({type:G.Sequence})],Dg);var Og=class extends pu{};Og=X([q({type:G.Choice})],Og);var kg=eg=class extends of{constructor(e){super(e),Object.setPrototypeOf(this,eg.prototype)}};kg=eg=X([q({type:G.Sequence})],kg);var Ag=tg=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,tg.prototype)}};Ag=tg=X([q({type:G.Set,itemType:Sf})],Ag);var jg=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.BmpString})],jg.prototype,`value`,void 0),jg=X([q({type:G.Choice})],jg);var Mg=class extends Z{};Mg=X([q({type:G.Sequence})],Mg);var Ng=ng=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,ng.prototype)}};Ng=ng=X([q({type:G.Sequence,itemType:Mg})],Ng);var Pg,Fg=Pg=class extends ou{constructor(e){super(e),Object.setPrototypeOf(this,Pg.prototype)}};Fg=Pg=X([q({type:G.Sequence,itemType:Ud})],Fg);var Ig=class{version=0;subject=new vu;subjectPKInfo=new ef;attributes=new Fg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Ig.prototype,`version`,void 0),X([J({type:vu})],Ig.prototype,`subject`,void 0),X([J({type:ef})],Ig.prototype,`subjectPKInfo`,void 0),X([J({type:Fg,implicit:!0,context:0,optional:!0})],Ig.prototype,`attributes`,void 0);var Lg=class{certificationRequestInfo=new Ig;certificationRequestInfoRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Ig,raw:!0})],Lg.prototype,`certificationRequestInfo`,void 0),X([J({type:Z})],Lg.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Lg.prototype,`signature`,void 0);var Rg=`crypto.algorithm`,zg=class{getAlgorithms(){return Th.resolveAll(Rg)}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}}},Bg=`crypto.algorithmProvider`;Th.registerSingleton(Bg,zg);var Vg,Hg=`1.3.36.3.3.2.8.1.1`,Ug=`${Hg}.1`,Wg=`${Hg}.2`,Gg=`${Hg}.3`,Kg=`${Hg}.4`,qg=`${Hg}.5`,Jg=`${Hg}.6`,Yg=`${Hg}.7`,Xg=`${Hg}.8`,Zg=`${Hg}.9`,Qg=`${Hg}.10`,$g=`${Hg}.11`,e_=`${Hg}.12`,t_=`${Hg}.13`,n_=`${Hg}.14`,r_=`brainpoolP160r1`,i_=`brainpoolP160t1`,a_=`brainpoolP192r1`,o_=`brainpoolP192t1`,s_=`brainpoolP224r1`,c_=`brainpoolP224t1`,l_=`brainpoolP256r1`,u_=`brainpoolP256t1`,d_=`brainpoolP320r1`,f_=`brainpoolP320t1`,p_=`brainpoolP384r1`,m_=`brainpoolP384t1`,h_=`brainpoolP512r1`,g_=`brainpoolP512t1`,__=`ECDSA`,v_=Vg=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case __.toLowerCase():if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return em;case`sha-256`:return tm;case`sha-384`:return nm;case`sha-512`:return rm}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=Xp;break;case`K-256`:t=Vg.SECP256K1;break;case`P-384`:t=Zp;break;case`P-521`:t=Qp;break;case r_:t=Ug;break;case i_:t=Wg;break;case a_:t=Gg;break;case o_:t=Kg;break;case s_:t=qg;break;case c_:t=Jg;break;case l_:t=Yg;break;case u_:t=Xg;break;case d_:t=Zg;break;case f_:t=Qg;break;case p_:t=$g;break;case m_:t=e_;break;case h_:t=t_;break;case g_:t=n_}if(t)return new Z({algorithm:Wp,parameters:Y.serialize(new lm({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Gp:return{name:__,hash:{name:`SHA-1`}};case qp:return{name:__,hash:{name:`SHA-256`}};case Jp:return{name:__,hash:{name:`SHA-384`}};case Yp:return{name:__,hash:{name:`SHA-512`}};case Wp:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(Y.parse(e.parameters,lm).namedCurve){case Xp:return{name:__,namedCurve:`P-256`};case Vg.SECP256K1:return{name:__,namedCurve:`K-256`};case Zp:return{name:__,namedCurve:`P-384`};case Qp:return{name:__,namedCurve:`P-521`};case Ug:return{name:__,namedCurve:r_};case Wg:return{name:__,namedCurve:i_};case Gg:return{name:__,namedCurve:a_};case Kg:return{name:__,namedCurve:o_};case qg:return{name:__,namedCurve:s_};case Jg:return{name:__,namedCurve:c_};case Yg:return{name:__,namedCurve:l_};case Xg:return{name:__,namedCurve:u_};case Zg:return{name:__,namedCurve:d_};case Qg:return{name:__,namedCurve:f_};case $g:return{name:__,namedCurve:p_};case e_:return{name:__,namedCurve:m_};case t_:return{name:__,namedCurve:h_};case n_:return{name:__,namedCurve:g_}}}return null}};v_.SECP256K1=`1.3.132.0.10`,v_=Vg=X([Eh()],v_),Th.registerSingleton(Rg,v_);var y_=Symbol(`name`),b_=Symbol(`value`),x_=class{constructor(e,t={},n=``){this[y_]=e,this[b_]=n;for(let e in t)this[e]=t[e]}};x_.NAME=y_,x_.VALUE=b_;var S_=class{static toTextObject(e){let t=new x_(`Algorithm Identifier`,{},C_.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Wp:{let n=new v_().toWebAlgorithm(e);n&&`namedCurve`in n?t[`Named Curve`]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},C_=class{static toString(e){return this.items[e]||e}};C_.items={[Em]:`sha1`,[Dm]:`sha224`,[Om]:`sha256`,[km]:`sha384`,[Am]:`sha512`,[pm]:`rsaEncryption`,[ym]:`sha1WithRSAEncryption`,[bm]:`sha224WithRSAEncryption`,[xm]:`sha256WithRSAEncryption`,[Sm]:`sha384WithRSAEncryption`,[Cm]:`sha512WithRSAEncryption`,[Wp]:`ecPublicKey`,[Gp]:`ecdsaWithSHA1`,[Kp]:`ecdsaWithSHA224`,[qp]:`ecdsaWithSHA256`,[Jp]:`ecdsaWithSHA384`,[Yp]:`ecdsaWithSHA512`,[vd]:`TLS WWW server authentication`,[yd]:`TLS WWW client authentication`,[bd]:`Code Signing`,[xd]:`E-mail Protection`,[Sd]:`Time Stamping`,[Cd]:`OCSP Signing`,[Bp]:`Signed Data`};var w_=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[x_.VALUE];a&&(i=` ${a}`),n.push(`${r}${e[x_.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[x_.NAME]=i,n.push(...this.serializeObj(e,t));else if(a instanceof x_)a[x_.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[x_.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)}};w_.oidSerializer=C_,w_.algorithmSerializer=S_;var T_,E_=class e{get rawData(){return su(this,T_,`f`)||cu(this,T_,Y.serialize(this.asn),`f`),su(this,T_,`f`)}constructor(...e){T_.set(this,void 0),U.isBufferSource(e[0])?(this.asn=Y.parse(e[0],e[1]),cu(this,T_,U.toArrayBuffer(e[0]),`f`),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(t){return t instanceof e&&Ta(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return Y.toString(this.rawData);case`text`:return w_.serialize(this.toTextObject());case`hex`:return Ca.ToHex(this.rawData);case`base64`:return Ca.ToBase64(this.rawData);case`base64url`:return Ca.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 x_(this.getTextName(),{},e)}};T_=new WeakMap,E_.NAME=`ASN`;var D_=class e extends E_{constructor(...e){let t;t=U.isBufferSource(e[0])?U.toArrayBuffer(e[0]):Y.serialize(new af({extnID:e[0],critical:e[1],extnValue:new Tl(U.toArrayBuffer(e[2]))})),super(t,af)}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[x_.NAME]===e.NAME&&(t[x_.NAME]=C_.toString(this.type)),t}},O_,k_=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[O_]=`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}};O_=Symbol.toStringTag,k_.DEFAULT=`default`;var A_=new k_,j_=/^[0-2](?:\.[1-9][0-9]*)+$/;function M_(e){return new RegExp(j_).test(e)}var N_=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 M_(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},P_=new N_;P_.register(`CN`,`2.5.4.3`),P_.register(`L`,`2.5.4.7`),P_.register(`ST`,`2.5.4.8`),P_.register(`O`,`2.5.4.10`),P_.register(`OU`,`2.5.4.11`),P_.register(`C`,`2.5.4.6`),P_.register(`DC`,`0.9.2342.19200300.100.1.25`),P_.register(`E`,`1.2.840.113549.1.9.1`),P_.register(`G`,`2.5.4.42`),P_.register(`I`,`2.5.4.43`),P_.register(`SN`,`2.5.4.4`),P_.register(`T`,`2.5.4.12`);function F_(e,t){return`\\${Ca.ToHex(Ca.FromUtf8String(t)).toUpperCase()}`}function I_(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,F_)}var L_=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 N_,this.asn=new vu;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 vu?e:U.isBufferSource(e)?Y.parse(e,vu):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||P_.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)||P_.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Ca.ToHex(e.value.anyValue)}`:I_(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?`#${Ca.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new vu,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 gu([s])),i=o}return t}fromJSON(e){let t=new vu;for(let n of e){let e=new gu;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 hu({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=Ca.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]||A_.get()):t=e[0]||A_.get(),await t.subtle.digest(n,this.toArrayBuffer())}},R_=`Cannot initialize GeneralName from ASN.1 data.`,z_=`${R_} Unsupported string format in use.`,B_=`${R_} Value doesn't match to GUID regular expression.`,V_=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,H_=`1.3.6.1.4.1.311.25.1`,U_=`1.3.6.1.4.1.311.20.2.3`,W_=`email`,G_=`guid`,K_=class extends E_{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let n=new L_(e[1]).toArrayBuffer(),r=Y.parse(n,vu);t=new Su({directoryName:r});break}case`dns`:t=new Su({dNSName:e[1]});break;case W_:t=new Su({rfc822Name:e[1]});break;case G_:{let n=new RegExp(V_,`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?Ca.ToHex(new Uint8Array(Ca.FromHex(e)).reverse()):e).join(``);t=new Su({otherName:new bu({typeId:H_,value:Y.serialize(new Tl(Ca.FromHex(r)))})});break}case`ip`:t=new Su({iPAddress:e[1]});break;case`id`:t=new Su({registeredID:e[1]});break;case`upn`:t=new Su({otherName:new bu({typeId:U_,value:Y.serialize(Ll.toASN(e[1]))})});break;case`url`:t=new Su({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],Su):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=W_,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 L_(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===H_){this.type=G_;let t=Y.parse(e.otherName.value,Tl),n=new RegExp(V_,`i`).exec(Ca.ToHex(t));if(!n)throw Error(B_);this.value=n.slice(1).map((e,t)=>t<3?Ca.ToHex(new Uint8Array(Ca.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===U_)this.type=`upn`,this.value=Y.parse(e.otherName.value,pu).toString();else throw Error(z_)}else throw Error(z_)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case G_:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case W_:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=C_.toString(t)),new x_(e,void 0,t)}},q_=class extends E_{constructor(e){let t;if(e instanceof Uu)t=e;else if(Array.isArray(e)){let n=[];for(let t of e)if(t instanceof Su)n.push(t);else{let e=Y.parse(new K_(t.type,t.value).rawData,Su);n.push(e)}t=new Uu(n)}else if(U.isBufferSource(e))t=Y.parse(e,Uu);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 K_(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[x_.NAME]];Array.isArray(r)||(r=[],e[n[x_.NAME]]=r),r.push(n)}return e}};q_.NAME=`GeneralNames`;var J_=`-{5}`,Y_=`\\n`,X_=`${J_}BEGIN (${`[^${Y_}]+`}(?=${J_}))${J_}`,Z_=`${J_}END \\1${J_}`,Q_=`\\n`,$_=`${X_}${Q_}(?:((?:${`[^:${Y_}]+`}: ${`(?:[^${Y_}]+${Q_}(?: +[^${Y_}]+${Q_})*)`})+))?${Q_}?(${`(?:[a-zA-Z0-9=+/]+${Q_})+`})${Z_}`,ev=class{static isPem(e){return typeof e==`string`&&new RegExp($_,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp($_,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[${Y_}]+`,`g`),``),t={type:r[1],headers:[],rawData:Ca.FromBase64(e)},i=r[2];if(i){let e=i.split(new RegExp(Q_,`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=Ca.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
|
+
`)}};ev.CertificateTag=`CERTIFICATE`,ev.CrlTag=`CRL`,ev.CertificateRequestTag=`CERTIFICATE REQUEST`,ev.PublicKeyTag=`PUBLIC KEY`,ev.PrivateKeyTag=`PRIVATE KEY`;var tv=class e extends E_{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(ev.isPem(e))return ev.decode(e)[0];if(Ca.isHex(e))return Ca.FromHex(e);if(Ca.isBase64(e))return Ca.FromBase64(e);if(Ca.isBase64Url(e))return Ca.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=Ca.ToBinary(e);if(ev.isPem(n))return ev.decode(n)[0];if(Ca.isHex(n))return Ca.FromHex(n);if(Ca.isBase64(n))return Ca.FromBase64(n);if(Ca.isBase64Url(n))return Ca.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 ev.encode(this.rawData,this.tag);default:return super.toString(e)}}},nv=class e extends tv{static async create(t,n=A_.get()){if(t instanceof e)return t;if(k_.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){tv.isAsnEncoded(e)?super(e,ef):super(e),this.tag=ev.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]||A_.get()):t=e[0]||A_.get();let i=this.rawData,a=Y.parse(this.rawData,ef);return a.algorithm.algorithm===gm&&(i=rv(a,i)),t.subtle.importKey(`spki`,i,r,!0,n)}onInit(e){let t=Th.resolve(Bg),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case pm:{let t=Y.parse(e.subjectPublicKey,qm),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]||A_.get()):t=e[0]||A_.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=A_.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=A_.get();let r=Y.parse(this.rawData,ef);return await t.subtle.digest(n,r.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,ef);switch(e.Algorithm=w_.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Wp:e[`EC Point`]=t.subjectPublicKey;break;case pm:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function rv(e,t){return e.algorithm=new Z({algorithm:pm,parameters:null}),t=Y.serialize(e),t}var iv=class e extends D_{static async create(t,n=!1,r=A_.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let i=await(await nv.create(t,r)).getKeyIdentifier(r);return new e(Ca.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new zu({keyIdentifier:new Ru(Ca.FromHex(e[0]))});super(Lu,e[1],Y.serialize(t))}else{let t=e[0],n=new zu({authorityCertIssuer:t.name instanceof q_?Y.parse(t.name.rawData,Uu):t.name,authorityCertSerialNumber:Ca.FromHex(t.serialNumber)});super(Lu,e[1],Y.serialize(n))}}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,zu);t.keyIdentifier&&(this.keyId=Ca.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Ca.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=Y.parse(this.value,zu);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new q_(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};iv.NAME=`Authority Key Identifier`;var av=class extends D_{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Vu);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new Vu({cA:e[0],pathLenConstraint:e[1]});super(Bu,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}};av.NAME=`Basic Constraints`;var ov;(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`})(ov||={});var sv=class extends D_{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,_d);this.usages=t.map(e=>e)}else{let t=new _d(e[0]);super(gd,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>C_.toString(e)).join(`, `),e}};sv.NAME=`Extended Key Usages`;var cv;(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`})(cv||={});var lv=class extends D_{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,jd);this.usages=t.toNumber()}else{let t=new jd(e[0]);super(kd,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,jd).toJSON().join(`, `),e}};lv.NAME=`Key Usages`;var uv=class e extends D_{static async create(t,n=!1,r=A_.get()){let i=await(await nv.create(t,r)).getKeyIdentifier(r);return new e(Ca.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,qd);this.keyId=Ca.ToHex(t)}else{let t=typeof e[0]==`string`?Ca.FromHex(e[0]):e[0],n=new qd(t);super(Kd,e[1],Y.serialize(n)),this.keyId=Ca.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,qd),e}};uv.NAME=`Subject Key Identifier`;var dv=class extends D_{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(Vd,e[1],new q_(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Hd);this.names=new q_(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};dv.NAME=`Subject Alternative Name`;var fv=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new D_(e),n=this.items.get(t.type);return n?new n(e):t}};fv.items=new Map;var pv=class extends D_{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,ed);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],n=e[1]??!1,r=new ed(t.map(e=>new $u({policyIdentifier:e})));super(qu,n,Y.serialize(r)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new x_(``,{},C_.toString(e))),e}};pv.NAME=`Certificate Policies`,fv.register(qu,pv);var mv=class extends D_{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 cd({distributionPoint:new sd({fullName:[new Su({uniformResourceIdentifier:e})]})})),n=new ld(t);super(id,e[1],Y.serialize(n))}else{let t=new ld(e[0]);super(id,e[1],Y.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,ld);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 K_(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};mv.NAME=`CRL Distribution Points`;var hv=class extends D_{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Iu){let t=new Iu(e[0]);super(Pu,e[1],Y.serialize(t))}else{let t=e[0],n=new Iu;_v(n,t,Ou,`ocsp`),_v(n,t,ku,`caIssuers`),_v(n,t,Au,`timeStamping`),_v(n,t,ju,`caRepository`),super(Pu,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,Iu).forEach(e=>{switch(e.accessMethod){case Ou:this.ocsp.push(new K_(e.accessLocation));break;case ku:this.caIssuers.push(new K_(e.accessLocation));break;case Au:this.timeStamping.push(new K_(e.accessLocation));break;case ju:this.caRepository.push(new K_(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&gv(e,`OCSP`,this.ocsp),this.caIssuers.length&&gv(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&gv(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&gv(e,`CA Repository`,this.caRepository),e}};hv.NAME=`Authority Info Access`;function gv(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new x_(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[x_.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function _v(e,t,n,r){let i=t[r];i&&(Array.isArray(i)?i:[i]).forEach(t=>{typeof t==`string`&&(t=new K_(`url`,t)),e.push(new Fu({accessMethod:n,accessLocation:Y.parse(t.rawData,Su)}))})}var vv=class extends D_{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(Dd,e[1],new q_(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Uu);this.names=new q_(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};vv.NAME=`Issuer Alternative Name`;var yv=class e extends E_{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 Ud({type:n,values:r}))}super(t,Ud)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new x_(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[x_.NAME]===e.NAME&&(t[x_.NAME]=C_.toString(this.type)),t}};yv.NAME=`Attribute`;var bv=class extends yv{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=new Og({printableString:e[0]});super(cg,[Y.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],Og);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[x_.VALUE]=this.password,e}};bv.NAME=`Challenge Password`;var xv=class extends yv{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=e[0],n=new of;for(let e of t)n.push(Y.parse(e.rawData,af));super(lg,[Y.serialize(n)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],of);this.items=e.map(e=>fv.create(Y.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[x_.NAME]]=n;return e}};xv.NAME=`Extensions`;var Sv=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new yv(e),n=this.items.get(t.type);return n?new n(e):t}};Sv.items=new Map;var Cv=`crypto.signatureFormatter`,wv=class{toAsnSignature(e,t){return U.toArrayBuffer(t)}toWebSignature(e,t){return U.toArrayBuffer(t)}},Tv,Ev=Tv=class{static createPssParams(e,t){let n=Tv.getHashAlgorithm(e);return n?new Vm({hashAlgorithm:n,maskGenAlgorithm:new Z({algorithm:Fm,parameters:Y.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=Th.resolve(Bg);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:ym,parameters:null});case`sha-256`:return new Z({algorithm:xm,parameters:null});case`sha-384`:return new Z({algorithm:Sm,parameters:null});case`sha-512`:return new Z({algorithm:Cm,parameters:null})}}else return new Z({algorithm:pm,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=Tv.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new Z({algorithm:gm,parameters:Y.serialize(t)})}return new Z({algorithm:gm,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case pm:return{name:`RSASSA-PKCS1-v1_5`};case ym:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case xm:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case Sm:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case Cm:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case gm:if(e.parameters){let t=Y.parse(e.parameters,Vm);return{name:`RSA-PSS`,hash:Th.resolve(Bg).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}};Ev=Tv=X([Eh()],Ev),Th.registerSingleton(Rg,Ev);var Dv=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new Z({algorithm:Em});case`sha-256`:return new Z({algorithm:Om});case`sha-384`:return new Z({algorithm:km});case`sha-512`:return new Z({algorithm:Am})}return null}toWebAlgorithm(e){switch(e.algorithm){case Em:return{name:`SHA-1`};case Om:return{name:`SHA-256`};case km:return{name:`SHA-384`};case Am:return{name:`SHA-512`}}return null}};Dv=X([Eh()],Dv),Th.registerSingleton(Rg,Dv);var Ov=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 dm,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,dm),i=t.namedCurve,a=e.namedCurveSize.get(i)||e.defaultNamedCurveSize;return wa(this.addPadding(a,this.removePadding(r.r)),this.addPadding(a,this.removePadding(r.s)))}return null}};Ov.namedCurveSize=new Map,Ov.defaultNamedCurveSize=32;var kv=`1.3.101.110`,Av=`1.3.101.111`,jv=`1.3.101.112`,Mv=`1.3.101.113`,Nv=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=jv;break;case`x25519`:t=kv;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=jv;break;case`ed448`:t=Mv}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=kv;break;case`x448`:t=Av}}return t?new Z({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case jv:return{name:`Ed25519`};case Mv:return{name:`EdDSA`,namedCurve:`Ed448`};case kv:return{name:`X25519`};case Av:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};Nv=X([Eh()],Nv),Th.registerSingleton(Rg,Nv);var Pv,Fv,Iv,Lv,Rv,zv,Bv,Vv,Hv=class extends tv{get subjectName(){return su(this,Fv,`f`)||cu(this,Fv,new L_(this.asn.certificationRequestInfo.subject),`f`),su(this,Fv,`f`)}get subject(){return su(this,Iv,`f`)||cu(this,Iv,this.subjectName.toString(),`f`),su(this,Iv,`f`)}get signatureAlgorithm(){if(!su(this,Lv,`f`)){let e=Th.resolve(Bg);cu(this,Lv,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return su(this,Lv,`f`)}get signature(){return su(this,Rv,`f`)||cu(this,Rv,this.asn.signature,`f`),su(this,Rv,`f`)}get publicKey(){return su(this,zv,`f`)||cu(this,zv,new nv(this.asn.certificationRequestInfo.subjectPKInfo),`f`),su(this,zv,`f`)}get attributes(){return su(this,Bv,`f`)||cu(this,Bv,this.asn.certificationRequestInfo.attributes.map(e=>Sv.create(Y.serialize(e))),`f`),su(this,Bv,`f`)}get extensions(){if(!su(this,Vv,`f`)){cu(this,Vv,[],`f`);let e=this.getAttribute(lg);e instanceof xv&&cu(this,Vv,e.items,`f`)}return su(this,Vv,`f`)}get tbs(){return su(this,Pv,`f`)||cu(this,Pv,this.asn.certificationRequestInfoRaw||Y.serialize(this.asn.certificationRequestInfo),`f`),su(this,Pv,`f`)}constructor(e){let t=tv.isAsnEncoded(e)?[e,Lg]:[e];super(t[0],t[1]),Pv.set(this,void 0),Fv.set(this,void 0),Iv.set(this,void 0),Lv.set(this,void 0),Rv.set(this,void 0),zv.set(this,void 0),Bv.set(this,void 0),Vv.set(this,void 0),this.tag=ev.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=A_.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=Th.resolveAll(Cv).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,Lg),n=t.certificationRequestInfo,r=new x_(``,{Version:`${sf[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new x_(``);for(let t of this.attributes){let n=t.toTextObject();e[n[x_.NAME]]=n}r.Attributes=e}return e.Data=r,e.Signature=new x_(``,{Algorithm:w_.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};Pv=new WeakMap,Fv=new WeakMap,Iv=new WeakMap,Lv=new WeakMap,Rv=new WeakMap,zv=new WeakMap,Bv=new WeakMap,Vv=new WeakMap,Hv.NAME=`PKCS#10 Certificate Request`;var Uv,Wv,Gv,Kv,qv,Jv,Yv,Xv,Zv,Qv,$v,ey,ty=class extends tv{get publicKey(){return su(this,ey,`f`)||cu(this,ey,new nv(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`),su(this,ey,`f`)}get serialNumber(){if(!su(this,Wv,`f`)){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),cu(this,Wv,Ca.ToHex(t),`f`)}return su(this,Wv,`f`)}get subjectName(){return su(this,Gv,`f`)||cu(this,Gv,new L_(this.asn.tbsCertificate.subject),`f`),su(this,Gv,`f`)}get subject(){return su(this,Kv,`f`)||cu(this,Kv,this.subjectName.toString(),`f`),su(this,Kv,`f`)}get issuerName(){return su(this,qv,`f`)||cu(this,qv,new L_(this.asn.tbsCertificate.issuer),`f`),su(this,qv,`f`)}get issuer(){return su(this,Jv,`f`)||cu(this,Jv,this.issuerName.toString(),`f`),su(this,Jv,`f`)}get notBefore(){if(!su(this,Yv,`f`)){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error(`Cannot get 'notBefore' value`);cu(this,Yv,e,`f`)}return su(this,Yv,`f`)}get notAfter(){if(!su(this,Xv,`f`)){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error(`Cannot get 'notAfter' value`);cu(this,Xv,e,`f`)}return su(this,Xv,`f`)}get signatureAlgorithm(){if(!su(this,Zv,`f`)){let e=Th.resolve(Bg);cu(this,Zv,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return su(this,Zv,`f`)}get signature(){return su(this,Qv,`f`)||cu(this,Qv,this.asn.signatureValue,`f`),su(this,Qv,`f`)}get extensions(){return su(this,$v,`f`)||(cu(this,$v,[],`f`),this.asn.tbsCertificate.extensions&&cu(this,$v,this.asn.tbsCertificate.extensions.map(e=>fv.create(Y.serialize(e))),`f`)),su(this,$v,`f`)}get tbs(){return su(this,Uv,`f`)||cu(this,Uv,this.asn.tbsCertificateRaw||Y.serialize(this.asn.tbsCertificate),`f`),su(this,Uv,`f`)}constructor(e){let t=tv.isAsnEncoded(e)?[e,lf]:[e];super(t[0],t[1]),Uv.set(this,void 0),Wv.set(this,void 0),Gv.set(this,void 0),Kv.set(this,void 0),qv.set(this,void 0),Jv.set(this,void 0),Yv.set(this,void 0),Xv.set(this,void 0),Zv.set(this,void 0),Qv.set(this,void 0),$v.set(this,void 0),ey.set(this,void 0),this.tag=ev.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=A_.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 nv)n={...i.algorithm,...this.signatureAlgorithm},r=await i.export(n,[`verify`],t);else if(U.isBufferSource(i)){let e=new nv(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=Th.resolveAll(Cv).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??=A_.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=A_.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,lf),n=t.tbsCertificate,r=new x_(``,{Version:`${sf[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":w_.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new x_(``,{"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 x_(``);for(let t of this.extensions){let n=t.toTextObject();e[n[x_.NAME]]=n}r.Extensions=e}return e.Data=r,e.Signature=new x_(``,{Algorithm:w_.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};Uv=new WeakMap,Wv=new WeakMap,Gv=new WeakMap,Kv=new WeakMap,qv=new WeakMap,Jv=new WeakMap,Yv=new WeakMap,Xv=new WeakMap,Zv=new WeakMap,Qv=new WeakMap,$v=new WeakMap,ey=new WeakMap,ty.NAME=`Certificate`;function ny(e,t=A_.get()){let n=U.toUint8Array(Ca.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 ry=class{static async createSelfSigned(e,t=A_.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=A_.get()){let n;n=e.publicKey instanceof nv?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=ny(e.serialNumber,t),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),o=new lf({tbsCertificate:new cf({version:sf.v3,serialNumber:r,validity:new nf({notBefore:i,notAfter:a}),extensions:new of(e.extensions?.map(e=>Y.parse(e.rawData,af))||[]),subjectPublicKeyInfo:Y.parse(n,ef)})});if(e.subject){let t=e.subject instanceof L_?e.subject:new L_(e.subject);o.tbsCertificate.subject=Y.parse(t.toArrayBuffer(),vu)}if(e.issuer){let t=e.issuer instanceof L_?e.issuer:new L_(e.issuer);o.tbsCertificate.issuer=Y.parse(t.toArrayBuffer(),vu)}let s={hash:`SHA-256`},c=`signingKey`in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},l=Th.resolve(Bg);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=Th.resolveAll(Cv).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 ty(Y.serialize(o))}},iy;(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`})(iy||={}),fv.register(Bu,av),fv.register(gd,sv),fv.register(kd,lv),fv.register(Kd,uv),fv.register(Lu,iv),fv.register(Vd,dv),fv.register(id,mv),fv.register(Pu,hv),fv.register(Dd,vv),Sv.register(cg,bv),Sv.register(lg,xv),Th.registerSingleton(Cv,wv),Th.registerSingleton(Cv,Ov),Ov.namedCurveSize.set(`P-256`,32),Ov.namedCurveSize.set(`K-256`,32),Ov.namedCurveSize.set(`P-384`,48),Ov.namedCurveSize.set(`P-521`,66);var ay=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})),oy=R(((e,t)=>{for(var n=te(`util`),r=ay(),i=/[\{\[]/,a=/[\}\]]/,o=`do.if.in.for.let.new.try.var.case.else.enum.eval.null.this.true.void.with.await.break.catch.class.const.false.super.throw.while.yield.delete.export.import.public.return.static.switch.typeof.default.extends.finally.package.private.continue.debugger.function.arguments.interface.protected.implements.instanceof.NaN.undefined`.split(`.`),s={},c=0;c<o.length;c++)s[o[c]]=!0;var l=function(e){return r(e)&&!s.hasOwnProperty(e)},u={s:function(e){return``+e},d:function(e){return``+Number(e)},o:function(e){return JSON.stringify(e)}},d=function(){var e=[],t=0,o={},s=function(n){for(var r=``;r.length<t*2;)r+=` `;e.push(r+n)},c=function(e){if(a.test(e.trim()[0])&&i.test(e[e.length-1])){t--,s(e),t++;return}if(i.test(e[e.length-1])){s(e),t++;return}if(a.test(e.trim()[0])){t--,s(e);return}s(e)},d=function(e){if(!e)return d;if(arguments.length===1&&e.indexOf(`
|
|
43
43
|
`)>-1)for(var t=e.trim().split(`
|
|
44
44
|
`),r=0;r<t.length;r++)c(t[r].trim());else c(n.format.apply(n,arguments));return d};return d.scope={},d.formats=u,d.sym=function(e){return(!e||!l(e))&&(e=`tmp`),o[e]||(o[e]=0),e+(o[e]++||``)},d.property=function(e,t){return arguments.length===1&&(t=e,e=``),t+=``,r(t)?e?e+`.`+t:t:e?e+`[`+JSON.stringify(t)+`]`:JSON.stringify(t)},d.toString=function(){return e.join(`
|
|
45
|
-
`)},d.toFunction=function(e){e||={};var t=`return (`+d.toString()+`)`;Object.keys(d.scope).forEach(function(t){e[t]||(e[t]=d.scope[t])});var n=Object.keys(e).map(function(e){return e}),r=n.map(function(t){return e[t]});return Function.apply(null,n.concat(t)).apply(null,r)},arguments.length&&d.apply(null,arguments),d};d.formats=u,t.exports=d})),
|
|
45
|
+
`)},d.toFunction=function(e){e||={};var t=`return (`+d.toString()+`)`;Object.keys(d.scope).forEach(function(t){e[t]||(e[t]=d.scope[t])});var n=Object.keys(e).map(function(e){return e}),r=n.map(function(t){return e[t]});return Function.apply(null,n.concat(t)).apply(null,r)},arguments.length&&d.apply(null,arguments),d};d.formats=u,t.exports=d})),sy=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}}})),cy=R(((e,t)=>{var n=oy(),r=sy(),i=class e{constructor(){this.queue=new r,this.offset=0}get length(){return this.queue.length-this.offset}append(t){if(Buffer.isBuffer(t)){if(this.offset>0){let e=this.queue.shift();this.queue.unshift(e.slice(this.offset)),this.offset=0}this.queue.push(t)}else if(Array.isArray(t))for(let e=0;e<t.length;e+=1)this.append(t[e]);else if(t instanceof e){if(this.offset>0){let e=this.queue.shift();this.queue.unshift(e.slice(this.offset)),this.offset=0}if(t.offset>0){let e=t.queue.shift();t.queue.unshift(e.slice(t.offset)),t.offset=0}let e=t.queue.head;for(;e;)this.queue.push(e.buffer),e=e.next}}get(e){let t=e;for(;t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let n=this.queue.head,{offset:r}=this;for(;n;){if(n.buffer.length-r>t)return n.buffer[t+r];t-=n.buffer.length-r,r=0,n=n.next}}slice(e,t){for(typeof e!=`number`&&(e=0),typeof t!=`number`&&(t=this.length);e<0;)e+=this.length;for(;t<0;)t+=this.length;if(t=Math.min(t,this.length),e>=this.length||t===0)return Buffer.alloc(0);let n=e;e=Math.min(n,t),t=Math.max(n,t);let r=this.queue.slice(e+this.offset,t+this.offset);if(r.count===1)return r.first;let i=r.head,a=Buffer.allocUnsafe(r.length),o=0;for(let e=0;e<r.count;e+=1)a.set(i.buffer,o),o+=i.buffer.length,i=i.next;return a}toString(e,t,n){return this.slice(t,n).toString(e)}consume(e){let t=e;for(;this.length>0;){let e=this.queue.first.length-this.offset;if(t>=e)this.queue.shift(),t-=e,this.offset=0;else{this.offset+=t;break}}}indexOf(e,t=0){if(!Number.isInteger(e))throw TypeError(`Invalid argument 1`);if(e<0||e>255)throw Error(`Invalid argument 1`);for(Number.isInteger(t)||(t=0);t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let n=this.queue.head,r=0,i=()=>{r+=n.buffer.length,n=n.next};for(;n;){let a=0;if(n===this.queue.head&&(a+=this.offset),t>=n.buffer.length-a){t-=n.buffer.length-a,i();continue}t<n.buffer.length&&(a+=t);let o=n.buffer.indexOf(e,a);if(o>-1)return o+r-this.offset;i(),a>this.offset&&(t=0)}return-1}},a={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(a).forEach(e=>{let t=n();t(`
|
|
46
46
|
function bufferlist_${e}(offset = 0) {
|
|
47
47
|
const start = offset + this.offset;
|
|
48
48
|
const head = this.queue.first;
|
|
@@ -76,7 +76,7 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
76
76
|
buf.${e}(value, 0, size);
|
|
77
77
|
this.append(buf);
|
|
78
78
|
}
|
|
79
|
-
`),i.prototype[e]=t.toFunction()}),t.exports=i})),
|
|
79
|
+
`),i.prototype[e]=t.toFunction()}),t.exports=i})),ly=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`}}})),uy=R(((e,t)=>{var{Transform:n}=te(`stream`),r=oy(),i=cy(),a=ly(),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})),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(`
|
|
105
|
+
`),s.prototype[e]=t.toFunction()});function l(e,t){if(e>t)throw new a(e,t)}t.exports=s})),dy=R(((e,t)=>{t.exports=function(e){return typeof e==`object`&&!!e&&Array.isArray(e)===!1}})),fy=R(((e,t)=>{var n=dy();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)}})),py=R(((e,t)=>{t.exports={isType:n,isUserType:fy(),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)}})),my=R(((e,t)=>{t.exports={skip:Symbol(`skip`),bytes:Symbol(`bytes`)}})),hy=R(((e,t)=>{var n=my();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)}}})),gy=R(((e,t)=>{var{isType:n,isUserType:r,isDecodeType:i}=py(),a=uy(),o=my(),s=hy();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.`)}})),_y=R(((e,t)=>{var{isUserType:n,isEncodeType:r,isType:i}=py(),a=my(),o=hy(),s=uy();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.")}})),vy=R(((e,t)=>{var{isUserType:n,isType:r}=py(),i=hy(),a=my();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)}}})),yy=R(((e,t)=>{var{decodeCommon:n}=gy(),{encodeCommon:r}=_y(),{encodingLengthCommon:i}=vy(),{isType:a,isUserType:o,isFunction:s}=py(),c=hy();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}})),by=R(((e,t)=>{var{isType:n,isFunction:r}=py(),i=ly(),a=uy();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.`)}})),xy=R(((e,t)=>{var{isType:n}=py();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}}})),Sy=R(((e,t)=>{var{decodeCommon:n}=gy(),{encodeCommon:r}=_y(),{encodingLengthCommon:i}=vy(),{isType:a,isFunction:o}=py(),s=my(),c=hy();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)}}})),Cy=R(((e,t)=>{var{isType:n}=py(),r=ly();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}`)}})),wy=R(((e,t)=>{var n=oy();t.exports={doublebe:r(8,`writeDoubleBE`,`readDoubleBE`),doublele:r(8,`writeDoubleLE`,`readDoubleLE`),floatbe:r(4,`writeFloatBE`,`readFloatBE`),floatle:r(4,`writeFloatLE`,`readFloatLE`),int8:r(1,`writeInt8`,`readInt8`),uint8:r(1,`writeUInt8`,`readUInt8`),int16be:r(2,`writeInt16BE`,`readInt16BE`),uint16be:r(2,`writeUInt16BE`,`readUInt16BE`),int16le:r(2,`writeInt16LE`,`readInt16LE`),uint16le:r(2,`writeUInt16LE`,`readUInt16LE`),int32be:r(4,`writeInt32BE`,`readInt32BE`),uint32be:r(4,`writeUInt32BE`,`readUInt32BE`),int32le:r(4,`writeInt32LE`,`readInt32LE`),uint32le:r(4,`writeUInt32LE`,`readUInt32LE`),int24be:i(3,`writeIntBE`,`readIntBE`),uint24be:i(3,`writeUIntBE`,`readUIntBE`),int24le:i(3,`writeIntLE`,`readIntLE`),uint24le:i(3,`writeUIntLE`,`readUIntLE`),int40be:i(5,`writeIntBE`,`readIntBE`),uint40be:i(5,`writeUIntBE`,`readUIntBE`),int40le:i(5,`writeIntLE`,`readIntLE`),uint40le:i(5,`writeUIntLE`,`readUIntLE`),int48be:i(6,`writeIntBE`,`readIntBE`),uint48be:i(6,`writeUIntBE`,`readUIntBE`),int48le:i(6,`writeIntLE`,`readIntLE`),uint48le:i(6,`writeUIntLE`,`readUIntLE`)};function r(e,t,r){let i=n(),a=n();return i(`
|
|
106
106
|
function decode_${r}(rstream) {
|
|
107
107
|
decode_${r}.bytes = ${i.formats.d(e)};
|
|
108
108
|
return rstream.${r}()
|
|
@@ -122,7 +122,7 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
122
122
|
wstream.${t}(value, ${i.formats.d(e)});
|
|
123
123
|
encode_${t}.bytes = ${i.formats.d(e)};
|
|
124
124
|
}
|
|
125
|
-
`),{encodingLength:()=>e,encode:a.toFunction(),decode:i.toFunction()}}})),
|
|
125
|
+
`),{encodingLength:()=>e,encode:a.toFunction(),decode:i.toFunction()}}})),Ty=R(((e,t)=>{var{isType:n,isFunction:r,isUserType:i}=py(),a=my(),{decodeCommon:o}=gy(),{encodeCommon:s}=_y(),{encodingLengthCommon:c}=vy(),l=hy();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}}})),Ey=R(((e,t)=>{var n=my(),{decodeCommon:r}=gy(),i=hy();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}}})),Dy=R(((e,t)=>{var n=oy(),r=ly(),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)}})),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
|
|
139
|
+
`),i.prototype[e]=t.toFunction({assertSize:o})}),t.exports=i;function o(e,t){if(e>t)throw new r(e,t)}})),Oy=R(((e,t)=>{var n=uy(),r=yy(),i=by(),a=xy(),o=Sy(),s=Cy(),c=wy(),l=Ty(),u=Ey(),{encode:d}=_y(),{decode:f}=gy(),{encodingLength:p}=vy(),m=Dy(),h=ly(),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}})),ky=V(aa(),1),Q=Oy(),Ay=T&&typeof T==`object`&&`webcrypto`in T?T.webcrypto:T&&typeof T==`object`&&`randomBytes`in T?T:void 0;function jy(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function My(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function Ny(e,...t){if(!jy(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 Py(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);My(e.outputLen),My(e.blockLen)}function Fy(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 Iy(e,t){Ny(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function Ly(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ry(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function zy(e,t){return e<<32-t|e>>>t}var By=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Vy=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Hy(e){if(Ny(e),By)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Vy[e[n]];return t}var Uy={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wy(e){if(e>=Uy._0&&e<=Uy._9)return e-Uy._0;if(e>=Uy.A&&e<=Uy.F)return e-(Uy.A-10);if(e>=Uy.a&&e<=Uy.f)return e-(Uy.a-10)}function Gy(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(By)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=Wy(e.charCodeAt(i)),a=Wy(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 Ky(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function qy(e){return typeof e==`string`&&(e=Ky(e)),Ny(e),e}function Jy(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];Ny(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 Yy=class{};function Xy(e){let t=t=>e().update(qy(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Zy(e=32){if(Ay&&typeof Ay.getRandomValues==`function`)return Ay.getRandomValues(new Uint8Array(e));if(Ay&&typeof Ay.randomBytes==`function`)return Uint8Array.from(Ay.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}var Qy=BigInt(0),$y=BigInt(1);function eb(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function tb(e,t,n=``){let r=jy(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 nb(e){let t=e.toString(16);return t.length&1?`0`+t:t}function rb(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?Qy:BigInt(`0x`+e)}function ib(e){return rb(Hy(e))}function ab(e){return Ny(e),rb(Hy(Uint8Array.from(e).reverse()))}function ob(e,t){return Gy(e.toString(16).padStart(t*2,`0`))}function sb(e,t){return ob(e,t).reverse()}function cb(e,t,n){let r;if(typeof t==`string`)try{r=Gy(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(jy(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 lb=e=>typeof e==`bigint`&&Qy<=e;function ub(e,t,n){return lb(e)&&lb(t)&&lb(n)&&t<=e&&e<n}function db(e,t,n,r){if(!ub(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function fb(e){let t=0;for(;e>Qy;e>>=$y,t+=1);return t}var pb=e=>($y<<BigInt(e))-$y;function mb(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 Jy(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function hb(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 gb(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 _b=BigInt(0),vb=BigInt(1),yb=BigInt(2),bb=BigInt(3),xb=BigInt(4),Sb=BigInt(5),Cb=BigInt(7),wb=BigInt(8),Tb=BigInt(9),Eb=BigInt(16);function Db(e,t){let n=e%t;return n>=_b?n:t+n}function Ob(e,t){if(e===_b)throw Error(`invert: expected non-zero number`);if(t<=_b)throw Error(`invert: expected positive modulus, got `+t);let n=Db(e,t),r=t,i=_b,a=vb,o=vb,s=_b;for(;n!==_b;){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!==vb)throw Error(`invert: does not exist`);return Db(i,t)}function kb(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Ab(e,t){let n=(e.ORDER+vb)/xb,r=e.pow(t,n);return kb(e,r,t),r}function jb(e,t){let n=(e.ORDER-Sb)/wb,r=e.mul(t,yb),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,yb),i),s=e.mul(a,e.sub(o,e.ONE));return kb(e,s,t),s}function Mb(e){let t=Vb(e),n=Nb(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Cb)/Eb;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 kb(e,p,t),p}}function Nb(e){if(e<bb)throw Error(`sqrt is not defined for small field`);let t=e-vb,n=0;for(;t%yb===_b;)t/=yb,n++;let r=yb,i=Vb(e);for(;zb(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Ab;let a=i.pow(r,t),o=(t+vb)/yb;return function(e,r){if(e.is0(r))return r;if(zb(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=vb<<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 Pb(e){return e%xb===bb?Ab:e%wb===Sb?jb:e%Eb===Tb?Mb(e):Nb(e)}var Fb=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Ib(e){return hb(e,Fb.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Lb(e,t,n){if(n<_b)throw Error(`invalid exponent, negatives unsupported`);if(n===_b)return e.ONE;if(n===vb)return t;let r=e.ONE,i=t;for(;n>_b;)n&vb&&(r=e.mul(r,i)),i=e.sqr(i),n>>=vb;return r}function Rb(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 zb(e,t){let n=(e.ORDER-vb)/yb,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 Bb(e,t){t!==void 0&&My(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Vb(e,t,n=!1,r={}){if(e<=_b)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}=Bb(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:pb(c),ZERO:_b,ONE:vb,allowedLengths:s,create:t=>Db(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return _b<=t&&t<e},is0:e=>e===_b,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&vb)===vb,neg:t=>Db(-t,e),eql:(e,t)=>e===t,sqr:t=>Db(t*t,e),add:(t,n)=>Db(t+n,e),sub:(t,n)=>Db(t-n,e),mul:(t,n)=>Db(t*n,e),pow:(e,t)=>Lb(d,e,t),div:(t,n)=>Db(t*Ob(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ob(t,e),sqrt:a||(t=>(u||=Pb(e),u(d,t))),toBytes:e=>n?sb(e,l):ob(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?ab(t):ib(t);if(o&&(i=Db(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>Rb(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Hb(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function Ub(e){let t=Hb(e);return t+Math.ceil(t/2)}function Wb(e,t,n=!1){let r=e.length,i=Hb(t),a=Ub(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=Db(n?ab(e):ib(e),t-vb)+vb;return n?sb(o,i):ob(o,i)}function Gb(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 Kb(e,t,n){return e&t^~e&n}function qb(e,t,n){return e&t^e&n^t&n}var Jb=class extends Yy{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=Ry(this.buffer)}update(e){Fy(this),e=qy(e),Ny(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=Ry(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){Fy(this),Iy(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Ly(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;Gb(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=Ry(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()}},Yb=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xb=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Zb=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Qb=BigInt(2**32-1),$b=BigInt(32);function ex(e,t=!1){return t?{h:Number(e&Qb),l:Number(e>>$b&Qb)}:{h:Number(e>>$b&Qb)|0,l:Number(e&Qb)|0}}function tx(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}=ex(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var nx=(e,t,n)=>e>>>n,rx=(e,t,n)=>e<<32-n|t>>>n,ix=(e,t,n)=>e>>>n|t<<32-n,ax=(e,t,n)=>e<<32-n|t>>>n,ox=(e,t,n)=>e<<64-n|t>>>n-32,sx=(e,t,n)=>e>>>n-32|t<<64-n;function cx(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var lx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ux=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,dx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),fx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,px=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),mx=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,hx=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]),gx=new Uint32Array(64),_x=class extends Jb{constructor(e=32){super(64,e,8,!1),this.A=Yb[0]|0,this.B=Yb[1]|0,this.C=Yb[2]|0,this.D=Yb[3]|0,this.E=Yb[4]|0,this.F=Yb[5]|0,this.G=Yb[6]|0,this.H=Yb[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)gx[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=gx[e-15],n=gx[e-2],r=zy(t,7)^zy(t,18)^t>>>3,i=zy(n,17)^zy(n,19)^n>>>10;gx[e]=i+gx[e-7]+r+gx[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=zy(o,6)^zy(o,11)^zy(o,25),u=l+t+Kb(o,s,c)+hx[e]+gx[e]|0,d=(zy(n,2)^zy(n,13)^zy(n,22))+qb(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(){Ly(gx)}destroy(){this.set(0,0,0,0,0,0,0,0),Ly(this.buffer)}},vx=tx(`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))),yx=vx[0],bx=vx[1],xx=new Uint32Array(80),Sx=new Uint32Array(80),Cx=class extends Jb{constructor(e=64){super(128,e,16,!1),this.Ah=Zb[0]|0,this.Al=Zb[1]|0,this.Bh=Zb[2]|0,this.Bl=Zb[3]|0,this.Ch=Zb[4]|0,this.Cl=Zb[5]|0,this.Dh=Zb[6]|0,this.Dl=Zb[7]|0,this.Eh=Zb[8]|0,this.El=Zb[9]|0,this.Fh=Zb[10]|0,this.Fl=Zb[11]|0,this.Gh=Zb[12]|0,this.Gl=Zb[13]|0,this.Hh=Zb[14]|0,this.Hl=Zb[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)xx[n]=e.getUint32(t),Sx[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=xx[e-15]|0,n=Sx[e-15]|0,r=ix(t,n,1)^ix(t,n,8)^nx(t,n,7),i=ax(t,n,1)^ax(t,n,8)^rx(t,n,7),a=xx[e-2]|0,o=Sx[e-2]|0,s=ix(a,o,19)^ox(a,o,61)^nx(a,o,6),c=dx(i,ax(a,o,19)^sx(a,o,61)^rx(a,o,6),Sx[e-7],Sx[e-16]),l=fx(c,r,s,xx[e-7],xx[e-16]);xx[e]=l|0,Sx[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=ix(u,d,14)^ix(u,d,18)^ox(u,d,41),v=ax(u,d,14)^ax(u,d,18)^sx(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=px(_,v,b,bx[e],Sx[e]),S=mx(x,g,t,y,yx[e],xx[e]),C=x|0,w=ix(n,r,28)^ox(n,r,34)^ox(n,r,39),T=ax(n,r,28)^sx(n,r,34)^sx(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}=cx(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=lx(C,T,D);n=ux(O,S,w,E),r=O|0}({h:n,l:r}=cx(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=cx(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=cx(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=cx(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=cx(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=cx(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=cx(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=cx(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(){Ly(xx,Sx)}destroy(){Ly(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},wx=class extends Cx{constructor(){super(48),this.Ah=Xb[0]|0,this.Al=Xb[1]|0,this.Bh=Xb[2]|0,this.Bl=Xb[3]|0,this.Ch=Xb[4]|0,this.Cl=Xb[5]|0,this.Dh=Xb[6]|0,this.Dl=Xb[7]|0,this.Eh=Xb[8]|0,this.El=Xb[9]|0,this.Fh=Xb[10]|0,this.Fl=Xb[11]|0,this.Gh=Xb[12]|0,this.Gl=Xb[13]|0,this.Hh=Xb[14]|0,this.Hl=Xb[15]|0}},Tx=Xy(()=>new _x),Ex=Xy(()=>new Cx),Dx=Xy(()=>new wx),Ox=class extends Yy{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Py(e);let n=qy(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),Ly(i)}update(e){return Fy(this),this.iHash.update(e),this}digestInto(e){Fy(this),Ny(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()}},kx=(e,t,n)=>new Ox(e,t).update(n).digest();kx.create=(e,t)=>new Ox(e,t);var Ax=BigInt(0),jx=BigInt(1);function Mx(e,t){let n=t.negate();return e?n:t}function Nx(e,t){let n=Rb(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Px(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function Fx(e,t){Px(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:pb(e),maxNumber:i,shiftBy:BigInt(e)}}function Ix(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+=jx);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 Lx(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 Rx(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 zx=new WeakMap,Bx=new WeakMap;function Vx(e){return Bx.get(e)||1}function Hx(e){if(e!==Ax)throw Error(`invalid wNAF`)}var Ux=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>Ax;)t&jx&&(n=n.add(r)),r=r.double(),t>>=jx;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=Fx(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=Fx(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Ix(n,e,a);n=o,c?i=i.add(Mx(u,t[d])):r=r.add(Mx(l,t[s]))}return Hx(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=Fx(e,this.bits);for(let e=0;e<i.windows&&n!==Ax;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=Ix(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Hx(n),r}getPrecomputes(e,t,n){let r=zx.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),zx.set(t,r))),r}cached(e,t,n){let r=Vx(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Vx(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Px(t,this.bits),Bx.set(e,t),zx.delete(e)}hasCache(e){return Vx(e)!==1}};function Wx(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>Ax||r>Ax;)n&jx&&(a=a.add(i)),r&jx&&(o=o.add(i)),i=i.double(),n>>=jx,r>>=jx;return{p1:a,p2:o}}function Gx(e,t,n,r){Lx(n,e),Rx(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=fb(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=pb(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 Kx(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Ib(t),t}return Vb(e,{isLE:n})}function qx(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>Ax))throw Error(`CURVE.${e} must be positive bigint`)}let i=Kx(t.p,n.Fp,r),a=Kx(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 Jx=(e,t)=>(e+(e>=0?t:-t)/tS)/t;function Yx(e,t,n){let[[r,i],[a,o]]=t,s=Jx(o*e,n),c=Jx(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<$x,f=u<$x;d&&(l=-l),f&&(u=-u);let p=pb(Math.ceil(fb(n)/2))+eS;if(l<$x||l>=p||u<$x||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function Xx(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function Zx(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return eb(n.lowS,`lowS`),eb(n.prehash,`prehash`),n.format!==void 0&&Xx(n.format),n}var Qx={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=Qx;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=nb(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?nb(i.length/2|128):``;return nb(e)+a+i+t},decode(e,t){let{Err:n}=Qx,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}=Qx;if(e<$x)throw new t(`integer: negative integers are not allowed`);let n=nb(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}=Qx;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 ib(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=Qx,i=cb(`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}=Qx,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},$x=BigInt(0),eS=BigInt(1),tS=BigInt(2),nS=BigInt(3),rS=BigInt(4);function iS(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=cb(`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 aS(e,t={}){let n=qx(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;hb(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=sS(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 eb(n,`isCompressed`),n?(u(),Jy(oS(!r.isOdd(a)),o)):Jy(Uint8Array.of(4),o,r.toBytes(a))}function f(e){tb(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,nS),rS),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 Yx(e,c.basises,i.ORDER)}let S=gb((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=gb(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=Mx(i,t),n=Mx(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(tb(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return T.fromBytes(cb(`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(nS),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,nS),{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,nS),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=>Nx(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 Nx(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===$x||r.is0())return T.ZERO;if(e===eS)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}=Wx(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===eS?!0:e?e(T,this):D.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===eS?this:e?e(T,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return eb(e,`isCompressed`),this.assertValidity(),p(T,this,e)}toHex(e=!0){return Hy(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 Nx(T,e)}static msm(e,t){return Gx(T,i,e,t)}static fromPrivateKey(e){return T.BASE.multiply(iS(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 Ux(T,t.endo?Math.ceil(E/2):E);return T.BASE.precompute(8),T}function oS(e){return Uint8Array.of(e?2:3)}function sS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function cS(e,t={}){let{Fn:n}=e,r=t.randomBytes||Zy,i=Object.assign(sS(e.Fp,n),{seed:Ub(n.ORDER)});function a(e){try{return!!iS(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 Wb(tb(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(iS(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=cb(`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=iS(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=>iS(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function lS(e,t,n={}){Py(t),hb(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||Zy,i=n.hmac||((e,...n)=>kx(t,e,Jy(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=cS(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>>eS}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){Xx(t);let n=p.signature;return tb(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}=Qx.toSig(tb(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(Gy(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*tS<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(Jy(oS(!(c&1)),u)),f=o.inv(l),p=x(cb(`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(Xx(e),e===`der`)return Gy(Qx.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 Jy(Uint8Array.of(this.recovery),t,n)}return Jy(t,n)}toHex(e){return Hy(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(cb(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(cb(`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 Hy(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return Hy(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=ib(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=pb(c);function C(e){return db(`num < 2^`+c,e,$x,S),o.toBytes(e)}function w(e,n){return tb(e,void 0,`message`),n?tb(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}=Zx(i,m);t=w(t,s);let l=x(t),u=iS(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(cb(`extraEntropy`,e))}let f=Jy(...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===$x)return;let c=o.create(r*o.create(h+s*u));if(c===$x)return;let l=(i.x===s?0:2)|Number(i.y&eS),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=cb(`message`,e);let{seed:a,k2sig:s}=T(e,n,r);return mb(t.outputLen,o.BYTES,i)(a,s)}function D(e){let t,n=typeof e==`string`||jy(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(cb(`sig`,e),`der`)}catch(e){if(!(e instanceof Qx.Err))throw e}if(!t)try{t=y.fromBytes(cb(`sig`,e),`compact`)}catch{return!1}}return t||!1}function O(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=Zx(i,m);if(r=cb(`publicKey`,r),n=w(cb(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?D(t):y.fromBytes(cb(`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}=Zx(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 uS(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:Vb(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 dS(e){let{CURVE:t,curveOpts:n}=uS(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 fS(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Bb(n.Fn.ORDER,n.Fn.BITS))})}function pS(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=dS(e);return fS(e,lS(aS(t,n),r,i))}function mS(e,t){let n=t=>pS({...e,hash:t});return{...n(t),create:n}}var hS={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)},gS={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)},_S={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)},vS=Vb(hS.p),yS=Vb(gS.p),bS=Vb(_S.p),xS=mS({...hS,Fp:vS,lowS:!1},Tx);mS({...gS,Fp:yS,lowS:!1},Dx),mS({..._S,Fp:bS,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Ex);var SS=xS,CS=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}})),wS=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}})),TS=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}})),ES=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}})),DS=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}})),OS=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)})),kS=R((e=>{var t=te(`buffer`).Buffer,n=CS(),r=wS(),i=TS(),a=ES(),o=DS(),s=OS(),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}})),AS=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)})}})),jS=V(R(((e,t)=>{var n=kS(),r=te(`dgram`),i=AS(),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 MS(){return c(2).readUInt16BE(0)}function NS(){return c(4).readUInt32BE(0)}var PS=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}},FS=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 IS(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 LS(e,t){return RS(e)(t)}function RS(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 zS(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 BS=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++)}},VS=3988292384,HS=2197175160;function US(e){return typeof e!=`string`}function WS(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 GS(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 KS(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 qS(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 JS=WS(VS),YS=GS(JS),XS=WS(HS),ZS=GS(XS);function QS(e,t=0){return US(e)?qS(e,t,JS,YS):KS(e,t,JS)}function $S(e,t=0){return US(e)?qS(e,t,XS,ZS):KS(e,t,XS)}function eC(e,t){return e+t&255}function tC(e,t){return e+t&65535}function nC(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function rC(e){return e&16777215}function iC(e,t){let n=32768;return e<t&&t-e>n||e>t&&e-t<n}function aC(e,t){let n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function oC(e,t){return e===t||aC(e,t)}var sC=e=>Number.parseInt(e,10),cC=(e,t)=>t?t[e]:void 0;async function lC(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:cC(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 uC(e){return e===`IPv4`?4:e===`IPv6`?6:e}var dC=ma.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}},fC=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e()),this._disposer=[]}},pC=dC(`werift-ice:packages/ice/src/transport.ts`),mC=class e{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=f(e),this.socket.on(`message`,(e,t)=>{uC(t.family)===6&&([t.address]=t.address.split(`%`)),this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){pC(`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=cC(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 lC(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?(pC(`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()}})},hC=class e{type=`tcp`;stream;constructor(e){this.stream=new _C(`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()}},gC=class e{type=`tls`;stream;constructor(e,t={}){this.stream=new _C(`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()}},_C=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=>{pC(`${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()}},vC={rsa_1:1,ecdsa_3:3},yC={sha256_4:4},bC={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},xC=Object.values(bC),SC={x25519_29:29,secp256r1_23:23},CC=Object.values(SC),wC={named_curve_3:3},TC={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},EC=[1,64],DC=[{hash:yC.sha256_4,signature:vC.rsa_1},{hash:yC.sha256_4,signature:vC.ecdsa_3}],OC=()=>{let e=SS.utils.randomPrivateKey(),t=SS.getPublicKey(e,!1);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}},kC=({publicKey:e,privateKey:t})=>{let n=SS.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function AC(e,t,n){switch(n){case SC.secp256r1_23:return kC({publicKey:e,privateKey:t});case SC.x25519_29:return Buffer.from(ky.default.scalarMult(t,e));default:throw Error()}}function jC(e,t,n){let r=o(e,t);return r.update(n),r.digest()}function MC(e,t,n,r=`sha256`){let i=n,a=[],o=t;do{o=jC(r,e,o);let i=jC(r,e,Buffer.concat([o,t]));a.push(i),n-=i.length}while(n>0);return Buffer.concat(a,i)}function NC(e,t,n){return MC(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function PC(e,t){let n=IC(`sha256`,t);return MC(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function FC(e,t,n,r,i,a){let o=a?r:i,s=a?i:r;return MC(n,Buffer.concat([Buffer.from(e),o,s]),t)}function IC(e,t){return a(e).update(t).digest()}function LC(e,t,n,r=12){let i=IC(`sha256`,t);return MC(e,Buffer.concat([Buffer.from(n),i]),r)}function RC(e,t){return LC(e,t,`client finished`)}function zC(e,t){return LC(e,t,`server finished`)}function BC(e,t,n,r,i,a,o=`sha256`){let s=r*2+i*2,c=e,l=Buffer.concat([n,t]),u=MC(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 VC={CLIENT:1,SERVER:2},HC=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}},UC=d;A_.set(UC);var WC=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 vC.rsa_1:return`RSASSA-PKCS1-v1_5`;case vC.ecdsa_3:return`ECDSA`}})(),r=(()=>{switch(e.hash){case yC.sha256_4:return`SHA-256`}})(),i=(()=>{switch(t){case SC.secp256r1_23:return`P-256`;case SC.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 UC.subtle.generateKey(a,!0,[`sign`,`verify`]);return{certPem:(await ry.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:ev.encode(await UC.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===VC.CLIENT?RC(this.masterSecret,e):zC(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===VC.CLIENT?this.localRandom:this.remoteRandom,n=this.sessionType===VC.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=ha.Certificate.fromPEM(Buffer.from(e)),i=ha.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:wC.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])}},GC=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(let n of t)if(e.includes(n))return n}},KC=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=null&&e.length>0).join(`,0x`),qC=e=>Object.entries({...e}).reduce((e,[t,n])=>((typeof n==`number`||typeof n==`string`)&&(e[t]=n),Buffer.isBuffer(n)&&(e[t]=KC(n)),e),{}),JC=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 qC(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:YC,uint24be:XC,buffer:ZC,array:QC,uint8:$C,string:ew}=Q.types,tw=QC({type:YC,data:ZC(YC)},YC,`bytes`),nw=ZC(XC),rw=$C,iw=ew(YC),aw={hash:$C,signature:$C},ow={major:$C,minor:$C},sw=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)}},cw=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:sw.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:tw};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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},lw=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:ow,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)}},uw=class e{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:KC(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 lw(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},dw=e=>t=>(e.lastFlight=t,t.flatMap(t=>(t.messageSeq=e.sequenceNumber++,t.toFragment().chunk()))),fw=e=>(t,n)=>t.map(t=>new uw({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)),pw=(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))(pw||{}),mw=dC(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`),hw=dC(`werift-dtls : packages/dtls/src/flight/flight.ts : err`),gw=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=dw(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),fw(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=>{hw(`fail to send`,hw)}),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}mw(this.dtls.sessionId,`retransmit`,n,this.dtls.flight)}if(n>e.RetransmitCount)throw hw(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}},_w=class extends gw{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 cw({major:254,minor:253},new sw,Buffer.from([]),Buffer.from([]),xC,[0],e);this.dtls.version=t.clientVersion,this.cipher.localRandom=sw.from(t.random);let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},vw=dC(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`),yw=class extends gw{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;vw(`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])}},bw={NULL:0,ECDHE:1},xw={NULL:0,RSA:1,ECDSA:2,PSK:3},Sw={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},Cw=class{id=0;name;signType;keyType;toString(){return this.name}};function ww(){let e=new Cw;return e.id=Sw.RSA,e.name=`RSA`,e.keyType=xw.RSA,e}function Tw(){let e=new Cw;return e.id=Sw.ECDHE_RSA,e.name=`ECDHE_RSA`,e.signType=bw.ECDHE,e.keyType=xw.RSA,e}function Ew(){let e=new Cw;return e.id=Sw.ECDHE_ECDSA,e.name=`ECDHE_ECDSA`,e.signType=bw.ECDHE,e.keyType=xw.ECDSA,e}function Dw(){let e=new Cw;return e.id=Sw.PSK,e.name=`PSK`,e.signType=bw.NULL,e.keyType=xw.PSK,e}function Ow(){let e=new Cw;return e.id=Sw.ECDHE_PSK,e.name=`ECDHE_PSK`,e.signType=bw.ECDHE,e.keyType=xw.PSK,e}var kw=dC(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`),Aw=class extends HC{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return qC(this)}init(e,t,n){let r=BC(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===VC.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===VC.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 kw(`decrypt failed`,r,e,KC(t),n,this.summary),r}}},jw={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},Mw={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},Nw={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},Pw=ww(),Fw=Tw(),Iw=Ew(),Lw=Dw(),Rw=Ow();function zw(e){switch(e){case jw.TLS_RSA_WITH_AES_128_GCM_SHA256:return Bw(jw.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,Pw,Mw);case jw.TLS_RSA_WITH_AES_256_GCM_SHA384:return Bw(jw.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,Pw,Nw,`sha384`);case jw.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Bw(jw.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,Fw,Mw);case jw.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Bw(jw.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,Fw,Nw,`sha384`);case jw.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Bw(jw.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,Iw,Mw);case jw.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Bw(jw.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,Iw,Nw,`sha384`);case jw.TLS_PSK_WITH_AES_128_GCM_SHA256:return Bw(jw.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,Lw,Mw,`sha256`);case jw.TLS_PSK_WITH_AES_256_GCM_SHA384:return Bw(jw.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,Lw,Nw,`sha384`);case jw.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Bw(jw.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,Rw,Mw,`sha256`);case jw.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Bw(jw.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,Rw,Nw,`sha384`)}return null}function Bw(e,t,n,r,i,a=`sha256`){let o=new Aw;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 Vw(e){switch(e){case SC.secp256r1_23:{let{privateKey:t,publicKey:n}=OC();return{curve:e,privateKey:t,publicKey:n}}case SC.x25519_29:{let t=ky.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw Error()}}var Hw=class{static type=23},Uw=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)}}},Ww=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)}}},Gw=class e{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Q.types.array(nw,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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Kw=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)}},qw=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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Jw=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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Yw=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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Xw=class e{constructor(e,t,n){this.certificateTypes=e,this.signatures=t,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:Q.types.array(rw,Q.types.uint8,`bytes`),signatures:Q.types.array(aw,Q.types.uint16be,`bytes`),authorities:Q.types.array(iw,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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Zw=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:ow,random:sw.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:tw}))):r}serialize(){let t=this.extensions===void 0?(0,Q.encode)(this,e.spec).slice():(0,Q.encode)(this,{...e.spec,extensions:tw}).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Qw=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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}};function $w(e,t){return Buffer.from((0,Q.encode)(e,t).slice())}var eT=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 $w(this,e.spec)}toFragment(){let e=this.serialize();return new JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},tT=e=>{switch(e){case 1:case 7:return 16}},nT=e=>{switch(e){case 1:return 14;case 7:return 12}};dC(`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 rT(e,t){let n=Buffer.alloc(t);return e.copy(n),n}function iT(e){return Number.parseInt(e.toString(),10)}function aT(e){let t=e[0];return t>127&&t<192}var oT=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 PS(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),LS([1,1,2],[e.value,this.type,this.length])}static deSerialize(t){let[n,r,i]=zS(t,[1,1,2]),a=IS(n,0,2),o=IS(n,2,1)>0,s=IS(n,3,5);return new e({version:a,padding:o,count:s,type:r,length:i})}},sT=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]=zS(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=LS([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])}},cT=class e{static count=1;count=e.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r]=zS(t,[4,4]);return new e({senderSsrc:n,mediaSsrc:r})}serialize(){return LS([4,4],[this.senderSsrc,this.mediaSsrc])}},lT=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]=zS(t,[4,4,4,1,1]),s=IS(o,0,6),c=(IS(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:LS([4],[i]).toString(),ssrcNum:a,brExp:s,brMantissa:c,ssrcFeedbacks:u,bitrate:l})}serialize(){let e=Buffer.concat([LS([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),LS([1],[this.ssrcNum])]),t=new PS(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(e=>LS([4],[e]))),r=Buffer.concat([e,LS([3],[t.value]),n]);return this.length=r.length/4,r}},uT=dC(`werift-rtp: /rtcp/psfb/index`),dT=class e{static type=206;type=e.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return oT.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(t,n){let r;switch(n.count){case sT.count:r=sT.deSerialize(t);break;case cT.count:r=cT.deSerialize(t);break;case lT.count:r=lT.deSerialize(t);break;default:uT(`unknown psfb packet`,n.count)}return new e({feedback:r})}},fT=class e{ssrc=0;reports=[];static type=201;type=e.type;constructor(e={}){Object.assign(this,e)}serialize(){let t=LS([4],[this.ssrc]);return t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),oT.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let[r]=zS(t,[4]),i=4,a=[];for(let e=0;e<n;e++)a.push(pT.deSerialize(t.slice(i,i+24))),i+=24;return new e({ssrc:r,reports:a})}},pT=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 LS([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]=zS(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})}},mT=205,hT=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 oT({type:mT,count:this.count,version:2})}static deSerialize(t,n){let[r,i]=zS(t,[4,4]),a=[];for(let e=8;e<t.length;e+=4){let[n,r]=zS(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=LS([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(LS([2,2],[e,n])),e=r,n=0)}),t.push(LS([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])}},gT=dC(`werift/rtp/rtcp/rtpfb/twcc`),_T=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 oT({type:205,count:this.count,version:2})}static deSerialize(t,n){let[r,i,a,o,s,c]=zS(t,[4,4,2,2,3,1]),l=[],u=[],d=16;for(let e=0;e<o;){let n=IS(t.slice(d,d+1)[0],0,1),r;switch(n){case 0:{let n=vT.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 bT({type:n.packetStatus}));e+=i}break;case 1:{let n=yT.deSerialize(t.slice(d,d+2));r=n,n.symbolSize===0&&n.symbolList.forEach(e=>{e===1&&u.push(new bT({type:1}))}),n.symbolSize===1&&n.symbolList.forEach(e=>{(e===1||e===2)&&u.push(new bT({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=LS([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){gT(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 vT).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}},vT=class e{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(t){let n=IS(t[0],1,2),r=(IS(t[0],3,5)<<8)+t[1];return new e({type:0,packetStatus:n,runLength:r})}serialize(){return new FS(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 xT({sequenceNumber:++e,received:t}));return n}},yT=class e{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=IS(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(IS(t[0],2+e,1))),i(8,e=>r.push(IS(t[1],e,1)));break;case 1:i(3,e=>r.push(IS(t[0],2+e*2,2))),i(4,e=>r.push(IS(t[1],e*2,2)));break;default:n=(IS(t[0],2,6)<<8)+t[1]}return new e({type:1,symbolSize:n,symbolList:r})}serialize(){let e=Buffer.alloc(2),t=new FS(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}},bT=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)}},xT=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(e){Object.assign(this,e)}},ST=dC(`werift-rtp:packages/rtp/rtcp/rtpfb/index`),CT=class e{static type=mT;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 hT.count:r=hT.deSerialize(t,n);break;case _T.count:r=_T.deSerialize(t,n);break;default:ST(`unknown rtpfb packet`,n.count)}return new e({feedback:r,header:n})}},wT=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 oT.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=TT.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({chunks:r})}},TT=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+=DT(e),e}serialize(){let e=Buffer.concat([LS([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(DT(e.length))])}static deSerialize(t){let n=t.readUInt32BE(),r=[];for(let e=4;e<t.length&&t[e]!==0;){let n=ET.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({source:n,items:r})}},ET=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([LS([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 DT(e){return e%4==0?0:4-e%4}var OT=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())]),oT.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let r=t.readUInt32BE(),i=kT.deSerialize(t.subarray(4,24)),a=24,o=[];for(let e=0;e<n;e++)o.push(pT.deSerialize(t.subarray(a,a+24))),a+=24;return new e({ssrc:r,senderInfo:i,reports:o})}},kT=class e{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:AT(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return LS([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(t){let[n,r,i,a]=zS(t,[8,4,4,4]);return new e({ntpTimestamp:n,rtpTimestamp:r,packetCount:i,octetCount:a})}},AT=e=>{let[t,n]=zS(LS([8],[e]),[4,4]);return Number(`${t}.${n}`)},jT=dC(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`),MT=class{static deSerialize(e){let t=0,n=[];for(;t<e.length;){let r=oT.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 OT.type:n.push(OT.deSerialize(i,r.count));break;case fT.type:n.push(fT.deSerialize(i,r.count));break;case wT.type:n.push(wT.deSerialize(i,r));break;case CT.type:n.push(CT.deSerialize(i,r));break;case dT.type:n.push(dT.deSerialize(i,r))}}catch(e){jT(`deSerialize RTCP`,e)}}return n}};function NT(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var PT={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 FT(e,t){return e.map(e=>{let n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case PT.sdesMid:case PT.sdesRTPStreamID:case PT.repairedRtpStreamId:return{uri:n,value:VT(e.payload)};case PT.transportWideCC:return{uri:n,value:HT(e.payload)};case PT.absSendTime:return{uri:n,value:UT(e.payload)};case PT.audioLevelIndication:return{uri:n,value:WT(e.payload)};case PT.videoOrientation:return{uri:n,value:GT(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>(t&&(e[t.uri]=t.value),e),{})}function IT(e){return Buffer.from(e)}function LT(e){return Buffer.from(e)}function RT(e){return Buffer.from(e)}function zT(e){return LS([2],[e])}function BT(e){let t=Buffer.alloc(3),n=e>>14n&16777215n;return t.writeUIntBE(Number(n),0,3),t}function VT(e){return e.toString()}function HT(e){return e.readUInt16BE()}function UT(e){return zS(e,[3])[0]}function WT(e){let t=new BS(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function GT(e){let t=new BS(e);return t.readBits(4),{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var KT=dC(`packages/rtp/src/rtp/red/packet.ts`),qT=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]=JT.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 JT;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}},JT=class e{fields=[];static deSerialize(t){let n=0,r=new e;for(;;){let e={};r.fields.push(e);let i=new BS(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 BS(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 BS(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){KT(e?.message)}return e}},YT=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 qT,t=this.cache.slice(-(this.distance+1)),n=t.pop();return n?(t.forEach(t=>{let r=nC(n.timestamp,-t.timestamp);r>XT||e.blocks.push({block:t.block,blockPT:t.blockPT,timestampOffset:r})}),e.blocks.push({block:n.block,blockPT:n.blockPT}),e):e}},XT=16383,ZT=class{size=150;sequenceNumbers=[];push(e,t){let n=[];return e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{let s=tC(t.header.sequenceNumber,-(e.blocks.length-(o+1)));i?n.push(new aE(new iE({timestamp:nC(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a)):n.push(new aE(new iE({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))}},QT={OneByte:48862,TwoByte:4096},$T=2,eE=4,tE=8,nE=12,rE=4,iE=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=QT.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=new e,r=0,i=t[r++];n.version=IS(i,0,2),n.padding=IS(i,2)>0,n.extension=IS(i,3)>0,n.csrcLength=IS(i,4,4),n.csrc=[...Array(n.csrcLength)].map(()=>{let e=t.readUInt32BE(r);return r+=4,e}),r+=nE-1;let a=t[1];n.marker=IS(a,0)>0,n.payloadType=IS(a,1,7),n.sequenceNumber=t.readUInt16BE($T),n.timestamp=t.readUInt32BE(eE),n.ssrc=t.readUInt32BE(tE);for(let e=0;e<n.csrc.length;e++){let r=nE+e*rE;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 QT.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 QT.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*rE;if(n.length>0||this.extension===!0){let e=4;switch(t){case QT.OneByte:for(let t of n)e+=1+t.payload.length;break;case QT.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 PS(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 PS(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,n++),t.writeUInt16BE(this.sequenceNumber,$T),n+=2,t.writeUInt32BE(this.timestamp,eE),n+=4,t.writeUInt32BE(this.ssrc,tE),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 QT.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 QT.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}},aE=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 iE({...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=iE.deSerialize(t);return new e(n,t.subarray(n.payloadOffset,t.length-n.paddingSize))}clear(){this.payload=null}};function oE(e,t,n){return new aE(new iE({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function sE(e,t,n,r){let i=Buffer.allocUnsafe(2);return i.writeUInt16BE(e.header.sequenceNumber,0),new aE(new iE({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 cE=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[]}},lE=class extends Error{constructor(e){super(e),this.name=`SrtpAuthenticationError`}},uE=12,dE=8;function fE(e,t,n=`Failed to authenticate SRTP packet`){let r=e.length-t;mE(e.length>=uE+t,n);let i=hE(()=>iE.deSerialize(e.subarray(0,r)),n);return i.paddingSize=0,mE(i.payloadOffset>=uE&&i.payloadOffset<=r,n),i}function pE(e,t,n,r=`Failed to authenticate SRTCP packet`){return mE(e.length>=dE+t+n,r),hE(()=>oT.deSerialize(e.subarray(0,4)),r)}function mE(e,t){if(!e)throw new lE(t)}function hE(e,t){try{return e()}catch{throw new lE(t)}}function gE(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding)return e.paddingSize=0,e;mE(t.length>e.payloadOffset,n);let r=t[t.length-1];return mE(r>0&&r<=t.length-e.payloadOffset,n),e.paddingSize=r,e}var _E=class extends cE{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=fE(e,this.authTagLength)){let r=e.length-this.authTagLength,a=e.subarray(0,r);yE(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,gE(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=pE(e,this.authTagLength,vE),n=e.length-(this.authTagLength+vE),r=e.subarray(0,e.length-this.authTagLength);yE(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)}},vE=4;function yE(e,t,n){if(e.length!==t.length||!u(e,t))throw new lE(n)}var bE=class extends cE{aeadAuthTagLen=16;rtpIvWriter=RS([2,4,4,2],!0);rtcpIvWriter=RS([2,4,2,4],!0);aadWriter=RS([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=fE(e,this.aeadAuthTagLen)){let r=e.subarray(0,n.payloadOffset),a=e.length-this.aeadAuthTagLen,o=e.subarray(a),s=Buffer.from([]);s=rT(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 CE(u,`SRTP`),d.copy(s,n.payloadOffset),[s,gE(n,s,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=e.readUInt32BE(4),i=e.length+this.aeadAuthTagLen,a=Buffer.from([]);a=rT(a,i+xE),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=pE(e,this.aeadAuthTagLen,xE),n=e.length-xE,r=n-this.aeadAuthTagLen,a=e.readUInt32BE(4),o=e.readUInt32BE(n),s=o>>>31==1,c=o&~(SE<<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 CE(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]|=SE,n}},xE=4,SE=128;function CE(e,t){try{e.final()}catch{throw new lE(`Failed to authenticate ${t} packet`)}}function wE(e,t){let n=r(`aes-128-ecb`,e,null);return n.setAutoPadding(!1),Buffer.concat([n.update(t),n.final()])}var TE=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 _E(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new bE(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])]),wE(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=wE(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=wE(this.masterKey,r),i=wE(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>EE&&t.rolloverCounter++:t.lastSequenceNumber<EE&&e>DE-EE?t.rolloverCounter>0&&t.rolloverCounter--:e<EE&&t.lastSequenceNumber>DE-EE&&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}},EE=100,DE=65535,OE=class extends TE{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){let t=e.readUInt32BE(4),n=this.getSrtcpSsrcState(t);return n.srtcpIndex++,n.srtcpIndex>>kE&&(n.srtcpIndex=0),this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}},kE=2147483647,AE=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)}},jE=class extends AE{constructor(e){super(OE),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)}},ME=class extends TE{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=fE(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}},NE=class extends AE{constructor(e){super(ME),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)}},PE=dC(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`),FE=class extends gw{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 Zw.deSerialize(e.fragment);case 11:return Gw.deSerialize(e.fragment);case 12:return eT.deSerialize(e.fragment);case 13:return Xw.deSerialize(e.fragment);case 14:return Qw.deSerialize(e.fragment)}})();t&&IE[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){PE(this.dtls.sessionId,`flight5 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let e=this.dtls.requestedCertificateTypes.length>0;PE(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 Gw([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 Jw(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=AC(i.publicKey,r.privateKey,r.curve);PE(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?PC(a,o):NC(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=zw(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),PE(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 vC.ecdsa_3:return TC.ecdsa_secp256r1_sha256;case vC.rsa_1:return TC.rsa_pkcs1_sha256}})();if(!n)throw Error();PE(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);let r=new qw(n,t),i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){let e=Kw.createEmpty().serialize(),t=fw(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 Yw(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 PE(this.dtls.sessionId,`finished`,this.cipher.cipher.summary),r}},IE={};IE[2]=({cipher:e,srtp:t,dtls:n})=>r=>{PE(n.sessionId,`serverHello`,r.cipherSuite),e.remoteRandom=sw.from(r.random),e.cipherSuite=r.cipherSuite,PE(n.sessionId,`selected cipherSuite`,e.cipherSuite),r.extensions&&r.extensions.forEach(e=>{switch(e.type){case Ww.type:{let r=Ww.fromData(e.data),i=GC.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);if(PE(n.sessionId,`selected srtp profile`,i),i==null)return;t.srtpProfile=i}break;case Hw.type:n.remoteExtendedMasterSecret=!0;break;case Uw.type:PE(n.sessionId,`RenegotiationIndication`)}})},IE[11]=({cipher:e,dtls:t})=>n=>{PE(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},IE[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw Error();PE(t.sessionId,`ServerKeyExchange`,n),PE(t.sessionId,`selected curve`,n.namedCurve),e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey},e.localKeyPair=Vw(n.namedCurve)},IE[13]=({dtls:e})=>t=>{PE(e.sessionId,`certificate_request`,t),e.requestedCertificateTypes=t.certificateTypes,e.requestedSignatureAlgorithms=t.signatures},IE[14]=({dtls:e})=>t=>{PE(e.sessionId,`server_hello_done`,t)};var LE=class e{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:ow,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 JC(this.msgType,e.length,this.messageSeq,0,e.length,e)}},RE=dC(`werift-dtls : packages/dtls/src/context/dtls.ts : log`),zE=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||(RE(this.sessionId,`exist`,r.summary,t,n),!1)});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}},BE=class{constructor(e){this.socket=e}send=(e,t)=>this.socket.send(e,t)},VE=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)}}},HE=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)}}},UE=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)}},WE=dC(`werift-dtls : packages/dtls/record/receive.ts : log`),GE=dC(`werift-dtls : packages/dtls/record/receive.ts : err`),KE=e=>{let t=0,n=[];for(;e.length>t;){let r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;let i=uw.deSerialize(e.subarray(t));n.push(i),t+=13+r}return n},qE=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:return WE(e.sessionId,`change cipher spec`),[{type:20,data:void 0}];case 22:{let r=n.fragment;try{n.recordLayerHeader.epoch>0&&(WE(e.sessionId,`decrypt handshake`),r=t.decryptPacket(n))}catch(t){throw GE(e.sessionId,`decrypt failed`,t),t}try{let e=0,t=[];for(;r.length>e;){let n=JC.deSerialize(r.subarray(e));t.push({type:22,data:n}),e+=n.fragment_length+12}return t}catch(t){throw GE(e.sessionId,`decSerialize failed`,t,r),t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=UE.deSerialize(n.fragment);if(pw[r.description]==null){let e=t.decryptPacket(n);r=UE.deSerialize(e)}if(GE(e.sessionId,`ContentType.alert`,r,pw[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}]}},JE=dC(`werift-dtls : packages/dtls/src/socket.ts : log`),YE=dC(`werift-dtls : packages/dtls/src/socket.ts : err`),XE=class{constructor(e,t){this.options=e,this.sessionType=t,this.dtls=new zE(this.options,this.sessionType),this.cipher=new WC(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new BE(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new $;onData=new $;onError=new $;onClose=new $;transport;cipher;dtls;srtp=new GC;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){JE(`renegotiation`,this.sessionType),this.connected=!1,this.cipher=new WC(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new zE(this.options,this.sessionType),this.srtp=new GC,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{let t=KE(e);for(let e of t)try{let t=qE(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=>JC.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{YE(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){YE(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){if(JE(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let e=Ww.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{let e=VE.createEmpty();e.data=CC,this.extensions.push(e.extension)}{let e=HE.createEmpty();e.data=DC,this.extensions.push(e.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:Hw.type,data:Buffer.alloc(0)});{let e=Uw.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=fw(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===VC.CLIENT?{localKey:r,localSalt:a,remoteKey:i,remoteSalt:o}:{localKey:i,localSalt:o,remoteKey:r,remoteSalt:a}}exportKeyingMaterial(e,t){return FC(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===VC.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},ZE=dC(`werift-dtls : packages/dtls/src/client.ts : log`),QE=class extends XE{constructor(e){super(e,VC.CLIENT),this.onHandleHandshakes=this.handleHandshakes,ZE(this.dtls.sessionId,`start client`)}async connect(){await new _w(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{ZE(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 3:{let e=LE.deSerialize(t.fragment);await new yw(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new FE(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(),ZE(this.dtls.sessionId,`dtls connected`)}}},$E=dC(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`),eD=(e,t,n,r)=>i=>{$E(`dtls version`,i.clientVersion),t.flight=2,t.recordSequenceNumber=0,t.sequenceNumber=0,i.extensions.forEach(e=>{switch(e.type){case VE.type:{let r=VE.fromData(e.data).data;$E(t.sessionId,`curves`,r),n.namedCurve=r.filter(e=>CC.includes(e))[0],$E(t.sessionId,`curve selected`,n.namedCurve)}break;case HE.type:{if(!n.signatureHashAlgorithm)throw Error(`need to set certificate`);let r=HE.fromData(e.data).data;$E(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 Ww.type:{if(!t.options?.srtpProfiles||t.options.srtpProfiles.length===0)return;let n=Ww.fromData(e.data);$E(t.sessionId,`srtp profiles`,n.profiles);let i=GC.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw Error();r.srtpProfile=i,$E(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case Hw.type:t.remoteExtendedMasterSecret=!0;break;case Uw.type:$E(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:$E(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}}),n.localRandom=new sw,n.remoteRandom=sw.from(i.random);let a=i.cipherSuites;$E(t.sessionId,`cipher suites`,a);let o=(()=>{switch(n.signatureHashAlgorithm?.signature){case vC.ecdsa_3:return bC.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case vC.rsa_1:return bC.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,$E(t.sessionId,`selected cipherSuite`,n.cipherSuite),n.localKeyPair=Vw(n.namedCurve),t.cookie||=c(20);let s=new LE({major:254,minor:253},t.cookie),l=dw(t)([s]),u=fw(t)(l.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(let t of u)e.send(t)},tD=dC(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`),nD=class extends gw{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){tD(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(Ww.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&e.push({type:Hw.type,data:Buffer.alloc(0)});let t=Uw.createEmpty();e.push(t.extension);let n=new Zw(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 Gw([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 eT(wC.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 Xw(EC,DC,[]);tD(this.dtls.sessionId,`sendCertificateRequest`,e);let t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerHelloDone(){let e=new Qw,t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}},rD=dC(`werift-dtls : packages/dtls/flight/server/flight6.ts`),iD=class extends gw{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 Gw.deSerialize(e.fragment);case 15:return qw.deSerialize(e.fragment);case 16:return Jw.deSerialize(e.fragment);case 20:return Yw.deSerialize(e.fragment)}})();if(t){let e=aD[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){rD(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=Kw.createEmpty().serialize(),t=fw(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 Yw(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},aD={};aD[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=AC(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);rD(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?PC(r,i):NC(r,e.remoteRandom.serialize(),e.localRandom.serialize()),e.cipher=zw(e.cipherSuite),e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize()),rD(t.sessionId,`setup cipher`,e.cipher.summary)},aD[11]=({cipher:e,dtls:t})=>n=>{rD(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},aD[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw Error(`client certificate missing before certificate verify`);rD(t.sessionId,`certificate_verify`,n.algorithm)},aD[20]=({dtls:e})=>t=>{rD(e.sessionId,`finished`,t)};var oD=dC(`werift-dtls : packages/dtls/src/server.ts : log`),sD=class extends XE{constructor(e){super(e,VC.SERVER),this.onHandleHandshakes=this.handleHandshakes,oD(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{oD(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=cw.deSerialize(t.fragment);e.cookie.length===0?(oD(this.dtls.sessionId,`send flight2`),eD(this.transport,this.dtls,this.cipher,this.srtp)(e)):this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)?(oD(this.dtls.sessionId,`send flight4`),await new nD(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)):oD(`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 iD(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(),oD(this.dtls.sessionId,`dtls connected`)}}}},cD=554869826,lD=1398035790;function uD(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 dD(e){let t=Buffer.alloc(2);return t.writeUInt16BE(e.length,0),Buffer.concat([t,e])}function fD(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 pD(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=pD(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 mD(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 hD(e){return x(e)}function gD(e){let[t]=e,n=hD(t)?1:2,r=Buffer.alloc(4);return r.writeUInt8(0,0),r.writeUInt8(n,1),r.writeUInt16BE(e[1],2),Buffer.concat([r,pD(t)])}function _D(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 vD(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[mD(r),n];case 2:if(r.length!==16)throw Error(`STUN address has invalid length for IPv6`);return[mD(r),n];default:throw Error(`STUN address has unknown protocol`)}}var yD=Buffer.alloc(6);yD.writeUInt16BE(cD>>16,0),yD.writeUInt32BE(cD,2);function bD(e,t){let n=[...yD,...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 xD(e,t){return vD(bD(e,t))}function SD(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 CD(e){let t=Buffer.alloc(e.length*2);return e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)}),t}function wD(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 TD(e,t){return bD(gD(e),t)}var ED=e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t},DD=e=>e.readUInt32BE(0),OD=e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e,0),t},kD=e=>e.readUInt16BE(0),AD=e=>{let t=Buffer.allocUnsafe(8);return t.writeBigUInt64BE(e,0),t},jD=e=>e.readBigUInt64BE(0),MD=e=>Buffer.from(e,`utf8`),ND=e=>e.toString(`utf8`),PD=e=>{if([...e].length>=128)throw Error(`SOFTWARE must be shorter than 128 characters`);return MD(e)},FD=e=>e,ID=e=>e,LD=[[1,`MAPPED-ADDRESS`,gD,vD],[3,`CHANGE-REQUEST`,ED,DD],[4,`SOURCE-ADDRESS`,gD,vD],[5,`CHANGED-ADDRESS`,gD,vD],[6,`USERNAME`,MD,ND],[8,`MESSAGE-INTEGRITY`,FD,ID],[9,`ERROR-CODE`,SD,_D],[10,`UNKNOWN-ATTRIBUTES`,CD,wD],[12,`CHANNEL-NUMBER`,OD,kD],[13,`LIFETIME`,ED,DD],[18,`XOR-PEER-ADDRESS`,TD,xD],[19,`DATA`,FD,ID],[20,`REALM`,MD,ND],[21,`NONCE`,FD,ID],[22,`XOR-RELAYED-ADDRESS`,TD,xD],[23,`REQUESTED-ADDRESS-FAMILY`,ED,DD],[24,`EVEN-PORT`,FD,ID],[25,`REQUESTED-TRANSPORT`,ED,DD],[28,`MESSAGE-INTEGRITY-SHA256`,FD,ID],[29,`PASSWORD-ALGORITHM`,FD,ID],[30,`USERHASH`,FD,ID],[32,`XOR-MAPPED-ADDRESS`,TD,xD],[34,`RESERVATION-TOKEN`,FD,ID],[36,`PRIORITY`,ED,DD],[37,`USE-CANDIDATE`,()=>Buffer.alloc(0),()=>null],[32770,`PASSWORD-ALGORITHMS`,FD,ID],[32771,`ALTERNATE-DOMAIN`,MD,ND],[32802,`SOFTWARE`,PD,ND],[32803,`ALTERNATE-SERVER`,gD,vD],[32808,`FINGERPRINT`,ED,DD],[32809,`ICE-CONTROLLED`,AD,jD],[32810,`ICE-CONTROLLING`,AD,jD],[32811,`RESPONSE-ORIGIN`,gD,vD],[32812,`OTHER-ADDRESS`,gD,vD]],RD=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=[]}},zD=LD.reduce((e,t)=>(e[t[0]]=t,e),{}),BD=LD.reduce((e,t)=>(e[t[1]]=t,e),{});function VD(e,t){if(!uD(e))return;let n=e.readUInt16BE(0),r=Buffer.from(e.slice(8,20)),i=new RD,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=qD(c);if(u+f>e.length)return;let p=zD[s];if(p){let[,a,,s]=p,c;try{c=s.name===xD.name?s(d,r):s(d)}catch{return}if(i.setAttribute(a,c),a===`FINGERPRINT`){let t=GD(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){let r=KD(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 HD(n&16111,n&272,r,i.getAttributes(),a)}var HD=class extends RD{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=>UD(e.type,e.value))),t=Buffer.alloc(8);return t.writeUInt16BE(this.messageMethod|this.messageClass,0),t.writeUInt16BE(e.length,2),t.writeUInt32BE(cD,4),Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){return this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e)),this}messageIntegrity(e){let t=WD(this.bytes,this.bytes.length-20+24);return Buffer.from(o(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){return this.setAttribute(`FINGERPRINT`,GD(this.bytes)),this}get serializedAttributes(){let e=[];for(let t of this.attributesKeys){let n=this.getAttributeValue(t),[r,,i]=BD[t],a=i.name===TD.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 UD(e,t){let n=t.length,r=qD(n),i=Buffer.alloc(4);return i.writeUInt16BE(e,0),i.writeUInt16BE(n,2),Buffer.concat([i,t,Buffer.alloc(r)])}var WD=(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 GD(e){return(QS(WD(e,e.length-20+8))^lD)>>>0}function KD(e,t){let n=WD(e,e.length-20+24);return Buffer.from(o(`sha1`,t).update(n).digest(`hex`),`hex`)}function qD(e){let t=e%4;return t===0?0:4-t}var JD=class extends Error{response;addr},YD=class extends JD{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}},XD=class extends JD{get str(){return`STUN transaction timed out`}},ZD=dC(`werift-ice:packages/ice/src/stun/transaction.ts`);async function QD(e,t=0){return b(e[0])?e:[(await D.lookup(e[0],{family:t})).address,e[1]]}function $D(e,t){return typeof e==`object`&&e?e:{retransmissions:typeof e==`number`?e:void 0,onRequestSent:t}}function eO(e,t){return e[0]===t[0]&&e[1]===t[1]}var tO=class{constructor(e,t,n,r,i){this.request=e,this.addr=t,this.protocol=n;let a=$D(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(!eO(this.expectedAddr,t)){ZD(`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`))){ZD(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}e.messageClass===256?(this.onResponse.execute(e,t),this.onResponse.complete()):this.onResponse.error(new YD(e,t))}};run=async()=>{try{if(this.signal?.aborted)throw new XD;return this.attachAbortListener(),this.retry().catch(e=>{ZD(`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 XD))}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=>{ZD(`send stun failed`,e)}),await this.wait(this.timeoutDelay),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&!this.ended&&(ZD(`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 nO(e,t,n){let r=$D(t,n);return e&&!r.integrityKey&&(r.integrityKey=e),r}var rO=dC(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function iO(e){return`${e[0]}:${e[1]}`}function aO(e){if(e.remoteAddress&&e.remotePort)return[e.remoteAddress,e.remotePort]}async function oO(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 sO=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(iO(t),e)}forgetSocket(e){e&&this.sockets.delete(iO(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}=fD(n.buffer);n.buffer=i;let a=n.remoteAddr??aO(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=>{rO(`tcp socket error`,e)}),n}handleFrame(e,t){try{let n=VD(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?VD(e,r.integrityKey):n;if(!i){rO(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){rO(`tcp frame parse error`,e)}}async sendFrame(e,t){let n=await this.getSocket(t);await new Promise((t,r)=>{n.socket.write(dD(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 QD(t),o=nO(n,r,i),s=new tO(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===iO(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()}},cO=class extends sO{pendingSockets=new Map;async connectionMade(e){this.localIp=e}async getSocket(e){let t=iO(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)}}},lO=class extends sO{server=y(e=>{this.registerSocket(e,aO(e))});async connectionMade(e,t){if(this.localIp=e,t){let n;for(let r=t[0];r<=t[1];r++)try{await oO(this.server,e,r);return}catch(e){n=e}throw n??Error(`tcp port not found`)}await oO(this.server,e)}async getSocket(e){let t=this.sockets.get(iO(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())})}},uO=dC(`werift-ice : packages/ice/src/stun/protocol.ts`),dO=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 mC.init(`udp4`,{portRange:t,interfaceAddresses:n}):await mC.init(`udp6`,{portRange:t,interfaceAddresses:n}),this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{let n=VD(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?VD(e,r.integrityKey):n;if(!i){uO(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){uO(`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(()=>{uO(`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 QD(t,this.transport.socketType===`udp6`?6:4),o=nO(n,r,i),s=new tO(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 fO(e,t,n){return a(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function pO(e){return c(e).toString(`hex`).substring(0,e)}function mO(){return c(12)}var hO=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)})})}},gO=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 _O(e){return e.length>=4&&(e[0]&192)==64}function vO(e,t){let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t.length,2),Buffer.concat([n,t])}function yO(e){if(!_O(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 bO(e){let t=qD(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function xO(e){let t=[],n=0,r=!1;for(;e.length-n>=4;){let i;if(_O(e.subarray(n))){let t=e.readUInt16BE(n+2);i=4+t+qD(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+qD(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 SO=dC(`werift-ice:packages/ice/src/turn/protocol.ts`),CO=500,wO=600,TO=285212672;function EO(e){return e.type===`tcp`||e.type===`tls`}function DO(e){return e[0]}function OO(e){return JSON.stringify(e)}var kO=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 fC;onRequestReceived=new $;onDataReceived=new $;handleStunMessage=(e,t)=>{try{let n=VD(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?VD(e,r.integrityKey):n;if(!i){SO(`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){SO(`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 QD(t),o=nO(n,r,i),s=new tO(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()}},AO=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??CO}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 HD(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,TO);let[t]=await this.requestWithRetry(e,this.server).catch(e=>{throw SO(`connect error`,e),e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`),this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);let n=t.getAttributeValue(`LIFETIME`);SO(`connect`,this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let t=yO(e),n=t&&this.addrByChannel[t.channelNumber];n&&t&&this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{let n=VD(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?VD(e,r.integrityKey):n;if(!i){SO(`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{SO(`parse error`,e.toString())}}dataReceived(e,t){let n=(e,t)=>{e.length>=4&&_O(e)?this.handleChannelData(e):this.handleSTUNMessage(e,t)};if(EO(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);let{frames:r,rest:i}=xO(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(EO(this.transport)?bO(e):e,t)}async createPermission(e){let t=new HD(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=gO(async(t,n,r)=>{let i=!0;for(r.once(()=>{i=!1});i;){let t=5/6*e*1e3;SO(`refresh delay`,t,{exp:e}),await E(t);let n=new HD(4,0);n.setAttribute(`LIFETIME`,e);try{let[t]=await this.requestWithRetry(n,this.server);e=t.getAttributeValue(`LIFETIME`),SO(`refresh`,{exp:e})}catch(e){SO(`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 QD(t),o=nO(this.integrityKey,r,i),s=new tO(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 YD==0)throw SO(`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)SO(`retry with nonce`,i),this.nonce=a,i===401&&(this.realm=o),this.integrityKey=NO(this.username,this.realm,this.password),e.transactionId=mO(),[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){SO(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);let n=new HD(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,this.server);return}await this.send(vO(n.number,e),this.server)}async getPermission(e){let t=DO(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 SO(`createPermission error`,e),e}finally{this.creatingPermissionByAddr.get(t)===r&&this.creatingPermissionByAddr.delete(t)}}async getChannel(e){let t=OO(e),n=this.channelBindingByAddr.get(t);if(n)return n;let r=this.channelByAddr[t],i=sC(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 SO(`channelBind error`,e),e}finally{this.channelBindingByAddr.get(t)===a&&this.channelBindingByAddr.delete(t)}}async ensureChannel(e){let t=OO(e),n=sC(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=sC(Date.now()/1e3)+this.channelRefreshTime,SO(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 HD(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 jO({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){r??=wO,c??=o?`tls`:`udp`;let l=c===`udp`?await mC.init(`udp4`,{portRange:i,interfaceAddresses:a}):c===`tcp`?await hC.init(e):await gC.init(e,s),u=new AO(e,t,n,r,l);return await u.connectionMade(),u}async function MO({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){return new kO(await jO({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}))}function NO(e,t,n){return fO(e,t,n)}var PO=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()&&VO(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}},FO={host:126,prflx:110,srflx:100,relay:0},IO={host:105,prflx:90,srflx:80,relay:0},LO={active:6,passive:4,so:2},RO={active:4,passive:2,so:6};function zO(e){return e?.toLowerCase()??`udp`}function BO(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function VO(e,t){if(zO(e.transport)!==`tcp`)return!0;let n=BO(e.tcptype),r=BO(t.tcptype);return!n||!r?!1:n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function HO({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(zO(t)!==`tcp`)return r;let i=BO(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?RO[i]:LO[i])+r}function UO(e,t=`udp`){return(zO(t)===`tcp`?IO:FO)[e]??0}function WO(e,t,n){let r=`${e}|${t}|${n}`;return a(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function GO(e,t=65535){let n=typeof t==`number`?`udp`:zO(t.transport),r=typeof t==`number`?t:t.localPreference??HO({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*UO(e,n)+256*r+255}function KO(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var qO=class{cache=new Map;mdnsInstance=(0,jS.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()}},JO=dC(`werift-ice : packages/ice/src/ice.ts : log`),YO=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 tk(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)}},XO=1e3;function ZO(e){return e===void 0||!Number.isFinite(e)||e<=0?XO:Math.max(500,Math.round(e*1e3*2+200))}var QO={iceLite:!1,useTcp:!1,useIpv4:!0,useIpv6:!0};function $O(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw Error(`Unexpected candidate type "${e.type}"`);return e}function ek(e,t){return e.sort((e,n)=>tk(e.localCandidate,e.remoteCandidate,t)-tk(n.localCandidate,n.remoteCandidate,t)).reverse()}function tk(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 nk(e,t){let n=new HD(1,0);try{let[r]=await e.request(n,t),i=e.localCandidate;if(!i)throw Error(`not exist`);return new PO(WO(`srflx`,i.transport,i.host),i.component,i.transport,GO(`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){JO(`error serverReflexiveCandidate`,e)}}function rk(e){return e&&Number.isNaN(e[1])?[e[0],443]:e}function ik(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=>uC(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 ak=dC(`werift-ice : packages/ice/src/utils.ts`);function ok(e){return uC(e.family)===4&&e.address?.startsWith(`169.254.`)||uC(e.family)===6&&e.address?.startsWith(`fe80::`)}function sk(e,{useLinkLocalAddress:t}={}){let n=m.networkInterfaces();return ak(n),ik(n,e,{useLinkLocalAddress:t},ok)}function ck(e,t,n={}){let r=[];return e&&r.push(...sk(4,n)),t&&r.push(...sk(6,n)),r}var lk=dC(`werift-ice : packages/ice/src/ice.ts : log`),uk=class{constructor(e,t){this._iceControlling=e,this.options={...QO,...t},this.iceLite&&(this._iceControlling=!1);let{stunServer:n,turnServer:r}=this.options;this.stunServer=rk(n)??[`stun.l.google.com`,19302],this.turnServer=rk(r),this.restart(),lk(`new Connection`,this.options)}localUsername=pO(4);localPassword=pO(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 hO;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=pO(4),this.localPassword=pO(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 hO,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(){lk(`resetNominatedPair`),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){lk(`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=ck(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}=fk(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 HD(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint(),e.sendStun(s,n).catch(e=>{lk(`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){lk(`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 dO;this.ensureProtocol(t);try{await t.connectionMade(w(e),this.options.portRange,this.options.interfaceAddresses),t.localIp=e,this.protocols.push(t),lk(`protocol`,t.localIp);let n=[e,t.getExtraInfo()[1]];return t.localCandidate=new PO(WO(`host`,`udp`,n[0]),1,`udp`,GO(`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){lk(`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 lO;if(this.ensureProtocol(t),await t.connectionMade(e,this.options.portRange),t.localIp=e,t.localCandidate=new PO(WO(`host`,`tcp`,e),1,`tcp`,GO(`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 cO;this.ensureProtocol(t),await t.connectionMade(e),t.localIp=e,t.localCandidate=new PO(WO(`host`,`tcp`,e),1,`tcp`,GO(`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 nk(n,r).catch(e=>{lk(`error`,e)});t&&this.appendLocalCandidate(t),clearTimeout(a),e(t)}else clearTimeout(a),e()}).catch(e=>{lk(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){let e=(async()=>{let e=this.options.turnTransport??`udp`,t=await MO({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 MO({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 lk(`turn candidateAddress`,n),t.localCandidate=new PO(WO(`relay`,`udp`,n[0]),1,`udp`,GO(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(t.localCandidate),t.localCandidate})().catch(e=>{lk(`query TURN server`,e)});n.push(e)}return n}async connect(){if(lk(`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(),lk(`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(),lk(`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(),lk(`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===dO.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=gO(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`&&(lk(`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=ZO(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&&lk(`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 qO,e.host=await this.lookup.lookup(e.host)}catch{return}try{$O(e)}catch{return}lk(`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{$O(t)}catch{continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){ek(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){lk(`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){lk(`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||=(lk(`ICE completed`),this.checkListState.put(new Promise(e=>e(1))),!0);return}lk(`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||(lk(`ICE failed`),this.checkListState.put(new Promise(e=>{e(2)}))))}checkStart=e=>gO(async t=>{lk(`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++,lk(`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(lk(`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){lk(`retry 401`,e.toJSON()),await this.checkStart(e).awaitable,t();return}lk(`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}=fk(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 PO(pO(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?KO(n.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(i));let s=this.findPair(n,i);if(s||(s=new YO(n,i,this.iceControlling),s.updateState(1),this.addPair(s)),s.noteIncomingRequest(e.transactionIdHex),s.requestsReceived++,s.responsesSent++,s.localCandidate.ufrag=r,lk(`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 YO(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=dk({remoteUsername:t,localUsername:n}),o=new HD(1,0);return o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,GO(`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 HD(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint(),n.sendStun(i,t).catch(e=>{lk(`sendStun error`,e)})}},dk=({remoteUsername:e,localUsername:t})=>`${e}:${t}`,fk=e=>{let[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function pk(e){return e.map((e,t)=>[t,e])}function mk(e,t){let n=e.split(t);return[n[0],n.slice(1).join(t)]}var hk=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)},gk=dC(`werift:packages/webrtc/src/dataChannel.ts`);function _k(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var vk=class extends hk{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()}gk(`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)}},yk=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=!0;protocol=``;negotiated=!1;id;constructor(e={}){Object.assign(this,e)}},bk=()=>({type:`nack`}),xk=()=>({type:`nack`,parameter:`pli`}),Sk=()=>({type:`goog-remb`}),Ck=()=>({type:`transport-cc`}),wk=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}},Tk=class{id;uri;constructor(e){Object.assign(this,e)}},Ek=class{type;parameter;constructor(e={}){Object.assign(this,e)}},Dk=class{ssrc;constructor(e={}){Object.assign(this,e)}},Ok=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}},kk=class{rid;direction;constructor(e){Object.assign(this,e)}},Ak=(e={})=>new wk({mimeType:`video/h264`,clockRate:9e4,rtcpFeedback:[bk(),xk(),Sk()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e}),jk=(e={})=>new wk({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[bk(),xk(),Sk()],...e}),Mk=(e={})=>new wk({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[bk(),xk(),Sk()],...e}),Nk=(e={})=>new wk({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[bk(),xk(),Sk()],...e}),Pk=(e={})=>new wk({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e}),Fk=(e={})=>new wk({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e}),Ik=[Nk(),Mk(),jk(),Ak(),Pk(),Fk()].map(e=>e.mimeType);Ik.filter(e=>e.toLowerCase().startsWith(`video/`)),Ik.filter(e=>e.toLowerCase().startsWith(`audio/`));var Lk=2,Rk=3,zk=0,Bk=50,Vk=51,Hk=53,Uk=56,Wk=57,Gk=`0.0.0.0`,Kk=9,qk={auto:`actpass`,client:`active`,server:`passive`},Jk=Object.keys(qk).reduce((e,t)=>{let n=qk[t];return e[n]=t,e},{}),Yk=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`stereo`,`useinbandfec`],Xk=[`cname`,`msid`,`mslabel`,`label`],Zk={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7},Qk=[`sendonly`,`sendrecv`],$k=[`sendrecv`,`recvonly`],eA=class extends Map{constructor(e){if(super(),e)for(let t of e)this.set(t.id,t)}};function tA(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function nA(e,t,n){return tA(`codec`,e,t,n)}function rA(){return performance.timeOrigin+performance.now()}function iA(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 aA(e,t){let n=new Map;for(let t of e)n.set(t.id,t);if(!t)return new eA([...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(...iA(t)))}return new eA([...r].map(e=>n.get(e)).filter(e=>!!e))}var oA=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`&&Qk.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=rA();return this.collectCodecStats(e)}collectCodecStats(e){let t=[];if(!this.dtlsTransport)return t;let n=tA(`transport`,this.dtlsTransport.id);for(let r of this.codecs){let i={type:`codec`,id:nA(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}},sA=[`inactive`,`sendonly`,`recvonly`,`sendrecv`],cA=class extends hk{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)?aE.deSerialize(e):e;t.header.payloadType=this.codec?.payloadType??t.header.payloadType,this.onReceiveRtp.execute(t)}},lA=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`)}},uA=dC(`werift:packages/webrtc/src/utils.ts`);function dA(e,t){return(e=>e.match(/(.{2})/g).join(`:`))((e=>e.toUpperCase())(a(t).update(e).digest(`hex`)))}var fA={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 pA(e){return fA[e.trim().toLowerCase()]}function mA(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function hA(e){let t=e[0];return t>19&&t<64}var gA=(e,t)=>sA[sA.indexOf(e)&sA.indexOf(t)];function _A(e){return e===`sendonly`?`recvonly`:e===`recvonly`?`sendonly`:e}var vA=Date.now,yA=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,bA=()=>yA+process.hrtime.bigint()/1000n,xA=()=>Date.now()/1e3,SA=()=>{let[e,t]=((A.timeOrigin+A.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return LS([4,4],[e,t]).readBigUInt64BE()},CA=e=>{let[t,n]=zS(LS([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)},wA=e=>{let[,t,n]=zS(LS([8],[e]),[2,2,2,2]);return LS([2,2],[t,n]).readUInt32BE()};function TA(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=DA(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 uA(`iceOptions`,t),t}function EA({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function DA(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=AA(a,kA(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};let c=OA({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c!==`invalid`)return{kind:`turn`,address:s,transport:c}}function OA({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 kA(e){return e===`stuns`||e===`turns`?5349:3478}function AA(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),jA(n.slice(e+1),t)]}let r=n.indexOf(`:`),i=n.lastIndexOf(`:`);return r!==-1&&r===i?[n.slice(0,r),jA(n.slice(r+1),t)]:[n,t]}function jA(e,t){let n=e.startsWith(`:`)?e.slice(1):e,r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}WC.createSelfSignedCertificateWithKey;var MA=(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},NA=dC(`werift:packages/webrtc/src/media/receiver/nack.ts`),PA=150,FA=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){NA(`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===tC(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>tC(this.newEstSeqNum,1)){for(let e=tC(this.newEstSeqNum,1);e<t;e=tC(e,1))this.setLost(e,1);this.newEstSeqNum=t,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>PA&&(this._lost=Object.entries(this._lost).slice(-PA).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 hT({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),r=new CT({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t),this.updateRetryCount(),this.onPacketLost.execute(n)}})},IA=dC(`werift:packages/webrtc/media/receiver/receiverTwcc`),LA=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:bA()},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=tC(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 bT({delta:Number(i)});a.parseDelta(),c.push(a),s!=null&&s.status!==a.type&&(r.push(new vT({packetStatus:s.status,runLength:e-s.minTSN})),s={minTSN:e,status:a.type}),e===n&&(s==null?r.push(new vT({packetStatus:a.type,runLength:1})):r.push(new vT({packetStatus:s.status,runLength:e-s.minTSN+1}))),s??={minTSN:e,status:a.type}}}if(!o)return;let l=new CT({feedback:new _T({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:rC(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([l]).catch(e=>{IA(e)}),this.extensionInfo={},this.fbPktCount=eC(this.fbPktCount,1)}},RA=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||iC(e.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=e.payload.length,this.headerBytesReceived+=e.header.serializeSize,this.lastPacketReceivedTimestamp=rA(),this.base_seq??=e.header.sequenceNumber,n){let n=sC(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}},zA=dC(`werift:packages/webrtc/src/transport/dtls.ts`);function BA(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 VA(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var HA=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 hk;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 GA(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 WC.createSelfSignedCertificateWithKey({signature:vC.ecdsa_3,hash:yC.sha256_4},SC.secp256r1_23);return this.localCertificate=new UA(t,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=KA([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new GA(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 sD({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:XA(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):new QE({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:XA(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`),zA(`dtls failed`,e),t(e)}),this.dtls instanceof QE&&(await E(100),this.dtls.connect().catch(e=>{this.setState(`failed`),zA(`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`),zA(`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=pA(e);if(!n)return[];let r=mA(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=JA(t),r=t.filter(({normalizedAlgorithm:e})=>e===n),i=r.reduce((t,{normalizedAlgorithm:n})=>(t.has(n)||t.set(n,mA(dA(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`);zA(`selected SRTP Profile`,e);let{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(tT(e),nT(e)),a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new NE(a),this.srtcp=new jE(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())&&aT(e)){if(this.bytesReceived+=e.length,this.packetsReceived++,NT(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof lE){zA(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=MT.deSerialize(t)}catch(e){zA(`dropping malformed SRTCP packet`,e);return}for(let e of n)try{this.onRtcp.execute(e)}catch(e){zA(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof lE){zA(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=aE.deSerialize(t)}catch(e){zA(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){zA(`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 zA(`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=rA()){let t=[],n=tA(`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?tA(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?tA(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?tA(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:BA(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:VA(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:tA(`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:tA(`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}},UA=class{constructor(e,t,n){this.certPem=t,this.signatureHash=n;let r=ha.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM(),this.privateKey=ha.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new WA(`sha-256`,dA(ha.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}},WA=class{constructor(e,t){this.algorithm=e,this.value=t}},GA=class{constructor(e=[],t){this.fingerprints=e,this.role=t}},KA=e=>{let t=new Set;return e.filter(({algorithm:e,value:n})=>{let r=`${pA(e)??e.trim().toLowerCase()}:${mA(n)}`;return!t.has(r)&&(t.add(r),!0)})},qA=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`],JA=e=>qA.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm,YA=class{constructor(e){this.ice=e,e.onData.subscribe(e=>{hA(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()}},XA=e=>new YA(e),ZA=dC(`werift:packages/webrtc/src/transport/ice.ts`);function QA(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 $A=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 hk;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=>tj(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>tj(e).toJSON())}getSelectedCandidatePair(){let e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);return e?{local:tj(e.localCandidate).toJSON(),remote:tj(e.remoteCandidate).toJSON()}:null}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){return!this.connection.remoteUsername||!this.connection.remotePassword?null:new aj({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(nj(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?(ZA(`renomination`,e),this.connection.resetNominatedPair(),this.renominating=!1):(ZA(`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=rA(),t=tA(`transport`,this.id)){let n=[];for(let r of this.connection.localCandidates){let i={type:`local-candidate`,id:tA(`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:tA(`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:tA(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:tA(`local-candidate`,i.localCandidate.id),remoteCandidateId:tA(`remote-candidate`,i.remoteCandidate.id),state:QA(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}},ej=class{constructor(e={}){this.options=e,this.connection=new uk(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(tj(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(tj)}get localParameters(){return new aj({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 tj(e){let t=new ij(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 nj(e){return new PO(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 rj=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return tj(PO.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}}},ij=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 rj({candidate:SM(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw Error(`candidate is required`);let t=EM(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{}}},aj=class{iceLite=!1;usernameFragment;password;constructor(e={}){Object.assign(this,e)}},oj=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(Ej(this.body.length))].map(()=>Buffer.from(`\0`))])}},sj=class extends oj{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=Oj(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,Dj(this.params)])}},cj=class e extends sj{static type=1;get type(){return e.type}},lj=class e extends sj{static type=2;get type(){return e.type}},uj=class e extends sj{static type=130;get type(){return e.type}},dj=class e extends oj{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})])}},fj=class e extends oj{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(Ej(e))].map(()=>Buffer.from(`\0`))])),n}},pj=class e extends oj{static type=10;get type(){return e.type}},mj=class e extends oj{static type=11;get type(){return e.type}},hj=class extends oj{constructor(e=0,t=void 0){super(e,t),this.flags=e,t&&(this.params=Oj(t))}params=[];get body(){return Dj(this.params)}},gj=class e extends hj{static type=6;get type(){return e.type}},_j=class e extends hj{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}))}},vj=class e extends hj{static type=4;get type(){return e.type}},yj=class e extends hj{static type=5;get type(){return e.type}},bj=class e extends hj{static type=130;get type(){return e.type}},xj=class e extends oj{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}},Sj=class e extends oj{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}},Cj=class e extends oj{static type=8;get type(){return e.type}},wj=class e extends oj{static type=14;get type(){return e.type}},Tj=[fj,cj,lj,xj,vj,yj,gj,Sj,Cj,_j,pj,mj,wj,bj,dj].reduce((e,t)=>(e[t.type]=t,e),{});function Ej(e){let t=e%4;return t?4-t:0}function Dj(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(Ej(i))].map(()=>Buffer.from(`\0`)))}),t}function Oj(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+Ej(i)}return t}function kj(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)!==$S(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=Tj[t.toString()];if(s)i.push(new s(n,o));else throw Error(`unknown`);a+=r+Ej(r)}return[t,n,r,i]}function Aj(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=$S(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 jj(e){return e.map((e,t)=>[t,e])}function Mj(e){return e.reduce((e,t)=>(e[t]=new $,e),{})}var Nj=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)}},Pj=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)}},Fj={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Ij=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)}},Lj={13:Nj,16:Ij,17:Pj},Rj=dC(`werift/sctp/sctp`),zj=24,Bj=60,Vj=65535,Hj=1200,Uj=1,Wj=2,Gj=4,Kj=10,qj=8,Jj=1/8,Yj=1/4,Xj=3,Zj=1,Qj=60,$j=2**32,eM=200,tM=30,nM=135,rM=7,iM=32776,aM=49152,oM=[`new`,`closed`,`connected`,`connecting`],sM=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=Mj(oM);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=NS();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=Vj;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*Hj;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=Vj;localTsn=Number(NS());lastSackedTsn=uM(this.localTsn);advancedPeerAckTsn=uM(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=Xj;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=tM;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]=kj(e);if(r.filter(e=>e.type===cj.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=>{Rj(`send delayed sack failed`,e.message)})},eM)}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let r=(n-this.lastReceivedTsn)%$j;n===t?e[e.length-1][1]=r:e.push([r,r]),t=dM(n)});let n=new xj(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=>{Rj(`send sack failed`,e.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case fj.type:this.receiveDataChunk(e);break;case cj.type:{if(!this.isServer)return;let t=e;Rj(`receive init`,t),this.lastReceivedTsn=uM(t.initialTsn),this.reconfigResponseSeq=uM(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 lj;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([rM,a]),Rj(`send initAck`,n),await this.sendChunk(n).catch(e=>{Rj(`send initAck failed`,e.message)})}break;case lj.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=uM(t.initialTsn),this.reconfigResponseSeq=uM(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 pj;for(let[e,r]of t.params)if(e===rM){n.body=r;break}await this.sendChunk(n).catch(e=>{Rj(`send echo failed`,e.message)}),this.timer1Start(n),this.setState(3)}break;case xj.type:await this.receiveSackChunk(e);break;case vj.type:{let t=new yj;t.params=e.params,await this.sendChunk(t).catch(e=>{Rj(`send heartbeat ack failed`,e.message)})}break;case gj.type:this.setState(1);break;case Sj.type:{this.timer2Cancel(),this.setState(7);let e=new Cj;await this.sendChunk(e).catch(e=>{Rj(`send shutdown ack failed`,e.message)}),this.t2Start(e),this.setState(6)}break;case _j.type:Rj(`ErrorChunk`,e.descriptions);break;case pj.type:{if(!this.isServer)return;let t=e.body,n=o(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=zj||!t.slice(4).equals(n)){Rj(`x State cookie is invalid`);return}let r=Math.floor(Date.now()/1e3),i=t.readUInt32BE(0);if(i<r-Bj||i>r){let e=new _j(0,void 0);e.params.push([_j.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]),await this.sendChunk(e).catch(e=>{Rj(`send errorChunk failed`,e.message)});return}let a=new mj;await this.sendChunk(a).catch(e=>{Rj(`send cookieAck failed`,e.message)}),this.setState(4)}break;case mj.type:if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4);break;case wj.type:if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1);break;case bj.type:{if(this.associationState!=4)return;let t=e;for(let[e,n]of t.params){let t=Lj[e];t&&await this.receiveReconfigParam(t.parse(n))}}break;case dj.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(let[t,n]of e)t===aM?this.remotePartialReliability=!0:t===iM&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(Rj(`receiveReconfigParam`,Lj[e.type]),e.type){case Nj.type:{let t=e,n=new Ij(t.requestSequence,Fj.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 Ij.type:{let t=e;if(t.result!==Fj.ReconfigResultSuccessPerformed)Rj(`OutgoingSSNResetRequestParam failed`,Object.keys(Fj).find(e=>Fj[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=Xj,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case Pj.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let n=new Ij(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&Uj)===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(aC(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&&oC(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)%$j,t.add(n)});let r=e.cumulativeTsn;for(let e of this.sentQueue){if(aC(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(aC(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,Hj):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=Hj))),a&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Hj),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):oC(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,oC(this.lastReceivedTsn,e.cumulativeTsn))return;let t=e=>aC(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let e of[...this.sackMisOrdered].sort())if(e===dM(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=tC(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-Yj)*this.rttvar+Yj*Math.abs(this.srtt-e),this.srtt=(1-Jj)*this.srtt+Jj*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(Zj,Math.min(this.srtt+4*this.rttvar,Qj))}receive(e,t,n){this.onReceive.execute(e,t,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new cM),this.inboundStreams[e]}markReceived(e){if(oC(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===dM(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;let t=e=>aC(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/Hj),c=0,l=[];for(let u=0;u<s;u++){let d=new fj(0,void 0);d.flags=0,a||(d.flags=Gj),u===0&&(d.flags|=Wj),u===s-1&&(d.flags|=Uj),d.tsn=this.localTsn,d.streamId=e,d.streamSeqNum=o,d.protocol=t,d.userData=n.slice(c,c+Hj),d.bookSize=d.userData.length,d.expiry=r,d.maxRetransmits=i,c+=Hj,this.localTsn=dM(this.localTsn),l.push(d)}for(l.forEach(e=>{this.outboundQueue.push(e)}),a&&(this.outboundStreamSeq[e]=tC(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=>{Rj(`send forwardTsn failed`,e.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit==null?4*Hj:2*Hj,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=>{Rj(`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=>{Rj(`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,nM);this.reconfigQueue=e.slice(nM);let n=new Nj(this.reconfigRequestSeq,this.reconfigResponseSeq,uM(this.localTsn),t);this.reconfigRequestSeq=dM(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Rj(`sendReconfigParam`,e);let t=new bj;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(e=>{Rj(`send reconfig failed`,e.message)})}async sendResetRequest(e){Rj(`sendResetRequest`,e);let t=new fj(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>qj)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Rj(`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>Kj)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Rj(`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*Hj),this.cwnd=Hj,this.transmit())};timer3Cancel(){this.timer3Handle&&=(clearTimeout(this.timer3Handle),void 0)}timerReconfigHandleStart(){this.isStopped||(this.timerReconfigHandle||=(Rj(`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>Kj)Rj(`timerReconfigFailures`,this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Rj(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Rj(`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 vj,t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0),e.params.push([1,t]),await this.sendChunk(e).catch(e=>{Rj(`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(){aC(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&Gj||(t[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new dj(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&Uj)break}for(let e=t;e<this.sentQueue.length;e++){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&Uj)break}return!0}static getCapabilities(){return new lM(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 cj;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Rj(`send init`,e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(e){Rj(`send init failed`,e.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([aM,Buffer.from(``)]),t.push(dj.type)),t.push(uj.type),e.push([iM,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw Error(`invalid remote port`);let t=Aj(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,Rj(`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 gj;await this.sendChunk(e).catch(e=>{Rj(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},cM=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||aC(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(let[t,n]of jj(this.reassembly)){if(n.tsn===e.tsn)throw Error(`duplicate chunk in reassembly`);if(aC(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&Gj),!(i.flags&Wj)){if(r)break;e++;continue}if(r&&iC(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&Uj){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=tC(this.streamSequenceNumber,1)),e=t,yield[i.streamId,i.protocol,a]}else e++;n=dM(n)}}pruneChunks(e){let t=-1,n=0;for(let[r,i]of this.reassembly.entries())if(oC(e,i.tsn))t=r,n+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(t+1),n}},lM=class{constructor(e){this.maxMessageSize=e}};function uM(e){return(e-1)%$j}function dM(e){return(e+1)%$j}var fM=dC(`werift:packages/webrtc/src/transport/sctp.ts`),pM=65536,mM=class e{constructor(e=5e3,t=pM){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new $;id=l().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=pM;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 sM(new gM(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===Bk&&n.length>0)switch(fM(`DCEP`,e,t,n),n[0]){case Rk:{if(n.length<12){fM(`DATA_CHANNEL_OPEN data.length not enough`);return}if(Object.keys(this.dataChannels).includes(e.toString()))fM(`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`);fM(`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 yk({label:s,ordered:!(t&128),maxPacketLifeTime:u,maxRetransmits:l,protocol:c,id:e}),f=new vk(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(Lk,0),this.dataChannelQueue.push([t,Bk,r]),await this.dataChannelFlush()}break;case Lk:{fM(`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 Vk:return n.toString(`utf8`);case Uk:return``;case Hk:return n;case Wk: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=zk,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(Rk,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,Bk,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===Bk)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=_k(t);return this.assertSendableMessageSize(r),e.addBufferedAmount(r),this.dataChannelQueue.push(typeof t==`string`?[e,Vk,n]:[e,Hk,n]),this.sctp.associationState!==4&&fM(`sctp not established`,this.sctp.associationState),this.dataChannelFlush(),r};getCapabilities(){return e.getCapabilities(this.maxMessageSize)}static getCapabilities(e=pM){return new hM(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`)))}},hM=class{constructor(e){this.maxMessageSize=e}},gM=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>this.dtls.sendData(e);close(){}},_M=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]=CM(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=bM(e.slice(2));else if(e.startsWith(`t=`))i.time=e.slice(2);else if(e.startsWith(`a=`)){let[t,n]=wM(e);switch(t){case`fingerprint`:{let[e,t]=n?.split(` `)||[];i.dtlsFingerprints.push(new WA(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`:TM(i.group,n);break;case`msid-semantic`:TM(i.msidSemantic,n);break;case`setup`:i.dtlsRole=Jk[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 vM(n,Number.parseInt(t[2]),t[3],o||r);if(s.dtlsParams=new GA([...i.dtlsFingerprints],i.dtlsRole),s.iceParams=new aj({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=bM(e.slice(2));else if(e.startsWith(`a=`)){let[t,n]=wM(e);switch(t){case`candidate`:if(!n)throw Error();s.iceCandidates.push(EM(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 Tk({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw Error();let[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new WA(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 hM(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{let[e,t]=mk(n,` `);s.rtcpPort=Number.parseInt(e),s.rtcpHost=bM(t)}break;case`rtcp-mux`:s.rtcpMux=!0;break;case`setup`:s.dtlsParams.role=Jk[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{let[e,t]=mk(n,` `),[r,i,a]=t.split(`/`),o;s.kind===`audio`&&(o=a?Number.parseInt(a):1);let c=new wk({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]=mk(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]=mk(n,` `),r=Number.parseInt(e),[i,a]=mk(t,`:`),o=s.ssrc.find(e=>e.ssrc===r);o||(o=new AM({ssrc:r}),s.ssrc.push(o)),Xk.includes(i)&&(o[i]=a)}break;case`ssrc-group`:TM(s.ssrcGroup,n);break;case`rid`:{let[e,t]=mk(n,` `);s.simulcastParameters.push(new kk({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]=wM(e);if(t===`fmtp`){let[e,t]=mk(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 Ek({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=${xM(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(t=>e.push(`a=group:${t.str}`)),this.extMapAllowMixed&&e.push(`a=extmap-allow-mixed`),this.msidSemantic.forEach(t=>e.push(`a=msid-semantic:${t.str}`));let t=this.media.map(e=>e.toString()).join(``);return e.join(`\r
|
|
140
140
|
`)+`\r
|
|
141
|
-
`+t}toJSON(){let e=this.string;return(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)&&(this.cachedJson=new
|
|
141
|
+
`+t}toJSON(){let e=this.string;return(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)&&(this.cachedJson=new DM(e,this.type)),this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},vM=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=${xM(this.host)}`),this.iceCandidates.forEach(t=>{e.push(`a=candidate:${SM(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:${qk[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} ${xM(this.rtcpHost)}`),this.rtcpMux&&e.push(`a=rtcp-mux`)),this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)}),this.ssrc.forEach(t=>{Xk.forEach(n=>{let r=t[n];r!==void 0&&e.push(`a=ssrc:${t.ssrc} ${n}:${r}`)})}),this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`),t.rtcpFeedback.forEach(n=>{let r=n.type;n.parameter&&(r+=` ${n.parameter}`),e.push(`a=rtcp-fb:${t.payloadType} ${r}`)}),t.parameters&&e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}),Object.keys(this.sctpMap).forEach(t=>{let n=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${n}`)}),this.sctpPort&&e.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(t=>{e.push(`a=rid:${t.rid} ${t.direction}`)});let t=`a=simulcast:`,n=this.simulcastParameters.filter(e=>e.direction===`recv`);n.length&&(t+=`recv ${n.map(e=>e.rid).join(`;`)} `);let r=this.simulcastParameters.filter(e=>e.direction===`send`);r.length&&(t+=`send ${r.map(e=>e.rid).join(`;`)}`),e.push(t)}return e.join(`\r
|
|
142
142
|
`)+`\r
|
|
143
|
-
`}},
|
|
143
|
+
`}},yM=class{constructor(e,t){this.semantic=e,this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function bM(e){let t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw Error(`exception`);return t[2]}function xM(e){return`IN IP${w(e)?4:6} ${e}`}function SM(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 CM(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 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};
|
|
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 wM(e){if(e.includes(`:`)){let t=mk(e.slice(2),`:`);return[t[0],t[1]]}return[e.slice(2),void 0]}function TM(e,t,n=e=>e.toString()){let r=t.split(` `);r.length>0&&e.push(new yM(r[0],r.slice(1).map(n)))}function EM(e){return tj(PO.fromSdp(e))}var DM=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 OM(e,t){t.origin=`- ${c(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`,t.msidSemantic.push(new yM(`WMS`,[`*`])),t.type=e}function kM(e){let t={};return e.split(`;`).forEach(e=>{if(e.includes(`=`)){let[n,r]=mk(e,`=`);Yk.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 AM=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}},jM=dC(`werift:packages/webrtc/src/media/rtpReceiver.ts`),MM=class{constructor(e,t,n){this.config=e,this.kind=t,this.rtcpSsrc=n,this.defaultTrack=new cA({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 FA(this);audioRedHandler=new ZT;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===Ck().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===xk().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 LA(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=xA()-this.receiveLastSRTimestamp[e];t>0&&t<65536&&(r=sC(t*65536))}return new pT({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})}),t=new fT({ssrc:this.rtcpSsrc,reports:e});try{this.config.debug.receiverReportDelay&&await E(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([t])}catch(e){jM(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}getInboundRtpStatsId(e){return tA(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return tA(`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?tA(`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?nA(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=rA(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),aA(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){jM(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;jM(`sendRtcpPLI`,{mediaSsrc:e});let t=new dT({feedback:new cT({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1,await this.dtlsTransport.sendRtcp([t])}catch(e){jM(e)}}handleRtcpPacket(e){switch(e.type){case OT.type:{let t=e;this.lastSRtimestamp[t.ssrc]=wA(t.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[t.ssrc]=xA(),this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1,this.remoteTimestampsBySsrc[t.ssrc]=CA(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 RA(r.clockRate),this.remoteStreams[e.header.ssrc].add(e),this.receiverTWCC){let e=t[PT.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=kM(r.parameters??``),a=this.codecs[i.apt];if(e.payload.length<2)return;e=oE(e,a.payloadType,t),n=this.trackBySSRC[t]}let i;if(!(r.name.toLowerCase()===`red`&&(i=qT.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()}}},NM=dC(`werift:packages/webrtc/src/media/router.ts`),PM=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){NM(`registerRtpReceiver`,t),this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){NM(`registerRtpReceiverBySsrc`,t),t.encodings.filter(e=>e.ssrc!=null).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc),e.addTrack(new cA({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;NM(`registerRtpReceiverByRid`,t),e.addTrack(new cA({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:!0,codec:r})),this.ridTable[t.rid]=e.receiver}routeRtp=e=>{let t=FT(e.header.extensions,this.extIdUriMap),n=this.ssrcTable[e.header.ssrc],r=t[PT.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 MM).find(t=>t.trackBySSRC[e.header.ssrc]),n&&(NM(`simulcast register receiver by ssrc`,e.header.ssrc),this.registerRtpReceiver(n,e.header.ssrc),n.handleRtpBySsrc(e,t))),!n){NM(`ssrcReceiver not found`);return}let i=t[PT.sdesMid];typeof i==`string`&&(n.sdesMid=i);let a=t[PT.repairedRtpStreamId];typeof a==`string`&&(n.latestRepairedRid=a)};routeRtcp=e=>{let t=[];switch(e.type){case OT.type:e=e,t.push(this.ssrcTable[e.ssrc]);break;case fT.type:e=e,e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case wT.type:break;case CT.type:{let n=e;n.feedback&&t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case dT.type:{let n=e;switch(n.feedback.count){case lT.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))}},FM=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 iT(this.totalSize/e*8*1e3)}get sendBitrate(){let e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return iT(this.totalSize/e*8*1e3)}},IM=20,LM=10,RM=class{congestion=!1;onAvailableBitrate=new $;onCongestion=new $;onCongestionScore=new $;congestionCounter=0;cumulativeResult=new FM;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=vA()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<IM?this.congestionCounter++:this.congestionScore<LM&&this.congestionScore++,this.congestionCounter>=IM&&!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>-IM){let e=iT(IM/2)+1,t=e-(e-(iT(IM/4)+1))/10*this.congestionScore;this.congestionCounter-=t}this.congestionCounter<=-IM&&(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}},zM=dC(`werift:packages/webrtc/src/media/rtpSender.ts`),BM=128,VM=.85,HM=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 RM;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=MS();redRedundantPayloadType;_redDistance=2;redEncoder=new YT(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=kM(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),zM(`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 OT({ssrc:this.ssrc,senderInfo:new kT({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=wA(this.ntpTimestamp),this.lastSentSRTimestamp=xA(),this.cname&&e.push(new wT({chunks:[new TT({source:this.ssrc,items:[new ET({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){zM(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:e,timestamp:t},n=!1){this.sequenceNumber!=null&&(this.seqOffset=tC(this.sequenceNumber,-e),n&&(this.seqOffset=tC(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=nC(this.timestamp,-t),n&&(this.timestampOffset=tC(this.timestampOffset,1))),this.rtpCache=[],zM(`replaceRTP`,this.sequenceNumber,e,this.seqOffset)}async sendRtp(e){if(this.dtlsTransport.state!==`connected`||!this.codec)return;e=Buffer.isBuffer(e)?aE.deSerialize(e):e;let{header:t,payload:n}=e;t.ssrc=this.ssrc,t.payloadType=this.codec.payloadType,t.timestamp=nC(t.timestamp,this.timestampOffset),t.sequenceNumber=tC(t.sequenceNumber,this.seqOffset),this.timestamp=t.timestamp,this.sequenceNumber=t.sequenceNumber;let r=SA(),i=[...t.extensions];t.extensions=this.headerExtensions.map(e=>{let t=(()=>{switch(e.uri){case PT.sdesMid:return this.mid?IT(this.mid):void 0;case PT.sdesRTPStreamID:return this.rtpStreamId?LT(this.rtpStreamId):void 0;case PT.repairedRtpStreamId:return this.repairedRtpStreamId?RT(this.repairedRtpStreamId):void 0;case PT.transportWideCC:return this.dtlsTransport.transportSequenceNumber=tC(this.dtlsTransport.transportSequenceNumber,1),zT(this.dtlsTransport.transportSequenceNumber);case PT.absSendTime:return BT(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=nC(this.packetCount,1),this.rtpCache[t.sequenceNumber%BM]=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=vA(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:s,sentAtMs:s};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(e){switch(e.type){case OT.type:case fT.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=xA()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t,this.roundTripTimeMeasurements++,this.rtt=this.rtt===void 0?t:VM*this.rtt+(1-VM)*t}});break;case CT.type:{let t=e;switch(t.feedback.count){case _T.count:{let e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case hT.count:{let e=t.feedback;this.nackCount++,e.lost.forEach(async e=>{let t=this.rtpCache[e%BM];t&&t.header.sequenceNumber!==e&&(t=void 0),t&&(this.rtxPayloadType!=null&&(t=sE(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=tC(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 dT.type:{let t=e;switch(t.feedback.count){case lT.count:{let e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case cT.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 tA(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return tA(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return tA(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){let t=[],n=this.dtlsTransport?tA(`transport`,this.dtlsTransport.id):void 0,r=this.codec&&n?nA(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=rA(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),aA(t,this.getStatsRootIds())}};function UM(e,t=e){return new DOMException(t,e)}function WM(e){return TypeError(e)}var GM=dC(`werift:packages/webrtc/src/transport/sctpManager.ts`),KM=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new $;constructor(){}createSctpTransport(e){let t=new mM(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=qM(t.maxPacketLifeTime,`maxPacketLifeTime`),r=qM(t.maxRetransmits,`maxRetransmits`),i={protocol:``,ordered:!0,negotiated:!1,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw WM(`maxPacketLifeTime and maxRetransmits cannot both be set`);this.sctpTransport||=this.createSctpTransport();let a=new yk({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol}),o=new vk(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(),GM(`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=rA()){let t=[];for(let n of this.dataChannels){let r={type:`data-channel`,id:tA(`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 qM(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw WM(`${t} must be an unsigned short`);return n}var JM=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 vM(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 AM({ssrc:e.sender.ssrc,cname:this.cname})],e.options.simulcast&&(n.simulcastParameters=e.options.simulcast.map(e=>new kk(e))),n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)&&(n.ssrc.push(new AM({ssrc:e.sender.rtxSsrc,cname:this.cname})),n.ssrcGroup=[new yM(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]),this.addTransportDescription(n,e.dtlsTransport),n}createMediaDescriptionForSctp(e){let t=new vM(`application`,Kk,`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=Gk,e.port=Kk,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=_M.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 UM(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-remote-offer`,`have-local-pranswer`].includes(n))throw UM(`InvalidStateError`,`Cannot handle answer in signaling state`)}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw UM(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-local-offer`,`have-remote-pranswer`].includes(n))throw UM(`InvalidStateError`,`Cannot handle answer in signaling state`)}buildOfferSdp(e,t){let n=new _M;OM(`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 yM(`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 _M;OM(`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,gA(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 yM(`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 UM(`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 UM(`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)}},YM=dC(`werift:packages/webrtc/src/transport/secureTransportManager.ts`),XM=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 UA(e.keyPem,e.certPem,e.signatureHash)}createTransport(){let e=this.iceTransports.find(e=>e.state!==`closed`),t=TA(this.config.iceServers),n=EA({parsedTurnTransport:t.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP}),r=new ej({...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 $A(r);return i.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new HA(this.config,i,this.certificate,ZM)}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=ij.fromJSON(t);if(!c)throw UM(`OperationError`,`Failed to parse ICE candidate`);let l=s[0],u=e.media[l];if(!u)throw UM(`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 UM(`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 UM(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r==`number`){if(r<0||r>=e.media.length)throw UM(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw WM(`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 UM(`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&&(YM(`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?YM(`skipping ICE gathering for bundled connection`):await Promise.allSettled(this.iceTransports.map(e=>e.gather())).catch(e=>{YM(`gatherCandidates failed`,e)})}setConnectionState(e){this.connectionState!==e&&(YM(`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 HA.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()}},ZM=[Zk.SRTP_AEAD_AES_128_GCM,Zk.SRTP_AES128_CM_HMAC_SHA1_80],QM=dC(`werift:packages/webrtc/src/peerConnection.ts`),$M=class extends hk{id=l().toString();cname=l().toString();config=tN();signalingState=`stable`;negotiationneeded=!1;needRestart=!1;router=new PM;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 JM({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new cN(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 oN({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 KM,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 XM({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=nN(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&&!iN(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(MA(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 pk([...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 aN(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 UM(`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){QM(`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){QM(`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 UM(`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 pk(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=gA(e.direction,e.offerDirection);e.setCurrentDirection(t)}return this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(e=>{QM(`gatherCandidates failed`,e)}),a.type===`answer`&&this.connect().catch(e=>{QM(`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 UM(`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(){QM(`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 QM(`iceTransport.start failed`,e),e}),e.state!==`connected`&&(await e.start().catch(e=>{throw QM(`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 _M&&(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`&&(QM(`caller start connect`),this.connect().catch(e=>{QM(`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 UM(`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 UM(`InvalidStateError`,`RTCPeerConnection is closed`)}setSignalingState(e){this.signalingState!==e&&(QM(`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:tA(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){let t=rA(),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?aA(n,this.transceiverManager.getStatsRootIds(e)):aA(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(),QM(`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()}},eN=(e,t)=>e.find(e=>e.mimeType.toLowerCase()===t.mimeType.toLowerCase())?t:void 0;function tN(){return{codecs:{audio:[Pk(),Fk()],video:[jk()]},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:pM}}tN();function nN(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 WM(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}return`iceCandidatePoolSize`in t&&(n.iceCandidatePoolSize=rN(t.iceCandidatePoolSize,`iceCandidatePoolSize`)),n}function rN(e,t){let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw WM(`${t} must be an unsigned short`);return n}function iN(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function aN(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 oN=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}},sN=dC(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`),cN=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 HM(e),o=new oA(r,t,new MM(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 UM(`InvalidAccessError`,`Track already added`);let n=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&Qk.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&&Qk.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 UM(`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!!$k.includes(e.direction);case`sendonly`:return!!Qk.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[kM(n.parameters??``).apt];return r&&e.ssrc.length===2&&(r.rtx=new Dk({ssrc:e.ssrc[1].ssrc})),t}return t[n.payloadType]=new Ok({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=eN(n,e);if(!r)return!1;if(r?.name.toLowerCase()===`rtx`){let e=kM(r.parameters??``).apt,i=t.rtp.codecs.find(t=>t.payloadType===e);return i?!!eN(n,i):!1}return!0}),sN(`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=_A(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 lA({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 lN(e){let t={get label(){return e.label},get readyState(){return e.readyState},get ordered(){return e.ordered},get maxRetransmits(){return e.maxRetransmits},get maxPacketLifeTime(){return e.maxPacketLifeTime},get bufferedAmount(){return e.bufferedAmount},onopen:null,onclose:null,onmessage:null,send(t){e.send(typeof t==`string`?t:Buffer.from(t))},close(){e.close()}};return e.onopen=()=>t.onopen?.(),e.onclose=()=>t.onclose?.(),e.onmessage=({data:e})=>t.onmessage?.({data:typeof e==`string`?e:Uint8Array.from(e).buffer}),t}function uN(e,t){let n={get connectionState(){return e.connectionState},get iceConnectionState(){return e.iceConnectionState},get signalingState(){return e.signalingState},get localDescription(){return e.localDescription},get remoteDescription(){return e.remoteDescription},onicecandidate:null,ondatachannel:null,onconnectionstatechange:null,oniceconnectionstatechange:null,createDataChannel:(t,n)=>lN(e.createDataChannel(t,n)),createOffer:t=>e.createOffer(t),createAnswer:()=>e.createAnswer(),setLocalDescription:t=>e.setLocalDescription(t),setRemoteDescription:t=>e.setRemoteDescription(t),addIceCandidate:t=>e.addIceCandidate(t),getStats:()=>e.getStats(),close:t};return e.onicecandidate=({candidate:e})=>n.onicecandidate?.({candidate:e??null}),e.ondatachannel=({channel:e})=>n.ondatachannel?.({channel:lN(e)}),e.onconnectionstatechange=()=>n.onconnectionstatechange?.(),e.oniceconnectionstatechange=()=>n.oniceconnectionstatechange?.(),n}function dN(){let e=new Set,t=new WeakMap,n=!1,r=!1,i;function a(n){let a=t.get(n);if(a)return a;let o=n.close();return t.set(n,o),o.then(()=>e.delete(n),t=>{r||(i=t),r=!0,e.delete(n)}),o}return{createPeerConnection(t){if(n)throw Error(`Native room transport is closed`);let r=new $M({iceServers:t.iceServers?.map(e=>({urls:e.urls})),bundlePolicy:t.bundlePolicy});return e.add(r),uN(r,()=>a(r))},async close(){if(n=!0,await Promise.allSettled([...e].map(a)),r)throw i}}}function fN(e){let t=Nr(e),n=new URL(t);if(n.protocol===`http:`&&![`localhost`,`127.0.0.1`,`[::1]`].includes(n.hostname))throw TypeError(`Native API keys require HTTPS except for loopback services.`);return t}async function pN(e,n={},r=new URL(`.`,import.meta.url)){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);let{serviceOrigin:i,apiKey:a,...o}=e;if(typeof a!=`string`||!/^b2d_[0-9a-f]{64}$/.test(a))throw TypeError(`A valid API key is required.`);n.signal?.throwIfAborted();let s=fN(i??`https://ball2d.com`),c=Hi(o),l=dN(),u=crypto.randomUUID(),d,f,p,m,h=new Promise((e,t)=>{p=e,m=t});h.catch(()=>{});try{let e=await Vi.create(c,{network:{serviceOrigin:s,createWebSocket:e=>new WebSocket(e),createPeerConnection:l.createPeerConnection},request:async(e,t)=>{let n=new URL(e);if(n.origin===s&&n.pathname===re.rooms&&t?.method===`POST`){let e=new Headers(t.headers);e.set(`Authorization`,`Bearer ${a}`),e.set(`Idempotency-Key`,u);let n=performance.now(),r=await fetch(new URL(re.sdkRooms,s),{...t,headers:e,redirect:`error`});if(r.status===401)throw await r.body?.cancel(),new ft(`API key is invalid, expired or revoked. Create a key from your Ball2D account.`,401);if(r.ok){let e=await r.clone().json();d=new Be(s,a,e.id,e.lease,n)}return r}return fetch(e,t)},loadEngine:async e=>_n.create(await t(new URL(`core.wasm`,r),{signal:e})),loadStadium:Kr(async e=>new Response(await t(new URL(`.${e}`,r),`utf8`)))},n.signal);if(f=e,n.signal?.throwIfAborted(),!d)throw Error(`Missing room authorization`);let i=()=>{queueMicrotask(()=>{Promise.allSettled([l.close(),d?.stop()]).then(e=>{let t=e.find(e=>e.status===`rejected`);t?.status===`rejected`?m(t.reason):p()})})};return e.signal.addEventListener(`abort`,i,{once:!0}),e.signal.aborted&&i(),{host:e,closed:h,leaseId:d.leaseId}}catch(e){let t=(await Promise.allSettled([()=>f?.close(),()=>d?.stop(),()=>l.close()].map(e=>Promise.resolve().then(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw t.length?AggregateError([e,...t],`Room creation and cleanup failed`,{cause:e}):e}}var mN=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)}},hN=[`sendChat`,`sendAnnouncement`,`setPlayerAdmin`,`setPlayerMuted`,`setPlayerTeam`,`kickPlayer`,`clearBan`,`clearBans`,`setScoreLimit`,`setTimeLimit`,`setCustomStadium`,`setDefaultStadium`,`setTeamsLock`,`setTeamColors`,`startGame`,`stopGame`,`pauseGame`,`setPassword`,`setRequireVerification`,`reorderPlayers`,`setKickRateLimit`,`setPlayerAvatar`,`setDiscProperties`,`setPlayerDiscProperties`];function gN(e,t){let n=Object.create(null);t&&Object.defineProperty(n,"closed",{enumerable:!0,value:t});let r=new mN(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 hN)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.onPlayerDirectChat.onPlayerTeamChange.onPlayerAdminChange.onPlayerMuteChange.onPlayerKicked.onPlayerActivity.onPlayerInput.onPlayerBallKick.onTeamGoal.onTeamVictory.onGameVictory.onGameStart.onGameStop.onGameTick.onGamePause.onGameUnpause.onGamePauseChange.onPositionsReset.onStadiumChange.onTeamsLockChange.onKickRateLimitSet.onRecordingComplete.onError`.split(`.`)){let r;Object.defineProperty(n,t,{enumerable:!0,get:()=>r,set:i=>{if(i!=null&&typeof i!=`function`)throw Error(`Callback must be a function`);r=i,Reflect.set(e,t,i==null?void 0:(...e)=>Reflect.apply(i,n,e))}})}return Object.defineProperty(n,"close",{enumerable:!0,value:()=>{r.close(),e.close()}}),Object.preventExtensions(n)}function _N(e){return ui(e)}function vN(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 yN(e,t={}){let{host:n,closed:r}=await pN(e,t);return gN(n,r)}export{ft as RoomAdmissionError,yN as createRoom,_N as readReplay,vN as validateStadium};
|