@urun-sh/openai 0.2.51 → 0.2.53

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.
@@ -0,0 +1,304 @@
1
+ "use strict";var dF=Object.create;var Rm=Object.defineProperty;var lF=Object.getOwnPropertyDescriptor;var uF=Object.getOwnPropertyNames;var fF=Object.getPrototypeOf,hF=Object.prototype.hasOwnProperty;var z=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}};var Ne=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},ic=(t,e)=>{for(var r in e)Rm(t,r,{get:e[r],enumerable:!0})},WA=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of uF(e))!hF.call(t,n)&&n!==r&&Rm(t,n,{get:()=>e[n],enumerable:!(s=lF(e,n))||s.enumerable});return t};var Fe=(t,e,r)=>(r=t!=null?dF(fF(t)):{},WA(e||!t||!t.__esModule?Rm(r,"default",{value:t,enumerable:!0}):r,t)),GA=t=>WA(Rm({},"__esModule",{value:!0}),t);var pF,N,g=z(()=>{"use strict";pF=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,N=pF()});var Y1=Ne(()=>{"use strict";g();var XA;(function(t){(function(e){var r=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),s=n(t);typeof r.Reflect<"u"&&(s=n(r.Reflect,s)),e(s,r),typeof r.Reflect>"u"&&(r.Reflect=t);function n(c,d){return function(u,l){Object.defineProperty(c,u,{configurable:!0,writable:!0,value:l}),d&&d(u,l)}}function i(){try{return Function("return this;")()}catch{}}function o(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||o()}})(function(e,r){var s=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",o=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,d=!a&&!c,u={create:a?function(){return nc(Object.create(null))}:c?function(){return nc({__proto__:null})}:function(){return nc({})},has:d?function(J,te){return s.call(J,te)}:function(J,te){return te in J},get:d?function(J,te){return s.call(J,te)?J[te]:void 0}:function(J,te){return J[te]}},l=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:_f(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:km(),m=typeof WeakMap=="function"?WeakMap:G1(),v=n?Symbol.for("@reflect-metadata:registry"):void 0,p=Jd(),x=vf(p);function w(J,te,oe,ye){if(q(oe)){if(!Ms(J))throw new TypeError;if(!tc(te))throw new TypeError;return Y(J,te)}else{if(!Ms(J))throw new TypeError;if(!ve(te))throw new TypeError;if(!ve(ye)&&!q(ye)&&!Q(ye))throw new TypeError;return Q(ye)&&(ye=void 0),oe=Ot(oe),H(J,te,oe,ye)}}e("decorate",w);function E(J,te){function oe(ye,$e){if(!ve(ye))throw new TypeError;if(!q($e)&&!W1($e))throw new TypeError;se(J,te,ye,$e)}return oe}e("metadata",E);function P(J,te,oe,ye){if(!ve(oe))throw new TypeError;return q(ye)||(ye=Ot(ye)),se(J,te,oe,ye)}e("defineMetadata",P);function j(J,te,oe){if(!ve(te))throw new TypeError;return q(oe)||(oe=Ot(oe)),F(J,te,oe)}e("hasMetadata",j);function T(J,te,oe){if(!ve(te))throw new TypeError;return q(oe)||(oe=Ot(oe)),K(J,te,oe)}e("hasOwnMetadata",T);function k(J,te,oe){if(!ve(te))throw new TypeError;return q(oe)||(oe=Ot(oe)),I(J,te,oe)}e("getMetadata",k);function _(J,te,oe){if(!ve(te))throw new TypeError;return q(oe)||(oe=Ot(oe)),G(J,te,oe)}e("getOwnMetadata",_);function A(J,te){if(!ve(J))throw new TypeError;return q(te)||(te=Ot(te)),D(J,te)}e("getMetadataKeys",A);function M(J,te){if(!ve(J))throw new TypeError;return q(te)||(te=Ot(te)),O(J,te)}e("getOwnMetadataKeys",M);function V(J,te,oe){if(!ve(te))throw new TypeError;if(q(oe)||(oe=Ot(oe)),!ve(te))throw new TypeError;q(oe)||(oe=Ot(oe));var ye=Ri(te,oe,!1);return q(ye)?!1:ye.OrdinaryDeleteMetadata(J,te,oe)}e("deleteMetadata",V);function Y(J,te){for(var oe=J.length-1;oe>=0;--oe){var ye=J[oe],$e=ye(te);if(!q($e)&&!Q($e)){if(!tc($e))throw new TypeError;te=$e}}return te}function H(J,te,oe,ye){for(var $e=J.length-1;$e>=0;--$e){var Ht=J[$e],Kt=Ht(te,oe,ye);if(!q(Kt)&&!Q(Kt)){if(!ve(Kt))throw new TypeError;ye=Kt}}return ye}function F(J,te,oe){var ye=K(J,te,oe);if(ye)return!0;var $e=sc(te);return Q($e)?!1:F(J,$e,oe)}function K(J,te,oe){var ye=Ri(te,oe,!1);return q(ye)?!1:Dt(ye.OrdinaryHasOwnMetadata(J,te,oe))}function I(J,te,oe){var ye=K(J,te,oe);if(ye)return G(J,te,oe);var $e=sc(te);if(!Q($e))return I(J,$e,oe)}function G(J,te,oe){var ye=Ri(te,oe,!1);if(!q(ye))return ye.OrdinaryGetOwnMetadata(J,te,oe)}function se(J,te,oe,ye){var $e=Ri(oe,ye,!0);$e.OrdinaryDefineOwnMetadata(J,te,oe,ye)}function D(J,te){var oe=O(J,te),ye=sc(J);if(ye===null)return oe;var $e=D(ye,te);if($e.length<=0)return oe;if(oe.length<=0)return $e;for(var Ht=new h,Kt=[],lt=0,Se=oe;lt<Se.length;lt++){var Re=Se[lt],Oe=Ht.has(Re);Oe||(Ht.add(Re),Kt.push(Re))}for(var Me=0,rt=$e;Me<rt.length;Me++){var Re=rt[Me],Oe=Ht.has(Re);Oe||(Ht.add(Re),Kt.push(Re))}return Kt}function O(J,te){var oe=Ri(J,te,!1);return oe?oe.OrdinaryOwnMetadataKeys(J,te):[]}function W(J){if(J===null)return 1;switch(typeof J){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return J===null?1:6;default:return 6}}function q(J){return J===void 0}function Q(J){return J===null}function pe(J){return typeof J=="symbol"}function ve(J){return typeof J=="object"?J!==null:typeof J=="function"}function at(J,te){switch(W(J)){case 0:return J;case 1:return J;case 2:return J;case 3:return J;case 4:return J;case 5:return J}var oe=te===3?"string":te===5?"number":"default",ye=yf(J,i);if(ye!==void 0){var $e=ye.call(J,oe);if(ve($e))throw new TypeError;return $e}return yt(J,oe==="default"?"number":oe)}function yt(J,te){if(te==="string"){var oe=J.toString;if(js(oe)){var ye=oe.call(J);if(!ve(ye))return ye}var $e=J.valueOf;if(js($e)){var ye=$e.call(J);if(!ve(ye))return ye}}else{var $e=J.valueOf;if(js($e)){var ye=$e.call(J);if(!ve(ye))return ye}var Ht=J.toString;if(js(Ht)){var ye=Ht.call(J);if(!ve(ye))return ye}}throw new TypeError}function Dt(J){return!!J}function vt(J){return""+J}function Ot(J){var te=at(J,3);return pe(te)?te:vt(te)}function Ms(J){return Array.isArray?Array.isArray(J):J instanceof Object?J instanceof Array:Object.prototype.toString.call(J)==="[object Array]"}function js(J){return typeof J=="function"}function tc(J){return typeof J=="function"}function W1(J){switch(W(J)){case 3:return!0;case 4:return!0;default:return!1}}function gf(J,te){return J===te||J!==J&&te!==te}function yf(J,te){var oe=J[te];if(oe!=null){if(!js(oe))throw new TypeError;return oe}}function xf(J){var te=yf(J,o);if(!js(te))throw new TypeError;var oe=te.call(J);if(!ve(oe))throw new TypeError;return oe}function Fn(J){return J.value}function rc(J){var te=J.next();return te.done?!1:te}function bf(J){var te=J.return;te&&te.call(J)}function sc(J){var te=Object.getPrototypeOf(J);if(typeof J!="function"||J===l||te!==l)return te;var oe=J.prototype,ye=oe&&Object.getPrototypeOf(oe);if(ye==null||ye===Object.prototype)return te;var $e=ye.constructor;return typeof $e!="function"||$e===J?te:$e}function wf(){var J;!q(v)&&typeof r.Reflect<"u"&&!(v in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(J=Qd(r.Reflect));var te,oe,ye,$e=new m,Ht={registerProvider:Kt,getProvider:Se,setProvider:Oe};return Ht;function Kt(Me){if(!Object.isExtensible(Ht))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case J===Me:break;case q(te):te=Me;break;case te===Me:break;case q(oe):oe=Me;break;case oe===Me:break;default:ye===void 0&&(ye=new h),ye.add(Me);break}}function lt(Me,rt){if(!q(te)){if(te.isProviderFor(Me,rt))return te;if(!q(oe)){if(oe.isProviderFor(Me,rt))return te;if(!q(ye))for(var It=xf(ye);;){var Mt=rc(It);if(!Mt)return;var es=Fn(Mt);if(es.isProviderFor(Me,rt))return bf(It),es}}}if(!q(J)&&J.isProviderFor(Me,rt))return J}function Se(Me,rt){var It=$e.get(Me),Mt;return q(It)||(Mt=It.get(rt)),q(Mt)&&(Mt=lt(Me,rt),q(Mt)||(q(It)&&(It=new f,$e.set(Me,It)),It.set(rt,Mt))),Mt}function Re(Me){if(q(Me))throw new TypeError;return te===Me||oe===Me||!q(ye)&&ye.has(Me)}function Oe(Me,rt,It){if(!Re(It))throw new Error("Metadata provider not registered.");var Mt=Se(Me,rt);if(Mt!==It){if(!q(Mt))return!1;var es=$e.get(Me);q(es)&&(es=new f,$e.set(Me,es)),es.set(rt,It)}return!0}}function Jd(){var J;return!q(v)&&ve(r.Reflect)&&Object.isExtensible(r.Reflect)&&(J=r.Reflect[v]),q(J)&&(J=wf()),!q(v)&&ve(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,v,{enumerable:!1,configurable:!1,writable:!1,value:J}),J}function vf(J){var te=new m,oe={isProviderFor:function(Re,Oe){var Me=te.get(Re);return q(Me)?!1:Me.has(Oe)},OrdinaryDefineOwnMetadata:Kt,OrdinaryHasOwnMetadata:$e,OrdinaryGetOwnMetadata:Ht,OrdinaryOwnMetadataKeys:lt,OrdinaryDeleteMetadata:Se};return p.registerProvider(oe),oe;function ye(Re,Oe,Me){var rt=te.get(Re),It=!1;if(q(rt)){if(!Me)return;rt=new f,te.set(Re,rt),It=!0}var Mt=rt.get(Oe);if(q(Mt)){if(!Me)return;if(Mt=new f,rt.set(Oe,Mt),!J.setProvider(Re,Oe,oe))throw rt.delete(Oe),It&&te.delete(Re),new Error("Wrong provider for target.")}return Mt}function $e(Re,Oe,Me){var rt=ye(Oe,Me,!1);return q(rt)?!1:Dt(rt.has(Re))}function Ht(Re,Oe,Me){var rt=ye(Oe,Me,!1);if(!q(rt))return rt.get(Re)}function Kt(Re,Oe,Me,rt){var It=ye(Me,rt,!0);It.set(Re,Oe)}function lt(Re,Oe){var Me=[],rt=ye(Re,Oe,!1);if(q(rt))return Me;for(var It=rt.keys(),Mt=xf(It),es=0;;){var Zd=rc(Mt);if(!Zd)return Me.length=es,Me;var Im=Fn(Zd);try{Me[es]=Im}catch(X1){try{bf(Mt)}finally{throw X1}}es++}}function Se(Re,Oe,Me){var rt=ye(Oe,Me,!1);if(q(rt)||!rt.delete(Re))return!1;if(rt.size===0){var It=te.get(Oe);q(It)||(It.delete(Me),It.size===0&&te.delete(It))}return!0}}function Qd(J){var te=J.defineMetadata,oe=J.hasOwnMetadata,ye=J.getOwnMetadata,$e=J.getOwnMetadataKeys,Ht=J.deleteMetadata,Kt=new m,lt={isProviderFor:function(Se,Re){var Oe=Kt.get(Se);return!q(Oe)&&Oe.has(Re)?!0:$e(Se,Re).length?(q(Oe)&&(Oe=new h,Kt.set(Se,Oe)),Oe.add(Re),!0):!1},OrdinaryDefineOwnMetadata:te,OrdinaryHasOwnMetadata:oe,OrdinaryGetOwnMetadata:ye,OrdinaryOwnMetadataKeys:$e,OrdinaryDeleteMetadata:Ht};return lt}function Ri(J,te,oe){var ye=p.getProvider(J,te);if(!q(ye))return ye;if(oe){if(p.setProvider(J,te,x))return x;throw new Error("Illegal state.")}}function _f(){var J={},te=[],oe=(function(){function lt(Se,Re,Oe){this._index=0,this._keys=Se,this._values=Re,this._selector=Oe}return lt.prototype["@@iterator"]=function(){return this},lt.prototype[o]=function(){return this},lt.prototype.next=function(){var Se=this._index;if(Se>=0&&Se<this._keys.length){var Re=this._selector(this._keys[Se],this._values[Se]);return Se+1>=this._keys.length?(this._index=-1,this._keys=te,this._values=te):this._index++,{value:Re,done:!1}}return{value:void 0,done:!0}},lt.prototype.throw=function(Se){throw this._index>=0&&(this._index=-1,this._keys=te,this._values=te),Se},lt.prototype.return=function(Se){return this._index>=0&&(this._index=-1,this._keys=te,this._values=te),{value:Se,done:!0}},lt})(),ye=(function(){function lt(){this._keys=[],this._values=[],this._cacheKey=J,this._cacheIndex=-2}return Object.defineProperty(lt.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),lt.prototype.has=function(Se){return this._find(Se,!1)>=0},lt.prototype.get=function(Se){var Re=this._find(Se,!1);return Re>=0?this._values[Re]:void 0},lt.prototype.set=function(Se,Re){var Oe=this._find(Se,!0);return this._values[Oe]=Re,this},lt.prototype.delete=function(Se){var Re=this._find(Se,!1);if(Re>=0){for(var Oe=this._keys.length,Me=Re+1;Me<Oe;Me++)this._keys[Me-1]=this._keys[Me],this._values[Me-1]=this._values[Me];return this._keys.length--,this._values.length--,gf(Se,this._cacheKey)&&(this._cacheKey=J,this._cacheIndex=-2),!0}return!1},lt.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=J,this._cacheIndex=-2},lt.prototype.keys=function(){return new oe(this._keys,this._values,$e)},lt.prototype.values=function(){return new oe(this._keys,this._values,Ht)},lt.prototype.entries=function(){return new oe(this._keys,this._values,Kt)},lt.prototype["@@iterator"]=function(){return this.entries()},lt.prototype[o]=function(){return this.entries()},lt.prototype._find=function(Se,Re){if(!gf(this._cacheKey,Se)){this._cacheIndex=-1;for(var Oe=0;Oe<this._keys.length;Oe++)if(gf(this._keys[Oe],Se)){this._cacheIndex=Oe;break}}return this._cacheIndex<0&&Re&&(this._cacheIndex=this._keys.length,this._keys.push(Se),this._values.push(void 0)),this._cacheIndex},lt})();return ye;function $e(lt,Se){return lt}function Ht(lt,Se){return Se}function Kt(lt,Se){return[lt,Se]}}function km(){var J=(function(){function te(){this._map=new f}return Object.defineProperty(te.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),te.prototype.has=function(oe){return this._map.has(oe)},te.prototype.add=function(oe){return this._map.set(oe,oe),this},te.prototype.delete=function(oe){return this._map.delete(oe)},te.prototype.clear=function(){this._map.clear()},te.prototype.keys=function(){return this._map.keys()},te.prototype.values=function(){return this._map.keys()},te.prototype.entries=function(){return this._map.entries()},te.prototype["@@iterator"]=function(){return this.keys()},te.prototype[o]=function(){return this.keys()},te})();return J}function G1(){var J=16,te=u.create(),oe=ye();return(function(){function Se(){this._key=ye()}return Se.prototype.has=function(Re){var Oe=$e(Re,!1);return Oe!==void 0?u.has(Oe,this._key):!1},Se.prototype.get=function(Re){var Oe=$e(Re,!1);return Oe!==void 0?u.get(Oe,this._key):void 0},Se.prototype.set=function(Re,Oe){var Me=$e(Re,!0);return Me[this._key]=Oe,this},Se.prototype.delete=function(Re){var Oe=$e(Re,!1);return Oe!==void 0?delete Oe[this._key]:!1},Se.prototype.clear=function(){this._key=ye()},Se})();function ye(){var Se;do Se="@@WeakMap@@"+lt();while(u.has(te,Se));return te[Se]=!0,Se}function $e(Se,Re){if(!s.call(Se,oe)){if(!Re)return;Object.defineProperty(Se,oe,{value:u.create()})}return Se[oe]}function Ht(Se,Re){for(var Oe=0;Oe<Re;++Oe)Se[Oe]=Math.random()*255|0;return Se}function Kt(Se){if(typeof Uint8Array=="function"){var Re=new Uint8Array(Se);return typeof crypto<"u"?crypto.getRandomValues(Re):typeof msCrypto<"u"?msCrypto.getRandomValues(Re):Ht(Re,Se),Re}return Ht(new Array(Se),Se)}function lt(){var Se=Kt(J);Se[6]=Se[6]&79|64,Se[8]=Se[8]&191|128;for(var Re="",Oe=0;Oe<J;++Oe){var Me=Se[Oe];(Oe===4||Oe===6||Oe===8)&&(Re+="-"),Me<16&&(Re+="0"),Re+=Me.toString(16).toLowerCase()}return Re}}function nc(J){return J.__=void 0,delete J.__,J}})})(XA||(XA={}))});var Ui=Ne((Jse,X6)=>{"use strict";g();var W6=["nodebuffer","arraybuffer","fragments"],G6=typeof Blob<"u";G6&&W6.push("blob");X6.exports={BINARY_TYPES:W6,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:G6,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Kf=Ne((Zse,bg)=>{"use strict";g();var{EMPTY_BUFFER:E$}=Ui(),ev=Buffer[Symbol.species];function C$(t,e){if(t.length===0)return E$;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let n=0;n<t.length;n++){let i=t[n];r.set(i,s),s+=i.length}return s<e?new ev(r.buffer,r.byteOffset,s):r}function Y6(t,e,r,s,n){for(let i=0;i<n;i++)r[s+i]=t[i]^e[i&3]}function J6(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function T$(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function tv(t){if(tv.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ev(t):ArrayBuffer.isView(t)?e=new ev(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),tv.readOnly=!1),e}bg.exports={concat:C$,mask:Y6,toArrayBuffer:T$,toBuffer:tv,unmask:J6};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");bg.exports.mask=function(e,r,s,n,i){i<48?Y6(e,r,s,n,i):t.mask(e,r,s,n,i)},bg.exports.unmask=function(e,r){e.length<32?J6(e,r):t.unmask(e,r)}}catch{}});var eI=Ne((tne,Z6)=>{"use strict";g();var Q6=Symbol("kDone"),rv=Symbol("kRun"),sv=class{constructor(e){this[Q6]=()=>{this.pending--,this[rv]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[rv]()}[rv](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Q6])}}};Z6.exports=sv});var Cl=Ne((sne,nI)=>{"use strict";g();var Wf=require("zlib"),tI=Kf(),A$=eI(),{kStatusCode:rI}=Ui(),k$=Buffer[Symbol.species],I$=Buffer.from([0,0,255,255]),vg=Symbol("permessage-deflate"),Mi=Symbol("total-length"),Sl=Symbol("callback"),zo=Symbol("buffers"),El=Symbol("error"),wg,nv=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!wg){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;wg=new A$(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Sl];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let n=r[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=n})}),e}decompress(e,r,s){wg.add(n=>{this._decompress(e,r,(i,o)=>{n(),s(i,o)})})}compress(e,r,s){wg.add(n=>{this._compress(e,r,(i,o)=>{n(),s(i,o)})})}_decompress(e,r,s){let n=this._isServer?"client":"server";if(!this._inflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?Wf.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Wf.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[vg]=this,this._inflate[Mi]=0,this._inflate[zo]=[],this._inflate.on("error",P$),this._inflate.on("data",sI)}this._inflate[Sl]=s,this._inflate.write(e),r&&this._inflate.write(I$),this._inflate.flush(()=>{let i=this._inflate[El];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=tI.concat(this._inflate[zo],this._inflate[Mi]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Mi]=0,this._inflate[zo]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,r,s){let n=this._isServer?"server":"client";if(!this._deflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?Wf.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Wf.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Mi]=0,this._deflate[zo]=[],this._deflate.on("data",R$)}this._deflate[Sl]=s,this._deflate.write(e),this._deflate.flush(Wf.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=tI.concat(this._deflate[zo],this._deflate[Mi]);r&&(i=new k$(i.buffer,i.byteOffset,i.length-4)),this._deflate[Sl]=null,this._deflate[Mi]=0,this._deflate[zo]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};nI.exports=nv;function R$(t){this[zo].push(t),this[Mi]+=t.length}function sI(t){if(this[Mi]+=t.length,this[vg]._maxPayload<1||this[Mi]<=this[vg]._maxPayload){this[zo].push(t);return}this[El]=new RangeError("Max payload size exceeded"),this[El].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[El][rI]=1009,this.removeListener("data",sI),this.reset()}function P$(t){if(this[vg]._inflate=null,this[El]){this[Sl](this[El]);return}t[rI]=1007,this[Sl](t)}});var Tl=Ne((ine,_g)=>{"use strict";g();var{isUtf8:iI}=require("buffer"),{hasBlob:B$}=Ui(),D$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function N$(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function iv(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function O$(t){return B$&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}_g.exports={isBlob:O$,isValidStatusCode:N$,isValidUTF8:iv,tokenChars:D$};if(iI)_g.exports.isValidUTF8=function(t){return t.length<24?iv(t):iI(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");_g.exports.isValidUTF8=function(e){return e.length<32?iv(e):t(e)}}catch{}});var lv=Ne((ane,fI)=>{"use strict";g();var{Writable:L$}=require("stream"),oI=Cl(),{BINARY_TYPES:U$,EMPTY_BUFFER:aI,kStatusCode:M$,kWebSocket:j$}=Ui(),{concat:ov,toArrayBuffer:F$,unmask:H$}=Kf(),{isValidStatusCode:$$,isValidUTF8:cI}=Tl(),Sg=Buffer[Symbol.species],Hs=0,dI=1,lI=2,uI=3,av=4,cv=5,Eg=6,dv=class extends L${constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||U$[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[j$]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Hs}_write(e,r,s){if(this._opcode===8&&this._state==Hs)return s();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){s(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Sg(s.buffer,s.byteOffset+e,s.length-e),new Sg(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=r.length-e;e>=s.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new Sg(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case Hs:this.getInfo(e);break;case dI:this.getPayloadLength16(e);break;case lI:this.getPayloadLength64(e);break;case uI:this.getMask();break;case av:this.getData(e);break;case cv:case Eg:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(r[0]&64)===64;if(s&&!this._extensions[oI.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=dI:this._payloadLength===127?this._state=lI:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=uI:this._state=av}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=av}getData(e){let r=aI;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&H$(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=cv,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(s);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[oI.extensionName].decompress(e,this._fin,(n,i)=>{if(n)return r(n);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(o);return}this._fragments.push(i)}this.dataMessage(r),this._state===Hs&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Hs;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=ov(s,r):this._binaryType==="arraybuffer"?n=F$(ov(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Hs):(this._state=Eg,setImmediate(()=>{this.emit("message",n,!0),this._state=Hs,this.startLoop(e)}))}else{let n=ov(s,r);if(!this._skipUTF8Validation&&!cI(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===cv||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Hs):(this._state=Eg,setImmediate(()=>{this.emit("message",n,!1),this._state=Hs,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,aI),this.end();else{let s=e.readUInt16BE(0);if(!$$(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let n=new Sg(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!cI(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=Hs;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Hs):(this._state=Eg,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Hs,this.startLoop(r)}))}createError(e,r,s,n,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=i,o[M$]=n,o}};fI.exports=dv});var hv=Ne((lne,mI)=>{"use strict";g();var{Duplex:dne}=require("stream"),{randomFillSync:V$}=require("crypto"),{types:{isUint8Array:q$}}=require("util"),hI=Cl(),{EMPTY_BUFFER:z$,kWebSocket:K$,NOOP:W$}=Ui(),{isBlob:Al,isValidStatusCode:G$}=Tl(),{mask:pI,toBuffer:gc}=Kf(),$s=Symbol("kByteLength"),X$=Buffer.alloc(4),Cg=8*1024,yc,kl=Cg,pn=0,Y$=1,J$=2,uv=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=pn,this.onerror=W$,this[K$]=void 0}static frame(e,r){let s,n=!1,i=2,o=!1;r.mask&&(s=r.maskBuffer||X$,r.generateMask?r.generateMask(s):(kl===Cg&&(yc===void 0&&(yc=Buffer.alloc(Cg)),V$(yc,0,Cg),kl=0),s[0]=yc[kl++],s[1]=yc[kl++],s[2]=yc[kl++],s[3]=yc[kl++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!r.mask||o)&&r[$s]!==void 0?a=r[$s]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(n?a+i:i);return d[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),r.mask?(d[1]|=128,d[i-4]=s[0],d[i-3]=s[1],d[i-2]=s[2],d[i-1]=s[3],o?[d,e]:n?(pI(e,s,d,i,a),[d]):(pI(e,s,e,0,a),[d,e])):[d,e]}close(e,r,s,n){let i;if(e===void 0)i=z$;else{if(typeof e!="number"||!G$(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof r=="string")i.write(r,2);else if(q$(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[$s]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==pn?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(t.frame(i,o),n)}ping(e,r,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):Al(e)?(n=e.size,i=!1):(e=gc(e),n=e.length,i=gc.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$s]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Al(e)?this._state!==pn?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==pn?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,r,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):Al(e)?(n=e.size,i=!1):(e=gc(e),n=e.length,i=gc.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$s]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Al(e)?this._state!==pn?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==pn?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,r,s){let n=this._extensions[hI.extensionName],i=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Al(e)?(a=e.size,c=!1):(e=gc(e),a=e.length,c=gc.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._threshold),this._compress=o):(o=!1,i=0),r.fin&&(this._firstFragment=!0);let d={[$s]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Al(e)?this._state!==pn?this.enqueue([this.getBlobData,e,this._compress,d,s]):this.getBlobData(e,this._compress,d,s):this._state!==pn?this.enqueue([this.dispatch,e,this._compress,d,s]):this.dispatch(e,this._compress,d,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[$s],this._state=J$,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(fv,this,a,n);return}this._bufferedBytes-=s[$s];let o=gc(i);r?this.dispatch(o,r,s,n):(this._state=pn,this.sendFrame(t.frame(o,s),n),this.dequeue())}).catch(i=>{process.nextTick(Q$,this,i,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let i=this._extensions[hI.extensionName];this._bufferedBytes+=s[$s],this._state=Y$,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");fv(this,c,n);return}this._bufferedBytes-=s[$s],this._state=pn,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===pn&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][$s],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][$s],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};mI.exports=uv;function fv(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let n=t._queue[s],i=n[n.length-1];typeof i=="function"&&i(e)}}function Q$(t,e,r){fv(t,e,r),t.onerror(e)}});var EI=Ne((fne,SI)=>{"use strict";g();var{kForOnEventAttribute:Gf,kListener:pv}=Ui(),gI=Symbol("kCode"),yI=Symbol("kData"),xI=Symbol("kError"),bI=Symbol("kMessage"),wI=Symbol("kReason"),Il=Symbol("kTarget"),vI=Symbol("kType"),_I=Symbol("kWasClean"),ji=class{constructor(e){this[Il]=null,this[vI]=e}get target(){return this[Il]}get type(){return this[vI]}};Object.defineProperty(ji.prototype,"target",{enumerable:!0});Object.defineProperty(ji.prototype,"type",{enumerable:!0});var xc=class extends ji{constructor(e,r={}){super(e),this[gI]=r.code===void 0?0:r.code,this[wI]=r.reason===void 0?"":r.reason,this[_I]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[gI]}get reason(){return this[wI]}get wasClean(){return this[_I]}};Object.defineProperty(xc.prototype,"code",{enumerable:!0});Object.defineProperty(xc.prototype,"reason",{enumerable:!0});Object.defineProperty(xc.prototype,"wasClean",{enumerable:!0});var Rl=class extends ji{constructor(e,r={}){super(e),this[xI]=r.error===void 0?null:r.error,this[bI]=r.message===void 0?"":r.message}get error(){return this[xI]}get message(){return this[bI]}};Object.defineProperty(Rl.prototype,"error",{enumerable:!0});Object.defineProperty(Rl.prototype,"message",{enumerable:!0});var Xf=class extends ji{constructor(e,r={}){super(e),this[yI]=r.data===void 0?null:r.data}get data(){return this[yI]}};Object.defineProperty(Xf.prototype,"data",{enumerable:!0});var Z$={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[Gf]&&n[pv]===e&&!n[Gf])return;let s;if(t==="message")s=function(i,o){let a=new Xf("message",{data:o?i:i.toString()});a[Il]=this,Tg(e,this,a)};else if(t==="close")s=function(i,o){let a=new xc("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Il]=this,Tg(e,this,a)};else if(t==="error")s=function(i){let o=new Rl("error",{error:i,message:i.message});o[Il]=this,Tg(e,this,o)};else if(t==="open")s=function(){let i=new ji("open");i[Il]=this,Tg(e,this,i)};else return;s[Gf]=!!r[Gf],s[pv]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[pv]===e&&!r[Gf]){this.removeListener(t,r);break}}};SI.exports={CloseEvent:xc,ErrorEvent:Rl,Event:ji,EventTarget:Z$,MessageEvent:Xf};function Tg(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ag=Ne((pne,CI)=>{"use strict";g();var{tokenChars:Yf}=Tl();function Kn(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function eV(t){let e=Object.create(null),r=Object.create(null),s=!1,n=!1,i=!1,o,a,c=-1,d=-1,u=-1,l=0;for(;l<t.length;l++)if(d=t.charCodeAt(l),o===void 0)if(u===-1&&Yf[d]===1)c===-1&&(c=l);else if(l!==0&&(d===32||d===9))u===-1&&c!==-1&&(u=l);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);u===-1&&(u=l);let h=t.slice(c,u);d===44?(Kn(e,h,r),r=Object.create(null)):o=h,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);else if(a===void 0)if(u===-1&&Yf[d]===1)c===-1&&(c=l);else if(d===32||d===9)u===-1&&c!==-1&&(u=l);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);u===-1&&(u=l),Kn(r,t.slice(c,u),!0),d===44&&(Kn(e,o,r),r=Object.create(null),o=void 0),c=u=-1}else if(d===61&&c!==-1&&u===-1)a=t.slice(c,l),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(n){if(Yf[d]!==1)throw new SyntaxError(`Unexpected character at index ${l}`);c===-1?c=l:s||(s=!0),n=!1}else if(i)if(Yf[d]===1)c===-1&&(c=l);else if(d===34&&c!==-1)i=!1,u=l;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(d===34&&t.charCodeAt(l-1)===61)i=!0;else if(u===-1&&Yf[d]===1)c===-1&&(c=l);else if(c!==-1&&(d===32||d===9))u===-1&&(u=l);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);u===-1&&(u=l);let h=t.slice(c,u);s&&(h=h.replace(/\\/g,""),s=!1),Kn(r,a,h),d===44&&(Kn(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=l);let f=t.slice(c,u);return o===void 0?Kn(e,f,r):(a===void 0?Kn(r,f,!0):s?Kn(r,a,f.replace(/\\/g,"")):Kn(r,a,f),Kn(e,o,r)),e}function tV(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(n=>{let i=s[n];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}CI.exports={format:tV,parse:eV}});var Pg=Ne((xne,UI)=>{"use strict";g();var rV=require("events"),sV=require("https"),nV=require("http"),kI=require("net"),iV=require("tls"),{randomBytes:oV,createHash:aV}=require("crypto"),{Duplex:gne,Readable:yne}=require("stream"),{URL:mv}=require("url"),Ko=Cl(),cV=lv(),dV=hv(),{isBlob:lV}=Tl(),{BINARY_TYPES:TI,CLOSE_TIMEOUT:uV,EMPTY_BUFFER:kg,GUID:fV,kForOnEventAttribute:gv,kListener:hV,kStatusCode:pV,kWebSocket:kr,NOOP:II}=Ui(),{EventTarget:{addEventListener:mV,removeEventListener:gV}}=EI(),{format:yV,parse:xV}=Ag(),{toBuffer:bV}=Kf(),RI=Symbol("kAborted"),yv=[8,13],Fi=["CONNECTING","OPEN","CLOSING","CLOSED"],wV=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Qt=class t extends rV{constructor(e,r,s){super(),this._binaryType=TI[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=kg,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),PI(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){TI.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let n=new cV({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new dV(e,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[kr]=this,i[kr]=this,e[kr]=this,n.on("conclude",SV),n.on("drain",EV),n.on("error",CV),n.on("message",TV),n.on("ping",AV),n.on("pong",kV),i.onerror=IV,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",NI),e.on("data",Rg),e.on("end",OI),e.on("error",LI),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ko.extensionName]&&this._extensions[Ko.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ks(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),DI(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xv(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||kg,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xv(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||kg,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xv(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Ko.extensionName]||(n.compress=!1),this._sender.send(e||kg,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ks(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Qt,"CONNECTING",{enumerable:!0,value:Fi.indexOf("CONNECTING")});Object.defineProperty(Qt.prototype,"CONNECTING",{enumerable:!0,value:Fi.indexOf("CONNECTING")});Object.defineProperty(Qt,"OPEN",{enumerable:!0,value:Fi.indexOf("OPEN")});Object.defineProperty(Qt.prototype,"OPEN",{enumerable:!0,value:Fi.indexOf("OPEN")});Object.defineProperty(Qt,"CLOSING",{enumerable:!0,value:Fi.indexOf("CLOSING")});Object.defineProperty(Qt.prototype,"CLOSING",{enumerable:!0,value:Fi.indexOf("CLOSING")});Object.defineProperty(Qt,"CLOSED",{enumerable:!0,value:Fi.indexOf("CLOSED")});Object.defineProperty(Qt.prototype,"CLOSED",{enumerable:!0,value:Fi.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Qt.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Qt.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[gv])return e[hV];return null},set(e){for(let r of this.listeners(t))if(r[gv]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[gv]:!0})}})});Qt.prototype.addEventListener=mV;Qt.prototype.removeEventListener=gV;UI.exports=Qt;function PI(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:uV,protocolVersion:yv[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,t._closeTimeout=n.closeTimeout,!yv.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${yv.join(", ")})`);let i;if(e instanceof mv)i=e;else try{i=new mv(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let v=new SyntaxError(c);if(t._redirects===0)throw v;Ig(t,v);return}let d=o?443:80,u=oV(16).toString("base64"),l=o?sV.request:nV.request,f=new Set,h;if(n.createConnection=n.createConnection||(o?_V:vV),n.defaultPort=n.defaultPort||d,n.port=i.port||d,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(h=new Ko({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=yV({[Ko.extensionName]:h.offer()})),r.length){for(let v of r){if(typeof v!="string"||!wV.test(v)||f.has(v))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(v)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){let v=n.path.split(":");n.socketPath=v[0],n.path=v[1]}let m;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?n.socketPath:i.host;let v=s&&s.headers;if(s={...s,headers:{}},v)for(let[p,x]of Object.entries(v))s.headers[p.toLowerCase()]=x}else if(t.listenerCount("redirect")===0){let v=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!v||t._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,v||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),m=t._req=l(n),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=l(n);n.timeout&&m.on("timeout",()=>{ks(t,m,"Opening handshake has timed out")}),m.on("error",v=>{m===null||m[RI]||(m=t._req=null,Ig(t,v))}),m.on("response",v=>{let p=v.headers.location,x=v.statusCode;if(p&&n.followRedirects&&x>=300&&x<400){if(++t._redirects>n.maxRedirects){ks(t,m,"Maximum redirects exceeded");return}m.abort();let w;try{w=new mv(p,e)}catch{let P=new SyntaxError(`Invalid URL: ${p}`);Ig(t,P);return}PI(t,w,r,s)}else t.emit("unexpected-response",m,v)||ks(t,m,`Unexpected server response: ${v.statusCode}`)}),m.on("upgrade",(v,p,x)=>{if(t.emit("upgrade",v),t.readyState!==Qt.CONNECTING)return;m=t._req=null;let w=v.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){ks(t,p,"Invalid Upgrade header");return}let E=aV("sha1").update(u+fV).digest("base64");if(v.headers["sec-websocket-accept"]!==E){ks(t,p,"Invalid Sec-WebSocket-Accept header");return}let P=v.headers["sec-websocket-protocol"],j;if(P!==void 0?f.size?f.has(P)||(j="Server sent an invalid subprotocol"):j="Server sent a subprotocol but none was requested":f.size&&(j="Server sent no subprotocol"),j){ks(t,p,j);return}P&&(t._protocol=P);let T=v.headers["sec-websocket-extensions"];if(T!==void 0){if(!h){ks(t,p,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=xV(T)}catch{ks(t,p,"Invalid Sec-WebSocket-Extensions header");return}let _=Object.keys(k);if(_.length!==1||_[0]!==Ko.extensionName){ks(t,p,"Server indicated an extension that was not requested");return}try{h.accept(k[Ko.extensionName])}catch{ks(t,p,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ko.extensionName]=h}t.setSocket(p,x,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(m,t):m.end()}function Ig(t,e){t._readyState=Qt.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function vV(t){return t.path=t.socketPath,kI.connect(t)}function _V(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=kI.isIP(t.host)?"":t.host),iV.connect(t)}function ks(t,e,r){t._readyState=Qt.CLOSING;let s=new Error(r);Error.captureStackTrace(s,ks),e.setHeader?(e[RI]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ig,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function xv(t,e,r){if(e){let s=lV(e)?e.size:bV(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${Fi[t.readyState]})`);process.nextTick(r,s)}}function SV(t,e){let r=this[kr];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[kr]!==void 0&&(r._socket.removeListener("data",Rg),process.nextTick(BI,r._socket),t===1005?r.close():r.close(t,e))}function EV(){let t=this[kr];t.isPaused||t._socket.resume()}function CV(t){let e=this[kr];e._socket[kr]!==void 0&&(e._socket.removeListener("data",Rg),process.nextTick(BI,e._socket),e.close(t[pV])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function AI(){this[kr].emitClose()}function TV(t,e){this[kr].emit("message",t,e)}function AV(t){let e=this[kr];e._autoPong&&e.pong(t,!this._isServer,II),e.emit("ping",t)}function kV(t){this[kr].emit("pong",t)}function BI(t){t.resume()}function IV(t){let e=this[kr];e.readyState!==Qt.CLOSED&&(e.readyState===Qt.OPEN&&(e._readyState=Qt.CLOSING,DI(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function DI(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function NI(){let t=this[kr];if(this.removeListener("close",NI),this.removeListener("data",Rg),this.removeListener("end",OI),t._readyState=Qt.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[kr]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",AI),t._receiver.on("finish",AI))}function Rg(t){this[kr]._receiver.write(t)||this.pause()}function OI(){let t=this[kr];t._readyState=Qt.CLOSING,t._receiver.end(),this.end()}function LI(){let t=this[kr];this.removeListener("error",LI),this.on("error",II),t&&(t._readyState=Qt.CLOSING,this.destroy())}});var HI=Ne((vne,FI)=>{"use strict";g();var wne=Pg(),{Duplex:RV}=require("stream");function MI(t){t.emit("close")}function PV(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jI(t){this.removeListener("error",jI),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function BV(t,e){let r=!0,s=new RV({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(r=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,i){if(t.readyState===t.CLOSED){i(n),process.nextTick(MI,s);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(n),process.nextTick(MI,s)}),r&&t.terminate()},s._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(n,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(n,i,o)});return}t.send(n,o)},s.on("end",PV),s.on("error",jI),s}FI.exports=BV});var bv=Ne((Sne,$I)=>{"use strict";g();var{tokenChars:DV}=Tl();function NV(t){let e=new Set,r=-1,s=-1,n=0;for(n;n<t.length;n++){let o=t.charCodeAt(n);if(s===-1&&DV[o]===1)r===-1&&(r=n);else if(n!==0&&(o===32||o===9))s===-1&&r!==-1&&(s=n);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=t.slice(r,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,n);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}$I.exports={parse:NV}});var XI=Ne((Tne,GI)=>{"use strict";g();var OV=require("events"),Bg=require("http"),{Duplex:Cne}=require("stream"),{createHash:LV}=require("crypto"),VI=Ag(),bc=Cl(),UV=bv(),MV=Pg(),{CLOSE_TIMEOUT:jV,GUID:FV,kWebSocket:HV}=Ui(),$V=/^[+/0-9A-Za-z]{22}==$/,qI=0,zI=1,WI=2,wv=class extends OV{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jV,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:MV,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Bg.createServer((s,n)=>{let i=Bg.STATUS_CODES[426];n.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),n.end(i)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=VV(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,i,o)=>{this.handleUpgrade(n,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=qI}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===WI){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Jf,this);return}if(e&&this.once("close",e),this._state!==zI)if(this._state=zI,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Jf,this):process.nextTick(Jf,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Jf(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,n){r.on("error",KI);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){wc(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){wc(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!$V.test(i)){wc(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){wc(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qf(r,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=UV.parse(c)}catch{wc(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&u!==void 0){let f=new bc({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=VI.parse(u);h[bc.extensionName]&&(f.accept(h[bc.extensionName]),l[bc.extensionName]=f)}catch{wc(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,m,v,p)=>{if(!h)return Qf(r,m||401,v,p);this.completeUpgrade(l,i,d,e,r,s,n)});return}if(!this.options.verifyClient(f))return Qf(r,401)}this.completeUpgrade(l,i,d,e,r,s,n)}completeUpgrade(e,r,s,n,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[HV])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qI)return Qf(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${LV("sha1").update(r+FV).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let l=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;l&&(d.push(`Sec-WebSocket-Protocol: ${l}`),u._protocol=l)}if(e[bc.extensionName]){let l=e[bc.extensionName].params,f=VI.format({[bc.extensionName]:[l]});d.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",d,n),i.write(d.concat(`\r
2
+ `).join(`\r
3
+ `)),i.removeListener("error",KI),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Jf,this)})),a(u,n)}};GI.exports=wv;function VV(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function Jf(t){t._state=WI,t.emit("close")}function KI(){this.destroy()}function Qf(t,e,r,s){r=r||Bg.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Bg.STATUS_CODES[e]}\r
4
+ `+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
5
+ `)+`\r
6
+ \r
7
+ `+r)}function wc(t,e,r,s,n,i){if(t.listenerCount("wsClientError")){let o=new Error(n);Error.captureStackTrace(o,wc),t.emit("wsClientError",o,r,e)}else Qf(r,s,n,i)}});var s3={};ic(s3,{PerMessageDeflate:()=>QI.default,Receiver:()=>ZI.default,Sender:()=>e3.default,WebSocket:()=>vv.default,WebSocketServer:()=>r3.default,createWebSocketStream:()=>YI.default,default:()=>qV,extension:()=>JI.default,subprotocol:()=>t3.default});var YI,JI,QI,ZI,e3,t3,vv,r3,qV,n3=z(()=>{"use strict";g();YI=Fe(HI(),1),JI=Fe(Ag(),1),QI=Fe(Cl(),1),ZI=Fe(lv(),1),e3=Fe(hv(),1),t3=Fe(bv(),1),vv=Fe(Pg(),1),r3=Fe(XI(),1),qV=vv.default});var Wo=Ne(i3=>{"use strict";g();function zV(){var t,e=!1,r=this;r._DeArray=function(s,n,i){return[s.slice(n,n+i)]},r._EnArray=function(s,n,i,o){for(var a=0;a<i;s[n+a]=o[a]?o[a]:0,a++);},r._DeChar=function(s,n){return String.fromCharCode(s[n])},r._EnChar=function(s,n,i){s[n]=i.charCodeAt(0)},r._DeInt=function(s,n){var i=e?t.len-1:0,o=e?-1:1,a=i+o*t.len,c,d,u;for(c=0,d=i,u=1;d!=a;c+=s[n+d]*u,d+=o,u*=256);return t.bSigned&&c&Math.pow(2,t.len*8-1)&&(c-=Math.pow(2,t.len*8)),c},r._EnInt=function(s,n,i){var o=e?t.len-1:0,a=e?-1:1,c=o+a*t.len,d;for(i=i<t.min?t.min:i>t.max?t.max:i,d=o;d!=c;s[n+d]=i&255,d+=a,i>>=8);},r._DeString=function(s,n,i){for(var o=new Array(i),a=0;a<i;o[a]=String.fromCharCode(s[n+a]),a++);return o.join("")},r._EnString=function(s,n,i,o){for(var a,c=0;c<i;s[n+c]=(a=o.charCodeAt(c))?a:0,c++);},r._De754=function(s,n){var i,o,a,c,d,u,l,f,h,m;for(l=t.mLen,f=t.len*8-t.mLen-1,m=(1<<f)-1,h=m>>1,c=e?0:t.len-1,d=e?1:-1,i=s[n+c],c+=d,u=-7,o=i&(1<<-u)-1,i>>=-u,u+=f;u>0;o=o*256+s[n+c],c+=d,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=l;u>0;a=a*256+s[n+c],c+=d,u-=8);switch(o){case 0:o=1-h;break;case m:return a?NaN:(i?-1:1)*(1/0);default:a=a+Math.pow(2,l),o=o-h;break}return(i?-1:1)*a*Math.pow(2,o-l)},r._En754=function(s,n,i){var o,a,c,d,u,l,f,h,m,v;for(f=t.mLen,h=t.len*8-t.mLen-1,v=(1<<h)-1,m=v>>1,o=i<0?1:0,i=Math.abs(i),isNaN(i)||i==1/0?(c=isNaN(i)?1:0,a=v):(a=Math.floor(Math.log(i)/Math.LN2),i*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+m>=1?i+=t.rt/l:i+=t.rt*Math.pow(2,1-m),i*l>=2&&(a++,l/=2),a+m>=v?(c=0,a=v):a+m>=1?(c=(i*l-1)*Math.pow(2,f),a=a+m):(c=i*Math.pow(2,m-1)*Math.pow(2,f),a=0)),d=e?t.len-1:0,u=e?-1:1;f>=8;s[n+d]=c&255,d+=u,c/=256,f-=8);for(a=a<<f|c,h+=f;h>0;s[n+d]=a&255,d+=u,a/=256,h-=8);s[n+d-u]|=o*128},r._DeInt64=function(s,n){var i=e?0:7,o=e?1:-1,a=i+o*8,c=[0,0,!t.bSigned],d,u,l;for(d=i,l=1,u=0;d!=a;c[l]=(c[l]<<8>>>0)+s[n+d],d+=o,u++,l=u<4?1:0);return c},r._EnInt64=function(s,n,i){var o=e?0:7,a=e?1:-1,c=o+a*8,d,u,l,f;for(d=o,l=1,u=0,f=24;d!=c;s[n+d]=i[l]>>f&255,d+=a,u++,l=u<4?1:0,f=24-8*(u%4));},r._sPattern="(\\d + )?([AxcbBhHsfdiIlLqQ])",r._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},r._elLut={A:{en:r._EnArray,de:r._DeArray},s:{en:r._EnString,de:r._DeString},c:{en:r._EnChar,de:r._DeChar},b:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:r._En754,de:r._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:r._En754,de:r._De754,len:8,mLen:52,rt:0},q:{en:r._EnInt64,de:r._DeInt64,bSigned:!0},Q:{en:r._EnInt64,de:r._DeInt64,bSigned:!1}},r._UnpackSeries=function(s,n,i,o){for(var a=t.de,c=[],d=0;d<s;c.push(a(i,o+d*n)),d++);return c},r._PackSeries=function(s,n,i,o,a,c){for(var d=t.en,u=0;u<s;d(i,o+u*n,a[c+u]),u++);},r.Unpack=function(s,n,i){e=s.charAt(0)!="<",i=i||0;for(var o=new RegExp(this._sPattern,"g"),a,c,d,u=[];a=o.exec(s);){if(c=a[1]==null||a[1]==""?1:parseInt(a[1]),d=this._lenLut[a[2]],i+c*d>n.length)return;switch(a[2]){case"A":case"s":u.push(this._elLut[a[2]].de(n,i,c));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":t=this._elLut[a[2]],u.push(this._UnpackSeries(c,d,n,i));break}i+=c*d}return Array.prototype.concat.apply([],u)},r.PackTo=function(s,n,i,o){e=s.charAt(0)!="<";for(var a=new RegExp(this._sPattern,"g"),c,d,u,l,f=0;c=a.exec(s);){if(d=c[1]==null||c[1]==""?1:parseInt(c[1]),u=this._lenLut[c[2]],i+d*u>n.length)return!1;switch(c[2]){case"A":case"s":if(f+1>o.length)return!1;this._elLut[c[2]].en(n,i,d,o[f]),f+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(t=this._elLut[c[2]],f+d>o.length)return!1;this._PackSeries(d,u,n,i,o,f),f+=d;break;case"x":for(l=0;l<d;l++)n[i+l]=0;break}i+=d*u}return n},r.Pack=function(s,n){return this.PackTo(s,new Array(this.CalcLength(s)),0,n)},r.CalcLength=function(s){for(var n=new RegExp(this._sPattern,"g"),i=0,o;o=n.exec(s);)i+=(o[1]==null||o[1]==""?1:parseInt(o[1]))*this._lenLut[o[2]];return i}}i3.jspack=new zV});var a3=Ne((Pne,o3)=>{"use strict";g();var Pl=1e3,Bl=Pl*60,Dl=Bl*60,vc=Dl*24,KV=vc*7,WV=vc*365.25;o3.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return GV(t);if(r==="number"&&isFinite(t))return e.long?YV(t):XV(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function GV(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return r*WV;case"weeks":case"week":case"w":return r*KV;case"days":case"day":case"d":return r*vc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Dl;case"minutes":case"minute":case"mins":case"min":case"m":return r*Bl;case"seconds":case"second":case"secs":case"sec":case"s":return r*Pl;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function XV(t){var e=Math.abs(t);return e>=vc?Math.round(t/vc)+"d":e>=Dl?Math.round(t/Dl)+"h":e>=Bl?Math.round(t/Bl)+"m":e>=Pl?Math.round(t/Pl)+"s":t+"ms"}function YV(t){var e=Math.abs(t);return e>=vc?Dg(t,e,vc,"day"):e>=Dl?Dg(t,e,Dl,"hour"):e>=Bl?Dg(t,e,Bl,"minute"):e>=Pl?Dg(t,e,Pl,"second"):t+" ms"}function Dg(t,e,r,s){var n=e>=r*1.5;return Math.round(t/r)+" "+s+(n?"s":"")}});var _v=Ne((Dne,c3)=>{"use strict";g();function JV(t){r.debug=r,r.default=r,r.coerce=c,r.disable=o,r.enable=n,r.enabled=a,r.humanize=a3(),r.destroy=d,Object.keys(t).forEach(u=>{r[u]=t[u]}),r.names=[],r.skips=[],r.formatters={};function e(u){let l=0;for(let f=0;f<u.length;f++)l=(l<<5)-l+u.charCodeAt(f),l|=0;return r.colors[Math.abs(l)%r.colors.length]}r.selectColor=e;function r(u){let l,f=null,h,m;function v(...p){if(!v.enabled)return;let x=v,w=Number(new Date),E=w-(l||w);x.diff=E,x.prev=l,x.curr=w,l=w,p[0]=r.coerce(p[0]),typeof p[0]!="string"&&p.unshift("%O");let P=0;p[0]=p[0].replace(/%([a-zA-Z%])/g,(T,k)=>{if(T==="%%")return"%";P++;let _=r.formatters[k];if(typeof _=="function"){let A=p[P];T=_.call(x,A),p.splice(P,1),P--}return T}),r.formatArgs.call(x,p),(x.log||r.log).apply(x,p)}return v.namespace=u,v.useColors=r.useColors(),v.color=r.selectColor(u),v.extend=s,v.destroy=r.destroy,Object.defineProperty(v,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==r.namespaces&&(h=r.namespaces,m=r.enabled(u)),m),set:p=>{f=p}}),typeof r.init=="function"&&r.init(v),v}function s(u,l){let f=r(this.namespace+(typeof l>"u"?":":l)+u);return f.log=this.log,f}function n(u){r.save(u),r.namespaces=u,r.names=[],r.skips=[];let l=(typeof u=="string"?u:"").trim().replace(" ",",").split(",").filter(Boolean);for(let f of l)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function i(u,l){let f=0,h=0,m=-1,v=0;for(;f<u.length;)if(h<l.length&&(l[h]===u[f]||l[h]==="*"))l[h]==="*"?(m=h,v=f,h++):(f++,h++);else if(m!==-1)h=m+1,v++,f=v;else return!1;for(;h<l.length&&l[h]==="*";)h++;return h===l.length}function o(){let u=[...r.names,...r.skips.map(l=>"-"+l)].join(",");return r.enable(""),u}function a(u){for(let l of r.skips)if(i(u,l))return!1;for(let l of r.names)if(i(u,l))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}c3.exports=JV});var d3=Ne((Is,Ng)=>{"use strict";g();Is.formatArgs=ZV;Is.save=eq;Is.load=tq;Is.useColors=QV;Is.storage=rq();Is.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Is.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function QV(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ZV(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ng.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(r++,n==="%c"&&(s=r))}),t.splice(s,0,e)}Is.log=console.debug||console.log||(()=>{});function eq(t){try{t?Is.storage.setItem("debug",t):Is.storage.removeItem("debug")}catch{}}function tq(){let t;try{t=Is.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function rq(){try{return localStorage}catch{}}Ng.exports=_v()(Is);var{formatters:sq}=Ng.exports;sq.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var u3={};ic(u3,{createSupportsColor:()=>Ev,default:()=>cq});function Vs(t,e=globalThis.Deno?globalThis.Deno.args:Lg.default.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",s=e.indexOf(r+t),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}function nq(){if(!("FORCE_COLOR"in Zt))return;if(Zt.FORCE_COLOR==="true")return 1;if(Zt.FORCE_COLOR==="false")return 0;if(Zt.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(Zt.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function iq(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function oq(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let s=nq();s!==void 0&&(Og=s);let n=r?Og:s;if(n===0)return 0;if(r){if(Vs("color=16m")||Vs("color=full")||Vs("color=truecolor"))return 3;if(Vs("color=256"))return 2}if("TF_BUILD"in Zt&&"AGENT_NAME"in Zt)return 1;if(t&&!e&&n===void 0)return 0;let i=n||0;if(Zt.TERM==="dumb")return i;if(Lg.default.platform==="win32"){let o=l3.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Zt)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Zt)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Zt)||Zt.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Zt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Zt.TEAMCITY_VERSION)?1:0;if(Zt.COLORTERM==="truecolor"||Zt.TERM==="xterm-kitty"||Zt.TERM==="xterm-ghostty"||Zt.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Zt){let o=Number.parseInt((Zt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Zt.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Zt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Zt.TERM)||"COLORTERM"in Zt?1:i}function Ev(t,e={}){let r=oq(t,{streamIsTTY:t&&t.isTTY,...e});return iq(r)}var Lg,l3,Sv,Zt,Og,aq,cq,f3=z(()=>{"use strict";g();Lg=Fe(require("process"),1),l3=Fe(require("os"),1),Sv=Fe(require("tty"),1);({env:Zt}=Lg.default);Vs("no-color")||Vs("no-colors")||Vs("color=false")||Vs("color=never")?Og=0:(Vs("color")||Vs("colors")||Vs("color=true")||Vs("color=always"))&&(Og=1);aq={stdout:Ev({isTTY:Sv.default.isatty(1)}),stderr:Ev({isTTY:Sv.default.isatty(2)})},cq=aq});var p3=Ne((Ir,Mg)=>{"use strict";g();var dq=require("tty"),Ug=require("util");Ir.init=gq;Ir.log=hq;Ir.formatArgs=uq;Ir.save=pq;Ir.load=mq;Ir.useColors=lq;Ir.destroy=Ug.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ir.colors=[6,2,3,4,5,1];try{let t=(f3(),GA(u3));t&&(t.stderr||t).level>=2&&(Ir.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{}Ir.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),t[r]=s,t},{});function lq(){return"colors"in Ir.inspectOpts?!!Ir.inspectOpts.colors:dq.isatty(process.stderr.fd)}function uq(t){let{namespace:e,useColors:r}=this;if(r){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),i=` ${n};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
8
+ `).join(`
9
+ `+i),t.push(n+"m+"+Mg.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=fq()+e+" "+t[0]}function fq(){return Ir.inspectOpts.hideDate?"":new Date().toISOString()+" "}function hq(...t){return process.stderr.write(Ug.formatWithOptions(Ir.inspectOpts,...t)+`
10
+ `)}function pq(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function mq(){return process.env.DEBUG}function gq(t){t.inspectOpts={};let e=Object.keys(Ir.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=Ir.inspectOpts[e[r]]}Mg.exports=_v()(Ir);var{formatters:h3}=Mg.exports;h3.o=function(t){return this.inspectOpts.colors=this.useColors,Ug.inspect(t,this.inspectOpts).split(`
11
+ `).map(e=>e.trim()).join(" ")};h3.O=function(t){return this.inspectOpts.colors=this.useColors,Ug.inspect(t,this.inspectOpts)}});var m3=Ne((Mne,Cv)=>{"use strict";g();typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Cv.exports=d3():Cv.exports=p3()});var jg=Ne(Nl=>{"use strict";g();Object.defineProperty(Nl,"__esModule",{value:!0});var yq=require("net");function xq(t){switch(yq.isIP(t)){case 4:return Buffer.from(t.split(".").map(n=>parseInt(n,10)));case 6:let e=t.split(":"),r=Buffer.alloc(16),s=0;e[e.length-1]===""&&(e[e.length-1]="0");for(let n=0;n<e.length;n++){if(e[n]===""){n+1<e.length&&e[n+1]!==""&&(s=16-(e.length-n-1)*2);continue}r.writeUInt16BE(parseInt(e[n],16),s),s+=2}return r;default:return null}}Nl.bytesFromIP=xq;function bq(t){switch(t.length){case 4:return[t[0],t[1],t[2],t[3]].join(".");case 16:let e=[],r=-1,s=0,n=-1,i=0;for(let o=0;o<t.length;o+=2){let a=t[o]<<8|t[o+1];a===0?(s++,r===-1&&(r=e.length),s>i&&(i=s,n=r)):(r=-1,s=0),e.push(a.toString(16))}if(i>0){let o="",a=e.slice(n+i);e.length=n,e.length===0&&(o+=":"),a.length===0&&(o+=":"),e.push(o,...a)}return e.join(":");default:return""}}Nl.bytesToIP=bq;var Go=Object.create(null),g3=/^[0-9.]+$/;function wq(t){return g3.test(t)&&Go[t]!==""?t:Go[t]==null?"":Go[t]}Nl.getOID=wq;function vq(t){return!g3.test(t)&&Go[t]!==""||Go[t]==null?t:Go[t]}Nl.getOIDName=vq;function ue(t,e){Go[t]=e,Go[e]=t}ue("1.2.840.113549.1.1.1","rsaEncryption");ue("1.2.840.113549.1.1.4","md5WithRsaEncryption");ue("1.2.840.113549.1.1.5","sha1WithRsaEncryption");ue("1.2.840.113549.1.1.8","mgf1");ue("1.2.840.113549.1.1.10","RSASSA-PSS");ue("1.2.840.113549.1.1.11","sha256WithRsaEncryption");ue("1.2.840.113549.1.1.12","sha384WithRsaEncryption");ue("1.2.840.113549.1.1.13","sha512WithRsaEncryption");ue("1.2.840.10045.2.1","ecEncryption");ue("1.2.840.10045.4.1","ecdsaWithSha1");ue("1.2.840.10045.4.3.2","ecdsaWithSha256");ue("1.2.840.10045.4.3.3","ecdsaWithSha384");ue("1.2.840.10045.4.3.4","ecdsaWithSha512");ue("1.2.840.10040.4.3","dsaWithSha1");ue("2.16.840.1.101.3.4.3.2","dsaWithSha256");ue("1.3.14.3.2.7","desCBC");ue("1.3.14.3.2.26","sha1");ue("2.16.840.1.101.3.4.2.1","sha256");ue("2.16.840.1.101.3.4.2.2","sha384");ue("2.16.840.1.101.3.4.2.3","sha512");ue("1.2.840.113549.2.5","md5");ue("1.3.101.110","X25519");ue("1.3.101.111","X448");ue("1.3.101.112","Ed25519");ue("1.3.101.113","Ed448");ue("1.2.840.113549.1.7.1","data");ue("1.2.840.113549.1.7.2","signedData");ue("1.2.840.113549.1.7.3","envelopedData");ue("1.2.840.113549.1.7.4","signedAndEnvelopedData");ue("1.2.840.113549.1.7.5","digestedData");ue("1.2.840.113549.1.7.6","encryptedData");ue("1.2.840.113549.1.9.1","emailAddress");ue("1.2.840.113549.1.9.2","unstructuredName");ue("1.2.840.113549.1.9.3","contentType");ue("1.2.840.113549.1.9.4","messageDigest");ue("1.2.840.113549.1.9.5","signingTime");ue("1.2.840.113549.1.9.6","counterSignature");ue("1.2.840.113549.1.9.7","challengePassword");ue("1.2.840.113549.1.9.8","unstructuredAddress");ue("1.2.840.113549.1.9.14","extensionRequest");ue("1.2.840.113549.1.9.20","friendlyName");ue("1.2.840.113549.1.9.21","localKeyId");ue("1.2.840.113549.1.9.22.1","x509Certificate");ue("1.2.840.113549.1.12.10.1.1","keyBag");ue("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");ue("1.2.840.113549.1.12.10.1.3","certBag");ue("1.2.840.113549.1.12.10.1.4","crlBag");ue("1.2.840.113549.1.12.10.1.5","secretBag");ue("1.2.840.113549.1.12.10.1.6","safeContentsBag");ue("1.2.840.113549.1.5.13","pkcs5PBES2");ue("1.2.840.113549.1.5.12","pkcs5PBKDF2");ue("1.2.840.113549.2.7","hmacWithSha1");ue("1.2.840.113549.2.9","hmacWithSha256");ue("1.2.840.113549.2.10","hmacWithSha384");ue("1.2.840.113549.2.11","hmacWithSha512");ue("1.2.840.113549.3.7","3desCBC");ue("2.16.840.1.101.3.4.1.2","aesCBC128");ue("2.16.840.1.101.3.4.1.42","aesCBC256");ue("2.5.4.3","commonName");ue("2.5.4.5","serialName");ue("2.5.4.6","countryName");ue("2.5.4.7","localityName");ue("2.5.4.8","stateOrProvinceName");ue("2.5.4.10","organizationName");ue("2.5.4.11","organizationalUnitName");ue("2.5.4.15","businessCategory");ue("2.16.840.1.113730.1.1","nsCertType");ue("2.5.29.2","keyAttributes");ue("2.5.29.4","keyUsageRestriction");ue("2.5.29.6","subtreesConstraint");ue("2.5.29.9","subjectDirectoryAttributes");ue("2.5.29.14","subjectKeyIdentifier");ue("2.5.29.15","keyUsage");ue("2.5.29.16","privateKeyUsagePeriod");ue("2.5.29.17","subjectAltName");ue("2.5.29.18","issuerAltName");ue("2.5.29.19","basicConstraints");ue("2.5.29.20","cRLNumber");ue("2.5.29.21","cRLReason");ue("2.5.29.22","expirationDate");ue("2.5.29.23","instructionCode");ue("2.5.29.24","invalidityDate");ue("2.5.29.27","deltaCRLIndicator");ue("2.5.29.28","issuingDistributionPoint");ue("2.5.29.29","certificateIssuer");ue("2.5.29.30","nameConstraints");ue("2.5.29.31","cRLDistributionPoints");ue("2.5.29.32","certificatePolicies");ue("2.5.29.33","policyMappings");ue("2.5.29.35","authorityKeyIdentifier");ue("2.5.29.36","policyConstraints");ue("2.5.29.37","extKeyUsage");ue("2.5.29.46","freshestCRL");ue("2.5.29.54","inhibitAnyPolicy");ue("1.3.6.1.4.1.311.60.2.1.2","jurisdictionST");ue("1.3.6.1.4.1.311.60.2.1.3","jurisdictionC");ue("1.3.6.1.4.1.11129.2.4.2","timestampList");ue("1.3.6.1.5.5.7.1.1","authorityInfoAccess");ue("1.3.6.1.5.5.7.3.1","serverAuth");ue("1.3.6.1.5.5.7.3.2","clientAuth");ue("1.3.6.1.5.5.7.3.3","codeSigning");ue("1.3.6.1.5.5.7.3.4","emailProtection");ue("1.3.6.1.5.5.7.3.8","timeStamping");ue("1.3.6.1.5.5.7.48.1","authorityInfoAccessOcsp");ue("1.3.6.1.5.5.7.48.2","authorityInfoAccessIssuers")});var Hg=Ne(($ne,Fg)=>{"use strict";g();(function(t){"use strict";var e=function(S){var B,R=new Float64Array(16);if(S)for(B=0;B<S.length;B++)R[B]=S[B];return R},r=function(){throw new Error("no PRNG")},s=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var i=e(),o=e([1]),a=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),u=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),l=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function h(S,B,R,y){S[B]=R>>24&255,S[B+1]=R>>16&255,S[B+2]=R>>8&255,S[B+3]=R&255,S[B+4]=y>>24&255,S[B+5]=y>>16&255,S[B+6]=y>>8&255,S[B+7]=y&255}function m(S,B,R,y,L){var X,ee=0;for(X=0;X<L;X++)ee|=S[B+X]^R[y+X];return(1&ee-1>>>8)-1}function v(S,B,R,y){return m(S,B,R,y,16)}function p(S,B,R,y){return m(S,B,R,y,32)}function x(S,B,R,y){for(var L=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,X=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,ee=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,ce=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,xe=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,He=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,ke=B[0]&255|(B[1]&255)<<8|(B[2]&255)<<16|(B[3]&255)<<24,Rt=B[4]&255|(B[5]&255)<<8|(B[6]&255)<<16|(B[7]&255)<<24,De=B[8]&255|(B[9]&255)<<8|(B[10]&255)<<16|(B[11]&255)<<24,tt=B[12]&255|(B[13]&255)<<8|(B[14]&255)<<16|(B[15]&255)<<24,st=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,ht=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,ut=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,nt=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,ct=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,it=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,Le=L,Ke=X,Ie=ee,Ue=ce,je=xe,Te=He,ne=ke,ie=Rt,he=De,ae=tt,de=st,ge=ht,Qe=ut,pt=nt,gt=ct,mt=it,$,bt=0;bt<20;bt+=2)$=Le+Qe|0,je^=$<<7|$>>>25,$=je+Le|0,he^=$<<9|$>>>23,$=he+je|0,Qe^=$<<13|$>>>19,$=Qe+he|0,Le^=$<<18|$>>>14,$=Te+Ke|0,ae^=$<<7|$>>>25,$=ae+Te|0,pt^=$<<9|$>>>23,$=pt+ae|0,Ke^=$<<13|$>>>19,$=Ke+pt|0,Te^=$<<18|$>>>14,$=de+ne|0,gt^=$<<7|$>>>25,$=gt+de|0,Ie^=$<<9|$>>>23,$=Ie+gt|0,ne^=$<<13|$>>>19,$=ne+Ie|0,de^=$<<18|$>>>14,$=mt+ge|0,Ue^=$<<7|$>>>25,$=Ue+mt|0,ie^=$<<9|$>>>23,$=ie+Ue|0,ge^=$<<13|$>>>19,$=ge+ie|0,mt^=$<<18|$>>>14,$=Le+Ue|0,Ke^=$<<7|$>>>25,$=Ke+Le|0,Ie^=$<<9|$>>>23,$=Ie+Ke|0,Ue^=$<<13|$>>>19,$=Ue+Ie|0,Le^=$<<18|$>>>14,$=Te+je|0,ne^=$<<7|$>>>25,$=ne+Te|0,ie^=$<<9|$>>>23,$=ie+ne|0,je^=$<<13|$>>>19,$=je+ie|0,Te^=$<<18|$>>>14,$=de+ae|0,ge^=$<<7|$>>>25,$=ge+de|0,he^=$<<9|$>>>23,$=he+ge|0,ae^=$<<13|$>>>19,$=ae+he|0,de^=$<<18|$>>>14,$=mt+gt|0,Qe^=$<<7|$>>>25,$=Qe+mt|0,pt^=$<<9|$>>>23,$=pt+Qe|0,gt^=$<<13|$>>>19,$=gt+pt|0,mt^=$<<18|$>>>14;Le=Le+L|0,Ke=Ke+X|0,Ie=Ie+ee|0,Ue=Ue+ce|0,je=je+xe|0,Te=Te+He|0,ne=ne+ke|0,ie=ie+Rt|0,he=he+De|0,ae=ae+tt|0,de=de+st|0,ge=ge+ht|0,Qe=Qe+ut|0,pt=pt+nt|0,gt=gt+ct|0,mt=mt+it|0,S[0]=Le>>>0&255,S[1]=Le>>>8&255,S[2]=Le>>>16&255,S[3]=Le>>>24&255,S[4]=Ke>>>0&255,S[5]=Ke>>>8&255,S[6]=Ke>>>16&255,S[7]=Ke>>>24&255,S[8]=Ie>>>0&255,S[9]=Ie>>>8&255,S[10]=Ie>>>16&255,S[11]=Ie>>>24&255,S[12]=Ue>>>0&255,S[13]=Ue>>>8&255,S[14]=Ue>>>16&255,S[15]=Ue>>>24&255,S[16]=je>>>0&255,S[17]=je>>>8&255,S[18]=je>>>16&255,S[19]=je>>>24&255,S[20]=Te>>>0&255,S[21]=Te>>>8&255,S[22]=Te>>>16&255,S[23]=Te>>>24&255,S[24]=ne>>>0&255,S[25]=ne>>>8&255,S[26]=ne>>>16&255,S[27]=ne>>>24&255,S[28]=ie>>>0&255,S[29]=ie>>>8&255,S[30]=ie>>>16&255,S[31]=ie>>>24&255,S[32]=he>>>0&255,S[33]=he>>>8&255,S[34]=he>>>16&255,S[35]=he>>>24&255,S[36]=ae>>>0&255,S[37]=ae>>>8&255,S[38]=ae>>>16&255,S[39]=ae>>>24&255,S[40]=de>>>0&255,S[41]=de>>>8&255,S[42]=de>>>16&255,S[43]=de>>>24&255,S[44]=ge>>>0&255,S[45]=ge>>>8&255,S[46]=ge>>>16&255,S[47]=ge>>>24&255,S[48]=Qe>>>0&255,S[49]=Qe>>>8&255,S[50]=Qe>>>16&255,S[51]=Qe>>>24&255,S[52]=pt>>>0&255,S[53]=pt>>>8&255,S[54]=pt>>>16&255,S[55]=pt>>>24&255,S[56]=gt>>>0&255,S[57]=gt>>>8&255,S[58]=gt>>>16&255,S[59]=gt>>>24&255,S[60]=mt>>>0&255,S[61]=mt>>>8&255,S[62]=mt>>>16&255,S[63]=mt>>>24&255}function w(S,B,R,y){for(var L=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,X=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,ee=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,ce=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,xe=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,He=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,ke=B[0]&255|(B[1]&255)<<8|(B[2]&255)<<16|(B[3]&255)<<24,Rt=B[4]&255|(B[5]&255)<<8|(B[6]&255)<<16|(B[7]&255)<<24,De=B[8]&255|(B[9]&255)<<8|(B[10]&255)<<16|(B[11]&255)<<24,tt=B[12]&255|(B[13]&255)<<8|(B[14]&255)<<16|(B[15]&255)<<24,st=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,ht=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,ut=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,nt=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,ct=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,it=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,Le=L,Ke=X,Ie=ee,Ue=ce,je=xe,Te=He,ne=ke,ie=Rt,he=De,ae=tt,de=st,ge=ht,Qe=ut,pt=nt,gt=ct,mt=it,$,bt=0;bt<20;bt+=2)$=Le+Qe|0,je^=$<<7|$>>>25,$=je+Le|0,he^=$<<9|$>>>23,$=he+je|0,Qe^=$<<13|$>>>19,$=Qe+he|0,Le^=$<<18|$>>>14,$=Te+Ke|0,ae^=$<<7|$>>>25,$=ae+Te|0,pt^=$<<9|$>>>23,$=pt+ae|0,Ke^=$<<13|$>>>19,$=Ke+pt|0,Te^=$<<18|$>>>14,$=de+ne|0,gt^=$<<7|$>>>25,$=gt+de|0,Ie^=$<<9|$>>>23,$=Ie+gt|0,ne^=$<<13|$>>>19,$=ne+Ie|0,de^=$<<18|$>>>14,$=mt+ge|0,Ue^=$<<7|$>>>25,$=Ue+mt|0,ie^=$<<9|$>>>23,$=ie+Ue|0,ge^=$<<13|$>>>19,$=ge+ie|0,mt^=$<<18|$>>>14,$=Le+Ue|0,Ke^=$<<7|$>>>25,$=Ke+Le|0,Ie^=$<<9|$>>>23,$=Ie+Ke|0,Ue^=$<<13|$>>>19,$=Ue+Ie|0,Le^=$<<18|$>>>14,$=Te+je|0,ne^=$<<7|$>>>25,$=ne+Te|0,ie^=$<<9|$>>>23,$=ie+ne|0,je^=$<<13|$>>>19,$=je+ie|0,Te^=$<<18|$>>>14,$=de+ae|0,ge^=$<<7|$>>>25,$=ge+de|0,he^=$<<9|$>>>23,$=he+ge|0,ae^=$<<13|$>>>19,$=ae+he|0,de^=$<<18|$>>>14,$=mt+gt|0,Qe^=$<<7|$>>>25,$=Qe+mt|0,pt^=$<<9|$>>>23,$=pt+Qe|0,gt^=$<<13|$>>>19,$=gt+pt|0,mt^=$<<18|$>>>14;S[0]=Le>>>0&255,S[1]=Le>>>8&255,S[2]=Le>>>16&255,S[3]=Le>>>24&255,S[4]=Te>>>0&255,S[5]=Te>>>8&255,S[6]=Te>>>16&255,S[7]=Te>>>24&255,S[8]=de>>>0&255,S[9]=de>>>8&255,S[10]=de>>>16&255,S[11]=de>>>24&255,S[12]=mt>>>0&255,S[13]=mt>>>8&255,S[14]=mt>>>16&255,S[15]=mt>>>24&255,S[16]=ne>>>0&255,S[17]=ne>>>8&255,S[18]=ne>>>16&255,S[19]=ne>>>24&255,S[20]=ie>>>0&255,S[21]=ie>>>8&255,S[22]=ie>>>16&255,S[23]=ie>>>24&255,S[24]=he>>>0&255,S[25]=he>>>8&255,S[26]=he>>>16&255,S[27]=he>>>24&255,S[28]=ae>>>0&255,S[29]=ae>>>8&255,S[30]=ae>>>16&255,S[31]=ae>>>24&255}function E(S,B,R,y){x(S,B,R,y)}function P(S,B,R,y){w(S,B,R,y)}var j=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function T(S,B,R,y,L,X,ee){var ce=new Uint8Array(16),xe=new Uint8Array(64),He,ke;for(ke=0;ke<16;ke++)ce[ke]=0;for(ke=0;ke<8;ke++)ce[ke]=X[ke];for(;L>=64;){for(E(xe,ce,ee,j),ke=0;ke<64;ke++)S[B+ke]=R[y+ke]^xe[ke];for(He=1,ke=8;ke<16;ke++)He=He+(ce[ke]&255)|0,ce[ke]=He&255,He>>>=8;L-=64,B+=64,y+=64}if(L>0)for(E(xe,ce,ee,j),ke=0;ke<L;ke++)S[B+ke]=R[y+ke]^xe[ke];return 0}function k(S,B,R,y,L){var X=new Uint8Array(16),ee=new Uint8Array(64),ce,xe;for(xe=0;xe<16;xe++)X[xe]=0;for(xe=0;xe<8;xe++)X[xe]=y[xe];for(;R>=64;){for(E(ee,X,L,j),xe=0;xe<64;xe++)S[B+xe]=ee[xe];for(ce=1,xe=8;xe<16;xe++)ce=ce+(X[xe]&255)|0,X[xe]=ce&255,ce>>>=8;R-=64,B+=64}if(R>0)for(E(ee,X,L,j),xe=0;xe<R;xe++)S[B+xe]=ee[xe];return 0}function _(S,B,R,y,L){var X=new Uint8Array(32);P(X,y,L,j);for(var ee=new Uint8Array(8),ce=0;ce<8;ce++)ee[ce]=y[ce+16];return k(S,B,R,ee,X)}function A(S,B,R,y,L,X,ee){var ce=new Uint8Array(32);P(ce,X,ee,j);for(var xe=new Uint8Array(8),He=0;He<8;He++)xe[He]=X[He+16];return T(S,B,R,y,L,xe,ce)}var M=function(S){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var B,R,y,L,X,ee,ce,xe;B=S[0]&255|(S[1]&255)<<8,this.r[0]=B&8191,R=S[2]&255|(S[3]&255)<<8,this.r[1]=(B>>>13|R<<3)&8191,y=S[4]&255|(S[5]&255)<<8,this.r[2]=(R>>>10|y<<6)&7939,L=S[6]&255|(S[7]&255)<<8,this.r[3]=(y>>>7|L<<9)&8191,X=S[8]&255|(S[9]&255)<<8,this.r[4]=(L>>>4|X<<12)&255,this.r[5]=X>>>1&8190,ee=S[10]&255|(S[11]&255)<<8,this.r[6]=(X>>>14|ee<<2)&8191,ce=S[12]&255|(S[13]&255)<<8,this.r[7]=(ee>>>11|ce<<5)&8065,xe=S[14]&255|(S[15]&255)<<8,this.r[8]=(ce>>>8|xe<<8)&8191,this.r[9]=xe>>>5&127,this.pad[0]=S[16]&255|(S[17]&255)<<8,this.pad[1]=S[18]&255|(S[19]&255)<<8,this.pad[2]=S[20]&255|(S[21]&255)<<8,this.pad[3]=S[22]&255|(S[23]&255)<<8,this.pad[4]=S[24]&255|(S[25]&255)<<8,this.pad[5]=S[26]&255|(S[27]&255)<<8,this.pad[6]=S[28]&255|(S[29]&255)<<8,this.pad[7]=S[30]&255|(S[31]&255)<<8};M.prototype.blocks=function(S,B,R){for(var y=this.fin?0:2048,L,X,ee,ce,xe,He,ke,Rt,De,tt,st,ht,ut,nt,ct,it,Le,Ke,Ie,Ue=this.h[0],je=this.h[1],Te=this.h[2],ne=this.h[3],ie=this.h[4],he=this.h[5],ae=this.h[6],de=this.h[7],ge=this.h[8],Qe=this.h[9],pt=this.r[0],gt=this.r[1],mt=this.r[2],$=this.r[3],bt=this.r[4],Pt=this.r[5],Bt=this.r[6],xt=this.r[7],Tt=this.r[8],At=this.r[9];R>=16;)L=S[B+0]&255|(S[B+1]&255)<<8,Ue+=L&8191,X=S[B+2]&255|(S[B+3]&255)<<8,je+=(L>>>13|X<<3)&8191,ee=S[B+4]&255|(S[B+5]&255)<<8,Te+=(X>>>10|ee<<6)&8191,ce=S[B+6]&255|(S[B+7]&255)<<8,ne+=(ee>>>7|ce<<9)&8191,xe=S[B+8]&255|(S[B+9]&255)<<8,ie+=(ce>>>4|xe<<12)&8191,he+=xe>>>1&8191,He=S[B+10]&255|(S[B+11]&255)<<8,ae+=(xe>>>14|He<<2)&8191,ke=S[B+12]&255|(S[B+13]&255)<<8,de+=(He>>>11|ke<<5)&8191,Rt=S[B+14]&255|(S[B+15]&255)<<8,ge+=(ke>>>8|Rt<<8)&8191,Qe+=Rt>>>5|y,De=0,tt=De,tt+=Ue*pt,tt+=je*(5*At),tt+=Te*(5*Tt),tt+=ne*(5*xt),tt+=ie*(5*Bt),De=tt>>>13,tt&=8191,tt+=he*(5*Pt),tt+=ae*(5*bt),tt+=de*(5*$),tt+=ge*(5*mt),tt+=Qe*(5*gt),De+=tt>>>13,tt&=8191,st=De,st+=Ue*gt,st+=je*pt,st+=Te*(5*At),st+=ne*(5*Tt),st+=ie*(5*xt),De=st>>>13,st&=8191,st+=he*(5*Bt),st+=ae*(5*Pt),st+=de*(5*bt),st+=ge*(5*$),st+=Qe*(5*mt),De+=st>>>13,st&=8191,ht=De,ht+=Ue*mt,ht+=je*gt,ht+=Te*pt,ht+=ne*(5*At),ht+=ie*(5*Tt),De=ht>>>13,ht&=8191,ht+=he*(5*xt),ht+=ae*(5*Bt),ht+=de*(5*Pt),ht+=ge*(5*bt),ht+=Qe*(5*$),De+=ht>>>13,ht&=8191,ut=De,ut+=Ue*$,ut+=je*mt,ut+=Te*gt,ut+=ne*pt,ut+=ie*(5*At),De=ut>>>13,ut&=8191,ut+=he*(5*Tt),ut+=ae*(5*xt),ut+=de*(5*Bt),ut+=ge*(5*Pt),ut+=Qe*(5*bt),De+=ut>>>13,ut&=8191,nt=De,nt+=Ue*bt,nt+=je*$,nt+=Te*mt,nt+=ne*gt,nt+=ie*pt,De=nt>>>13,nt&=8191,nt+=he*(5*At),nt+=ae*(5*Tt),nt+=de*(5*xt),nt+=ge*(5*Bt),nt+=Qe*(5*Pt),De+=nt>>>13,nt&=8191,ct=De,ct+=Ue*Pt,ct+=je*bt,ct+=Te*$,ct+=ne*mt,ct+=ie*gt,De=ct>>>13,ct&=8191,ct+=he*pt,ct+=ae*(5*At),ct+=de*(5*Tt),ct+=ge*(5*xt),ct+=Qe*(5*Bt),De+=ct>>>13,ct&=8191,it=De,it+=Ue*Bt,it+=je*Pt,it+=Te*bt,it+=ne*$,it+=ie*mt,De=it>>>13,it&=8191,it+=he*gt,it+=ae*pt,it+=de*(5*At),it+=ge*(5*Tt),it+=Qe*(5*xt),De+=it>>>13,it&=8191,Le=De,Le+=Ue*xt,Le+=je*Bt,Le+=Te*Pt,Le+=ne*bt,Le+=ie*$,De=Le>>>13,Le&=8191,Le+=he*mt,Le+=ae*gt,Le+=de*pt,Le+=ge*(5*At),Le+=Qe*(5*Tt),De+=Le>>>13,Le&=8191,Ke=De,Ke+=Ue*Tt,Ke+=je*xt,Ke+=Te*Bt,Ke+=ne*Pt,Ke+=ie*bt,De=Ke>>>13,Ke&=8191,Ke+=he*$,Ke+=ae*mt,Ke+=de*gt,Ke+=ge*pt,Ke+=Qe*(5*At),De+=Ke>>>13,Ke&=8191,Ie=De,Ie+=Ue*At,Ie+=je*Tt,Ie+=Te*xt,Ie+=ne*Bt,Ie+=ie*Pt,De=Ie>>>13,Ie&=8191,Ie+=he*bt,Ie+=ae*$,Ie+=de*mt,Ie+=ge*gt,Ie+=Qe*pt,De+=Ie>>>13,Ie&=8191,De=(De<<2)+De|0,De=De+tt|0,tt=De&8191,De=De>>>13,st+=De,Ue=tt,je=st,Te=ht,ne=ut,ie=nt,he=ct,ae=it,de=Le,ge=Ke,Qe=Ie,B+=16,R-=16;this.h[0]=Ue,this.h[1]=je,this.h[2]=Te,this.h[3]=ne,this.h[4]=ie,this.h[5]=he,this.h[6]=ae,this.h[7]=de,this.h[8]=ge,this.h[9]=Qe},M.prototype.finish=function(S,B){var R=new Uint16Array(10),y,L,X,ee;if(this.leftover){for(ee=this.leftover,this.buffer[ee++]=1;ee<16;ee++)this.buffer[ee]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(y=this.h[1]>>>13,this.h[1]&=8191,ee=2;ee<10;ee++)this.h[ee]+=y,y=this.h[ee]>>>13,this.h[ee]&=8191;for(this.h[0]+=y*5,y=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=y,y=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=y,R[0]=this.h[0]+5,y=R[0]>>>13,R[0]&=8191,ee=1;ee<10;ee++)R[ee]=this.h[ee]+y,y=R[ee]>>>13,R[ee]&=8191;for(R[9]-=8192,L=(y^1)-1,ee=0;ee<10;ee++)R[ee]&=L;for(L=~L,ee=0;ee<10;ee++)this.h[ee]=this.h[ee]&L|R[ee];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,X=this.h[0]+this.pad[0],this.h[0]=X&65535,ee=1;ee<8;ee++)X=(this.h[ee]+this.pad[ee]|0)+(X>>>16)|0,this.h[ee]=X&65535;S[B+0]=this.h[0]>>>0&255,S[B+1]=this.h[0]>>>8&255,S[B+2]=this.h[1]>>>0&255,S[B+3]=this.h[1]>>>8&255,S[B+4]=this.h[2]>>>0&255,S[B+5]=this.h[2]>>>8&255,S[B+6]=this.h[3]>>>0&255,S[B+7]=this.h[3]>>>8&255,S[B+8]=this.h[4]>>>0&255,S[B+9]=this.h[4]>>>8&255,S[B+10]=this.h[5]>>>0&255,S[B+11]=this.h[5]>>>8&255,S[B+12]=this.h[6]>>>0&255,S[B+13]=this.h[6]>>>8&255,S[B+14]=this.h[7]>>>0&255,S[B+15]=this.h[7]>>>8&255},M.prototype.update=function(S,B,R){var y,L;if(this.leftover){for(L=16-this.leftover,L>R&&(L=R),y=0;y<L;y++)this.buffer[this.leftover+y]=S[B+y];if(R-=L,B+=L,this.leftover+=L,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(R>=16&&(L=R-R%16,this.blocks(S,B,L),B+=L,R-=L),R){for(y=0;y<R;y++)this.buffer[this.leftover+y]=S[B+y];this.leftover+=R}};function V(S,B,R,y,L,X){var ee=new M(X);return ee.update(R,y,L),ee.finish(S,B),0}function Y(S,B,R,y,L,X){var ee=new Uint8Array(16);return V(ee,0,R,y,L,X),v(S,B,ee,0)}function H(S,B,R,y,L){var X;if(R<32)return-1;for(A(S,0,B,0,R,y,L),V(S,16,S,32,R-32,S),X=0;X<16;X++)S[X]=0;return 0}function F(S,B,R,y,L){var X,ee=new Uint8Array(32);if(R<32||(_(ee,0,32,y,L),Y(B,16,B,32,R-32,ee)!==0))return-1;for(A(S,0,B,0,R,y,L),X=0;X<32;X++)S[X]=0;return 0}function K(S,B){var R;for(R=0;R<16;R++)S[R]=B[R]|0}function I(S){var B,R,y=1;for(B=0;B<16;B++)R=S[B]+y+65535,y=Math.floor(R/65536),S[B]=R-y*65536;S[0]+=y-1+37*(y-1)}function G(S,B,R){for(var y,L=~(R-1),X=0;X<16;X++)y=L&(S[X]^B[X]),S[X]^=y,B[X]^=y}function se(S,B){var R,y,L,X=e(),ee=e();for(R=0;R<16;R++)ee[R]=B[R];for(I(ee),I(ee),I(ee),y=0;y<2;y++){for(X[0]=ee[0]-65517,R=1;R<15;R++)X[R]=ee[R]-65535-(X[R-1]>>16&1),X[R-1]&=65535;X[15]=ee[15]-32767-(X[14]>>16&1),L=X[15]>>16&1,X[14]&=65535,G(ee,X,1-L)}for(R=0;R<16;R++)S[2*R]=ee[R]&255,S[2*R+1]=ee[R]>>8}function D(S,B){var R=new Uint8Array(32),y=new Uint8Array(32);return se(R,S),se(y,B),p(R,0,y,0)}function O(S){var B=new Uint8Array(32);return se(B,S),B[0]&1}function W(S,B){var R;for(R=0;R<16;R++)S[R]=B[2*R]+(B[2*R+1]<<8);S[15]&=32767}function q(S,B,R){for(var y=0;y<16;y++)S[y]=B[y]+R[y]}function Q(S,B,R){for(var y=0;y<16;y++)S[y]=B[y]-R[y]}function pe(S,B,R){var y,L,X=0,ee=0,ce=0,xe=0,He=0,ke=0,Rt=0,De=0,tt=0,st=0,ht=0,ut=0,nt=0,ct=0,it=0,Le=0,Ke=0,Ie=0,Ue=0,je=0,Te=0,ne=0,ie=0,he=0,ae=0,de=0,ge=0,Qe=0,pt=0,gt=0,mt=0,$=R[0],bt=R[1],Pt=R[2],Bt=R[3],xt=R[4],Tt=R[5],At=R[6],dr=R[7],Lt=R[8],sr=R[9],nr=R[10],ir=R[11],gr=R[12],Vr=R[13],qr=R[14],zr=R[15];y=B[0],X+=y*$,ee+=y*bt,ce+=y*Pt,xe+=y*Bt,He+=y*xt,ke+=y*Tt,Rt+=y*At,De+=y*dr,tt+=y*Lt,st+=y*sr,ht+=y*nr,ut+=y*ir,nt+=y*gr,ct+=y*Vr,it+=y*qr,Le+=y*zr,y=B[1],ee+=y*$,ce+=y*bt,xe+=y*Pt,He+=y*Bt,ke+=y*xt,Rt+=y*Tt,De+=y*At,tt+=y*dr,st+=y*Lt,ht+=y*sr,ut+=y*nr,nt+=y*ir,ct+=y*gr,it+=y*Vr,Le+=y*qr,Ke+=y*zr,y=B[2],ce+=y*$,xe+=y*bt,He+=y*Pt,ke+=y*Bt,Rt+=y*xt,De+=y*Tt,tt+=y*At,st+=y*dr,ht+=y*Lt,ut+=y*sr,nt+=y*nr,ct+=y*ir,it+=y*gr,Le+=y*Vr,Ke+=y*qr,Ie+=y*zr,y=B[3],xe+=y*$,He+=y*bt,ke+=y*Pt,Rt+=y*Bt,De+=y*xt,tt+=y*Tt,st+=y*At,ht+=y*dr,ut+=y*Lt,nt+=y*sr,ct+=y*nr,it+=y*ir,Le+=y*gr,Ke+=y*Vr,Ie+=y*qr,Ue+=y*zr,y=B[4],He+=y*$,ke+=y*bt,Rt+=y*Pt,De+=y*Bt,tt+=y*xt,st+=y*Tt,ht+=y*At,ut+=y*dr,nt+=y*Lt,ct+=y*sr,it+=y*nr,Le+=y*ir,Ke+=y*gr,Ie+=y*Vr,Ue+=y*qr,je+=y*zr,y=B[5],ke+=y*$,Rt+=y*bt,De+=y*Pt,tt+=y*Bt,st+=y*xt,ht+=y*Tt,ut+=y*At,nt+=y*dr,ct+=y*Lt,it+=y*sr,Le+=y*nr,Ke+=y*ir,Ie+=y*gr,Ue+=y*Vr,je+=y*qr,Te+=y*zr,y=B[6],Rt+=y*$,De+=y*bt,tt+=y*Pt,st+=y*Bt,ht+=y*xt,ut+=y*Tt,nt+=y*At,ct+=y*dr,it+=y*Lt,Le+=y*sr,Ke+=y*nr,Ie+=y*ir,Ue+=y*gr,je+=y*Vr,Te+=y*qr,ne+=y*zr,y=B[7],De+=y*$,tt+=y*bt,st+=y*Pt,ht+=y*Bt,ut+=y*xt,nt+=y*Tt,ct+=y*At,it+=y*dr,Le+=y*Lt,Ke+=y*sr,Ie+=y*nr,Ue+=y*ir,je+=y*gr,Te+=y*Vr,ne+=y*qr,ie+=y*zr,y=B[8],tt+=y*$,st+=y*bt,ht+=y*Pt,ut+=y*Bt,nt+=y*xt,ct+=y*Tt,it+=y*At,Le+=y*dr,Ke+=y*Lt,Ie+=y*sr,Ue+=y*nr,je+=y*ir,Te+=y*gr,ne+=y*Vr,ie+=y*qr,he+=y*zr,y=B[9],st+=y*$,ht+=y*bt,ut+=y*Pt,nt+=y*Bt,ct+=y*xt,it+=y*Tt,Le+=y*At,Ke+=y*dr,Ie+=y*Lt,Ue+=y*sr,je+=y*nr,Te+=y*ir,ne+=y*gr,ie+=y*Vr,he+=y*qr,ae+=y*zr,y=B[10],ht+=y*$,ut+=y*bt,nt+=y*Pt,ct+=y*Bt,it+=y*xt,Le+=y*Tt,Ke+=y*At,Ie+=y*dr,Ue+=y*Lt,je+=y*sr,Te+=y*nr,ne+=y*ir,ie+=y*gr,he+=y*Vr,ae+=y*qr,de+=y*zr,y=B[11],ut+=y*$,nt+=y*bt,ct+=y*Pt,it+=y*Bt,Le+=y*xt,Ke+=y*Tt,Ie+=y*At,Ue+=y*dr,je+=y*Lt,Te+=y*sr,ne+=y*nr,ie+=y*ir,he+=y*gr,ae+=y*Vr,de+=y*qr,ge+=y*zr,y=B[12],nt+=y*$,ct+=y*bt,it+=y*Pt,Le+=y*Bt,Ke+=y*xt,Ie+=y*Tt,Ue+=y*At,je+=y*dr,Te+=y*Lt,ne+=y*sr,ie+=y*nr,he+=y*ir,ae+=y*gr,de+=y*Vr,ge+=y*qr,Qe+=y*zr,y=B[13],ct+=y*$,it+=y*bt,Le+=y*Pt,Ke+=y*Bt,Ie+=y*xt,Ue+=y*Tt,je+=y*At,Te+=y*dr,ne+=y*Lt,ie+=y*sr,he+=y*nr,ae+=y*ir,de+=y*gr,ge+=y*Vr,Qe+=y*qr,pt+=y*zr,y=B[14],it+=y*$,Le+=y*bt,Ke+=y*Pt,Ie+=y*Bt,Ue+=y*xt,je+=y*Tt,Te+=y*At,ne+=y*dr,ie+=y*Lt,he+=y*sr,ae+=y*nr,de+=y*ir,ge+=y*gr,Qe+=y*Vr,pt+=y*qr,gt+=y*zr,y=B[15],Le+=y*$,Ke+=y*bt,Ie+=y*Pt,Ue+=y*Bt,je+=y*xt,Te+=y*Tt,ne+=y*At,ie+=y*dr,he+=y*Lt,ae+=y*sr,de+=y*nr,ge+=y*ir,Qe+=y*gr,pt+=y*Vr,gt+=y*qr,mt+=y*zr,X+=38*Ke,ee+=38*Ie,ce+=38*Ue,xe+=38*je,He+=38*Te,ke+=38*ne,Rt+=38*ie,De+=38*he,tt+=38*ae,st+=38*de,ht+=38*ge,ut+=38*Qe,nt+=38*pt,ct+=38*gt,it+=38*mt,L=1,y=X+L+65535,L=Math.floor(y/65536),X=y-L*65536,y=ee+L+65535,L=Math.floor(y/65536),ee=y-L*65536,y=ce+L+65535,L=Math.floor(y/65536),ce=y-L*65536,y=xe+L+65535,L=Math.floor(y/65536),xe=y-L*65536,y=He+L+65535,L=Math.floor(y/65536),He=y-L*65536,y=ke+L+65535,L=Math.floor(y/65536),ke=y-L*65536,y=Rt+L+65535,L=Math.floor(y/65536),Rt=y-L*65536,y=De+L+65535,L=Math.floor(y/65536),De=y-L*65536,y=tt+L+65535,L=Math.floor(y/65536),tt=y-L*65536,y=st+L+65535,L=Math.floor(y/65536),st=y-L*65536,y=ht+L+65535,L=Math.floor(y/65536),ht=y-L*65536,y=ut+L+65535,L=Math.floor(y/65536),ut=y-L*65536,y=nt+L+65535,L=Math.floor(y/65536),nt=y-L*65536,y=ct+L+65535,L=Math.floor(y/65536),ct=y-L*65536,y=it+L+65535,L=Math.floor(y/65536),it=y-L*65536,y=Le+L+65535,L=Math.floor(y/65536),Le=y-L*65536,X+=L-1+37*(L-1),L=1,y=X+L+65535,L=Math.floor(y/65536),X=y-L*65536,y=ee+L+65535,L=Math.floor(y/65536),ee=y-L*65536,y=ce+L+65535,L=Math.floor(y/65536),ce=y-L*65536,y=xe+L+65535,L=Math.floor(y/65536),xe=y-L*65536,y=He+L+65535,L=Math.floor(y/65536),He=y-L*65536,y=ke+L+65535,L=Math.floor(y/65536),ke=y-L*65536,y=Rt+L+65535,L=Math.floor(y/65536),Rt=y-L*65536,y=De+L+65535,L=Math.floor(y/65536),De=y-L*65536,y=tt+L+65535,L=Math.floor(y/65536),tt=y-L*65536,y=st+L+65535,L=Math.floor(y/65536),st=y-L*65536,y=ht+L+65535,L=Math.floor(y/65536),ht=y-L*65536,y=ut+L+65535,L=Math.floor(y/65536),ut=y-L*65536,y=nt+L+65535,L=Math.floor(y/65536),nt=y-L*65536,y=ct+L+65535,L=Math.floor(y/65536),ct=y-L*65536,y=it+L+65535,L=Math.floor(y/65536),it=y-L*65536,y=Le+L+65535,L=Math.floor(y/65536),Le=y-L*65536,X+=L-1+37*(L-1),S[0]=X,S[1]=ee,S[2]=ce,S[3]=xe,S[4]=He,S[5]=ke,S[6]=Rt,S[7]=De,S[8]=tt,S[9]=st,S[10]=ht,S[11]=ut,S[12]=nt,S[13]=ct,S[14]=it,S[15]=Le}function ve(S,B){pe(S,B,B)}function at(S,B){var R=e(),y;for(y=0;y<16;y++)R[y]=B[y];for(y=253;y>=0;y--)ve(R,R),y!==2&&y!==4&&pe(R,R,B);for(y=0;y<16;y++)S[y]=R[y]}function yt(S,B){var R=e(),y;for(y=0;y<16;y++)R[y]=B[y];for(y=250;y>=0;y--)ve(R,R),y!==1&&pe(R,R,B);for(y=0;y<16;y++)S[y]=R[y]}function Dt(S,B,R){var y=new Uint8Array(32),L=new Float64Array(80),X,ee,ce=e(),xe=e(),He=e(),ke=e(),Rt=e(),De=e();for(ee=0;ee<31;ee++)y[ee]=B[ee];for(y[31]=B[31]&127|64,y[0]&=248,W(L,R),ee=0;ee<16;ee++)xe[ee]=L[ee],ke[ee]=ce[ee]=He[ee]=0;for(ce[0]=ke[0]=1,ee=254;ee>=0;--ee)X=y[ee>>>3]>>>(ee&7)&1,G(ce,xe,X),G(He,ke,X),q(Rt,ce,He),Q(ce,ce,He),q(He,xe,ke),Q(xe,xe,ke),ve(ke,Rt),ve(De,ce),pe(ce,He,ce),pe(He,xe,Rt),q(Rt,ce,He),Q(ce,ce,He),ve(xe,ce),Q(He,ke,De),pe(ce,He,a),q(ce,ce,ke),pe(He,He,ce),pe(ce,ke,De),pe(ke,xe,L),ve(xe,Rt),G(ce,xe,X),G(He,ke,X);for(ee=0;ee<16;ee++)L[ee+16]=ce[ee],L[ee+32]=He[ee],L[ee+48]=xe[ee],L[ee+64]=ke[ee];var tt=L.subarray(32),st=L.subarray(16);return at(tt,tt),pe(st,st,tt),se(S,st),0}function vt(S,B){return Dt(S,B,n)}function Ot(S,B){return r(B,32),vt(S,B)}function Ms(S,B,R){var y=new Uint8Array(32);return Dt(y,R,B),P(S,s,y,j)}var js=H,tc=F;function W1(S,B,R,y,L,X){var ee=new Uint8Array(32);return Ms(ee,L,X),js(S,B,R,y,ee)}function gf(S,B,R,y,L,X){var ee=new Uint8Array(32);return Ms(ee,L,X),tc(S,B,R,y,ee)}var yf=[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 xf(S,B,R,y){for(var L=new Int32Array(16),X=new Int32Array(16),ee,ce,xe,He,ke,Rt,De,tt,st,ht,ut,nt,ct,it,Le,Ke,Ie,Ue,je,Te,ne,ie,he,ae,de,ge,Qe=S[0],pt=S[1],gt=S[2],mt=S[3],$=S[4],bt=S[5],Pt=S[6],Bt=S[7],xt=B[0],Tt=B[1],At=B[2],dr=B[3],Lt=B[4],sr=B[5],nr=B[6],ir=B[7],gr=0;y>=128;){for(je=0;je<16;je++)Te=8*je+gr,L[je]=R[Te+0]<<24|R[Te+1]<<16|R[Te+2]<<8|R[Te+3],X[je]=R[Te+4]<<24|R[Te+5]<<16|R[Te+6]<<8|R[Te+7];for(je=0;je<80;je++)if(ee=Qe,ce=pt,xe=gt,He=mt,ke=$,Rt=bt,De=Pt,tt=Bt,st=xt,ht=Tt,ut=At,nt=dr,ct=Lt,it=sr,Le=nr,Ke=ir,ne=Bt,ie=ir,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=($>>>14|Lt<<18)^($>>>18|Lt<<14)^(Lt>>>9|$<<23),ie=(Lt>>>14|$<<18)^(Lt>>>18|$<<14)^($>>>9|Lt<<23),he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ne=$&bt^~$&Pt,ie=Lt&sr^~Lt&nr,he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ne=yf[je*2],ie=yf[je*2+1],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ne=L[je%16],ie=X[je%16],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,Ie=de&65535|ge<<16,Ue=he&65535|ae<<16,ne=Ie,ie=Ue,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=(Qe>>>28|xt<<4)^(xt>>>2|Qe<<30)^(xt>>>7|Qe<<25),ie=(xt>>>28|Qe<<4)^(Qe>>>2|xt<<30)^(Qe>>>7|xt<<25),he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ne=Qe&pt^Qe&gt^pt&gt,ie=xt&Tt^xt&At^Tt&At,he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,tt=de&65535|ge<<16,Ke=he&65535|ae<<16,ne=He,ie=nt,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=Ie,ie=Ue,he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,He=de&65535|ge<<16,nt=he&65535|ae<<16,pt=ee,gt=ce,mt=xe,$=He,bt=ke,Pt=Rt,Bt=De,Qe=tt,Tt=st,At=ht,dr=ut,Lt=nt,sr=ct,nr=it,ir=Le,xt=Ke,je%16===15)for(Te=0;Te<16;Te++)ne=L[Te],ie=X[Te],he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=L[(Te+9)%16],ie=X[(Te+9)%16],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,Ie=L[(Te+1)%16],Ue=X[(Te+1)%16],ne=(Ie>>>1|Ue<<31)^(Ie>>>8|Ue<<24)^Ie>>>7,ie=(Ue>>>1|Ie<<31)^(Ue>>>8|Ie<<24)^(Ue>>>7|Ie<<25),he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,Ie=L[(Te+14)%16],Ue=X[(Te+14)%16],ne=(Ie>>>19|Ue<<13)^(Ue>>>29|Ie<<3)^Ie>>>6,ie=(Ue>>>19|Ie<<13)^(Ie>>>29|Ue<<3)^(Ue>>>6|Ie<<26),he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,L[Te]=de&65535|ge<<16,X[Te]=he&65535|ae<<16;ne=Qe,ie=xt,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[0],ie=B[0],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[0]=Qe=de&65535|ge<<16,B[0]=xt=he&65535|ae<<16,ne=pt,ie=Tt,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[1],ie=B[1],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[1]=pt=de&65535|ge<<16,B[1]=Tt=he&65535|ae<<16,ne=gt,ie=At,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[2],ie=B[2],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[2]=gt=de&65535|ge<<16,B[2]=At=he&65535|ae<<16,ne=mt,ie=dr,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[3],ie=B[3],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[3]=mt=de&65535|ge<<16,B[3]=dr=he&65535|ae<<16,ne=$,ie=Lt,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[4],ie=B[4],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[4]=$=de&65535|ge<<16,B[4]=Lt=he&65535|ae<<16,ne=bt,ie=sr,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[5],ie=B[5],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[5]=bt=de&65535|ge<<16,B[5]=sr=he&65535|ae<<16,ne=Pt,ie=nr,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[6],ie=B[6],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[6]=Pt=de&65535|ge<<16,B[6]=nr=he&65535|ae<<16,ne=Bt,ie=ir,he=ie&65535,ae=ie>>>16,de=ne&65535,ge=ne>>>16,ne=S[7],ie=B[7],he+=ie&65535,ae+=ie>>>16,de+=ne&65535,ge+=ne>>>16,ae+=he>>>16,de+=ae>>>16,ge+=de>>>16,S[7]=Bt=de&65535|ge<<16,B[7]=ir=he&65535|ae<<16,gr+=128,y-=128}return y}function Fn(S,B,R){var y=new Int32Array(8),L=new Int32Array(8),X=new Uint8Array(256),ee,ce=R;for(y[0]=1779033703,y[1]=3144134277,y[2]=1013904242,y[3]=2773480762,y[4]=1359893119,y[5]=2600822924,y[6]=528734635,y[7]=1541459225,L[0]=4089235720,L[1]=2227873595,L[2]=4271175723,L[3]=1595750129,L[4]=2917565137,L[5]=725511199,L[6]=4215389547,L[7]=327033209,xf(y,L,B,R),R%=128,ee=0;ee<R;ee++)X[ee]=B[ce-R+ee];for(X[R]=128,R=256-128*(R<112?1:0),X[R-9]=0,h(X,R-8,ce/536870912|0,ce<<3),xf(y,L,X,R),ee=0;ee<8;ee++)h(S,8*ee,y[ee],L[ee]);return 0}function rc(S,B){var R=e(),y=e(),L=e(),X=e(),ee=e(),ce=e(),xe=e(),He=e(),ke=e();Q(R,S[1],S[0]),Q(ke,B[1],B[0]),pe(R,R,ke),q(y,S[0],S[1]),q(ke,B[0],B[1]),pe(y,y,ke),pe(L,S[3],B[3]),pe(L,L,d),pe(X,S[2],B[2]),q(X,X,X),Q(ee,y,R),Q(ce,X,L),q(xe,X,L),q(He,y,R),pe(S[0],ee,ce),pe(S[1],He,xe),pe(S[2],xe,ce),pe(S[3],ee,He)}function bf(S,B,R){var y;for(y=0;y<4;y++)G(S[y],B[y],R)}function sc(S,B){var R=e(),y=e(),L=e();at(L,B[2]),pe(R,B[0],L),pe(y,B[1],L),se(S,y),S[31]^=O(R)<<7}function wf(S,B,R){var y,L;for(K(S[0],i),K(S[1],o),K(S[2],o),K(S[3],i),L=255;L>=0;--L)y=R[L/8|0]>>(L&7)&1,bf(S,B,y),rc(B,S),rc(S,S),bf(S,B,y)}function Jd(S,B){var R=[e(),e(),e(),e()];K(R[0],u),K(R[1],l),K(R[2],o),pe(R[3],u,l),wf(S,R,B)}function vf(S,B,R){var y=new Uint8Array(64),L=[e(),e(),e(),e()],X;for(R||r(B,32),Fn(y,B,32),y[0]&=248,y[31]&=127,y[31]|=64,Jd(L,y),sc(S,L),X=0;X<32;X++)B[X+32]=S[X];return 0}var Qd=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 Ri(S,B){var R,y,L,X;for(y=63;y>=32;--y){for(R=0,L=y-32,X=y-12;L<X;++L)B[L]+=R-16*B[y]*Qd[L-(y-32)],R=Math.floor((B[L]+128)/256),B[L]-=R*256;B[L]+=R,B[y]=0}for(R=0,L=0;L<32;L++)B[L]+=R-(B[31]>>4)*Qd[L],R=B[L]>>8,B[L]&=255;for(L=0;L<32;L++)B[L]-=R*Qd[L];for(y=0;y<32;y++)B[y+1]+=B[y]>>8,S[y]=B[y]&255}function _f(S){var B=new Float64Array(64),R;for(R=0;R<64;R++)B[R]=S[R];for(R=0;R<64;R++)S[R]=0;Ri(S,B)}function km(S,B,R,y){var L=new Uint8Array(64),X=new Uint8Array(64),ee=new Uint8Array(64),ce,xe,He=new Float64Array(64),ke=[e(),e(),e(),e()];Fn(L,y,32),L[0]&=248,L[31]&=127,L[31]|=64;var Rt=R+64;for(ce=0;ce<R;ce++)S[64+ce]=B[ce];for(ce=0;ce<32;ce++)S[32+ce]=L[32+ce];for(Fn(ee,S.subarray(32),R+32),_f(ee),Jd(ke,ee),sc(S,ke),ce=32;ce<64;ce++)S[ce]=y[ce];for(Fn(X,S,R+64),_f(X),ce=0;ce<64;ce++)He[ce]=0;for(ce=0;ce<32;ce++)He[ce]=ee[ce];for(ce=0;ce<32;ce++)for(xe=0;xe<32;xe++)He[ce+xe]+=X[ce]*L[xe];return Ri(S.subarray(32),He),Rt}function G1(S,B){var R=e(),y=e(),L=e(),X=e(),ee=e(),ce=e(),xe=e();return K(S[2],o),W(S[1],B),ve(L,S[1]),pe(X,L,c),Q(L,L,S[2]),q(X,S[2],X),ve(ee,X),ve(ce,ee),pe(xe,ce,ee),pe(R,xe,L),pe(R,R,X),yt(R,R),pe(R,R,L),pe(R,R,X),pe(R,R,X),pe(S[0],R,X),ve(y,S[0]),pe(y,y,X),D(y,L)&&pe(S[0],S[0],f),ve(y,S[0]),pe(y,y,X),D(y,L)?-1:(O(S[0])===B[31]>>7&&Q(S[0],i,S[0]),pe(S[3],S[0],S[1]),0)}function nc(S,B,R,y){var L,X=new Uint8Array(32),ee=new Uint8Array(64),ce=[e(),e(),e(),e()],xe=[e(),e(),e(),e()];if(R<64||G1(xe,y))return-1;for(L=0;L<R;L++)S[L]=B[L];for(L=0;L<32;L++)S[L+32]=y[L];if(Fn(ee,S,R),_f(ee),wf(ce,xe,ee),Jd(xe,B.subarray(32)),rc(ce,xe),sc(X,ce),R-=64,p(B,0,X,0)){for(L=0;L<R;L++)S[L]=0;return-1}for(L=0;L<R;L++)S[L]=B[L+64];return R}var J=32,te=24,oe=32,ye=16,$e=32,Ht=32,Kt=32,lt=32,Se=32,Re=te,Oe=oe,Me=ye,rt=64,It=32,Mt=64,es=32,Zd=64;t.lowlevel={crypto_core_hsalsa20:P,crypto_stream_xor:A,crypto_stream:_,crypto_stream_salsa20_xor:T,crypto_stream_salsa20:k,crypto_onetimeauth:V,crypto_onetimeauth_verify:Y,crypto_verify_16:v,crypto_verify_32:p,crypto_secretbox:H,crypto_secretbox_open:F,crypto_scalarmult:Dt,crypto_scalarmult_base:vt,crypto_box_beforenm:Ms,crypto_box_afternm:js,crypto_box:W1,crypto_box_open:gf,crypto_box_keypair:Ot,crypto_hash:Fn,crypto_sign:km,crypto_sign_keypair:vf,crypto_sign_open:nc,crypto_secretbox_KEYBYTES:J,crypto_secretbox_NONCEBYTES:te,crypto_secretbox_ZEROBYTES:oe,crypto_secretbox_BOXZEROBYTES:ye,crypto_scalarmult_BYTES:$e,crypto_scalarmult_SCALARBYTES:Ht,crypto_box_PUBLICKEYBYTES:Kt,crypto_box_SECRETKEYBYTES:lt,crypto_box_BEFORENMBYTES:Se,crypto_box_NONCEBYTES:Re,crypto_box_ZEROBYTES:Oe,crypto_box_BOXZEROBYTES:Me,crypto_sign_BYTES:rt,crypto_sign_PUBLICKEYBYTES:It,crypto_sign_SECRETKEYBYTES:Mt,crypto_sign_SEEDBYTES:es,crypto_hash_BYTES:Zd,gf:e,D:c,L:Qd,pack25519:se,unpack25519:W,M:pe,A:q,S:ve,Z:Q,pow2523:yt,add:rc,set25519:K,modL:Ri,scalarmult:wf,scalarbase:Jd};function Im(S,B){if(S.length!==J)throw new Error("bad key size");if(B.length!==te)throw new Error("bad nonce size")}function X1(S,B){if(S.length!==Kt)throw new Error("bad public key size");if(B.length!==lt)throw new Error("bad secret key size")}function Ts(){for(var S=0;S<arguments.length;S++)if(!(arguments[S]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function KA(S){for(var B=0;B<S.length;B++)S[B]=0}t.randomBytes=function(S){var B=new Uint8Array(S);return r(B,S),B},t.secretbox=function(S,B,R){Ts(S,B,R),Im(R,B);for(var y=new Uint8Array(oe+S.length),L=new Uint8Array(y.length),X=0;X<S.length;X++)y[X+oe]=S[X];return H(L,y,y.length,B,R),L.subarray(ye)},t.secretbox.open=function(S,B,R){Ts(S,B,R),Im(R,B);for(var y=new Uint8Array(ye+S.length),L=new Uint8Array(y.length),X=0;X<S.length;X++)y[X+ye]=S[X];return y.length<32||F(L,y,y.length,B,R)!==0?null:L.subarray(oe)},t.secretbox.keyLength=J,t.secretbox.nonceLength=te,t.secretbox.overheadLength=ye,t.scalarMult=function(S,B){if(Ts(S,B),S.length!==Ht)throw new Error("bad n size");if(B.length!==$e)throw new Error("bad p size");var R=new Uint8Array($e);return Dt(R,S,B),R},t.scalarMult.base=function(S){if(Ts(S),S.length!==Ht)throw new Error("bad n size");var B=new Uint8Array($e);return vt(B,S),B},t.scalarMult.scalarLength=Ht,t.scalarMult.groupElementLength=$e,t.box=function(S,B,R,y){var L=t.box.before(R,y);return t.secretbox(S,B,L)},t.box.before=function(S,B){Ts(S,B),X1(S,B);var R=new Uint8Array(Se);return Ms(R,S,B),R},t.box.after=t.secretbox,t.box.open=function(S,B,R,y){var L=t.box.before(R,y);return t.secretbox.open(S,B,L)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var S=new Uint8Array(Kt),B=new Uint8Array(lt);return Ot(S,B),{publicKey:S,secretKey:B}},t.box.keyPair.fromSecretKey=function(S){if(Ts(S),S.length!==lt)throw new Error("bad secret key size");var B=new Uint8Array(Kt);return vt(B,S),{publicKey:B,secretKey:new Uint8Array(S)}},t.box.publicKeyLength=Kt,t.box.secretKeyLength=lt,t.box.sharedKeyLength=Se,t.box.nonceLength=Re,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(S,B){if(Ts(S,B),B.length!==Mt)throw new Error("bad secret key size");var R=new Uint8Array(rt+S.length);return km(R,S,S.length,B),R},t.sign.open=function(S,B){if(Ts(S,B),B.length!==It)throw new Error("bad public key size");var R=new Uint8Array(S.length),y=nc(R,S,S.length,B);if(y<0)return null;for(var L=new Uint8Array(y),X=0;X<L.length;X++)L[X]=R[X];return L},t.sign.detached=function(S,B){for(var R=t.sign(S,B),y=new Uint8Array(rt),L=0;L<y.length;L++)y[L]=R[L];return y},t.sign.detached.verify=function(S,B,R){if(Ts(S,B,R),B.length!==rt)throw new Error("bad signature size");if(R.length!==It)throw new Error("bad public key size");var y=new Uint8Array(rt+S.length),L=new Uint8Array(rt+S.length),X;for(X=0;X<rt;X++)y[X]=B[X];for(X=0;X<S.length;X++)y[X+rt]=S[X];return nc(L,y,y.length,R)>=0},t.sign.keyPair=function(){var S=new Uint8Array(It),B=new Uint8Array(Mt);return vf(S,B),{publicKey:S,secretKey:B}},t.sign.keyPair.fromSecretKey=function(S){if(Ts(S),S.length!==Mt)throw new Error("bad secret key size");for(var B=new Uint8Array(It),R=0;R<B.length;R++)B[R]=S[32+R];return{publicKey:B,secretKey:new Uint8Array(S)}},t.sign.keyPair.fromSeed=function(S){if(Ts(S),S.length!==es)throw new Error("bad seed size");for(var B=new Uint8Array(It),R=new Uint8Array(Mt),y=0;y<32;y++)R[y]=S[y];return vf(B,R,!0),{publicKey:B,secretKey:R}},t.sign.publicKeyLength=It,t.sign.secretKeyLength=Mt,t.sign.seedLength=es,t.sign.signatureLength=rt,t.hash=function(S){Ts(S);var B=new Uint8Array(Zd);return Fn(B,S,S.length),B},t.hash.hashLength=Zd,t.verify=function(S,B){return Ts(S,B),S.length===0||B.length===0||S.length!==B.length?!1:m(S,0,B,0,S.length)===0},t.setPRNG=function(S){r=S},(function(){var S=typeof self<"u"?self.crypto||self.msCrypto:null;if(S&&S.getRandomValues){var B=65536;t.setPRNG(function(R,y){var L,X=new Uint8Array(y);for(L=0;L<y;L+=B)S.getRandomValues(X.subarray(L,L+Math.min(y-L,B)));for(L=0;L<y;L++)R[L]=X[L];KA(X)})}else typeof require<"u"&&(S=require("crypto"),S&&S.randomBytes&&t.setPRNG(function(R,y){var L,X=S.randomBytes(y);for(L=0;L<y;L++)R[L]=X[L];KA(X)}))})()})(typeof Fg<"u"&&Fg.exports?Fg.exports:self.nacl=self.nacl||{})});var kv=Ne(Av=>{"use strict";g();Object.defineProperty(Av,"__esModule",{value:!0});var Tv=class{constructor(e,r=0,s=0){this.start=r,this.end=s>r?s:r,this.buf=e}get length(){return this.buf.length}reset(e=0,r=0){return this.start=e,r>=this.start?this.end=r:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,r="Too few bytes to parse."){let s=this.end+e;if(s>this.buf.length){let n=new Error(r);throw n.available=this.buf.length,n.requested=s,n}return this.walk(0),this}mustWalk(e,r){return this.mustHas(e,r),this.walk(e),this}};Av.BufferVisitor=Tv});var b3=Ne(Bv=>{"use strict";g();Object.defineProperty(Bv,"__esModule",{value:!0});var y3=require("util"),x3=64,Rv="-----BEGIN ",Pv="-----END ",Zf="-----",Iv="Proc-Type",$g=class{static parse(e){let r=[],s=e.toString("utf8").split(`
12
+ `).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#"));for(;s.length>0;)r.push(_q(s));if(r.length===0)throw new Error("PEM: no block");return r}constructor(e,r){this.type=e,this.body=r,this.headers=Object.create(null)}get procType(){return this.getHeader(Iv)}getHeader(e){let r=this.headers[e];return r??""}setHeader(e,r){if(e.includes(":"))throw new Error("pem: cannot encode a header key that contains a colon");if(e===""||r==="")throw new Error("pem: invalid header key or value");this.headers[e]=r}toString(){let e=Rv+this.type+Zf+`
13
+ `,r=Object.keys(this.headers);if(r.length>0){let i=this.procType;i!==""&&(e+=`${Iv}: ${i}
14
+ `),r.sort();for(let o of r)o!==Iv&&(e+=`${o}: ${this.headers[o]}
15
+ `);e+=`
16
+ `}let s=this.body.toString("base64"),n=0;for(;n<s.length;)e+=s.slice(n,n+x3)+`
17
+ `,n+=x3;return e+=Pv+this.type+Zf+`
18
+ `,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[y3.inspect.custom](e,r){return`<${this.constructor.name} ${y3.inspect(this.toJSON(),r)}>`}};Bv.PEM=$g;function _q(t){let e=t.shift();if(e==null||!e.startsWith(Rv)||!e.endsWith(Zf))throw new Error("pem: invalid BEGIN line");let r=e.slice(Rv.length,e.length-Zf.length);if(r==="")throw new Error("pem: invalid type");let s=[];for(e=t.shift();e!=null&&e.includes(": ");){let o=e.split(": ");if(o.length!==2||o[0]===""||o[1]==="")throw new Error("pem: invalid Header line");s.push(o),e=t.shift()}let n="";for(;e!=null&&!e.startsWith(Pv);)n+=e,e=t.shift();if(e==null||e!==`${Pv}${r}${Zf}`)throw new Error("pem: invalid END line");let i=new $g(r,Buffer.from(n,"base64"));if(n===""||i.body.toString("base64")!==n)throw new Error("pem: invalid base64 body");for(let o of s)i.setHeader(o[0],o[1]);return i}});var S3=Ne(Xo=>{"use strict";g();Object.defineProperty(Xo,"__esModule",{value:!0});var w3=require("util"),Vg=kv(),or;(function(t){t[t.UNIVERSAL=0]="UNIVERSAL",t[t.APPLICATION=64]="APPLICATION",t[t.CONTEXT_SPECIFIC=128]="CONTEXT_SPECIFIC",t[t.PRIVATE=192]="PRIVATE"})(or=Xo.Class||(Xo.Class={}));var _t;(function(t){t[t.NONE=0]="NONE",t[t.BOOLEAN=1]="BOOLEAN",t[t.INTEGER=2]="INTEGER",t[t.BITSTRING=3]="BITSTRING",t[t.OCTETSTRING=4]="OCTETSTRING",t[t.NULL=5]="NULL",t[t.OID=6]="OID",t[t.ENUMERATED=10]="ENUMERATED",t[t.UTF8=12]="UTF8",t[t.SEQUENCE=16]="SEQUENCE",t[t.SET=17]="SET",t[t.NUMERICSTRING=18]="NUMERICSTRING",t[t.PRINTABLESTRING=19]="PRINTABLESTRING",t[t.T61STRING=20]="T61STRING",t[t.IA5STRING=22]="IA5STRING",t[t.UTCTIME=23]="UTCTIME",t[t.GENERALIZEDTIME=24]="GENERALIZEDTIME",t[t.GENERALSTRING=27]="GENERALSTRING"})(_t=Xo.Tag||(Xo.Tag={}));var eh=class{constructor(e,r){this.buf=e,this.bitLen=r}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let r=Math.floor(e/8),s=7-e%8;return this.buf[r]>>s&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let r=Buffer.alloc(this.buf.length);r[0]=this.buf[0]>>e;for(let s=1;s<this.buf.length;s++)r[s]=this.buf[s-1]<<8-e,r[s]|=this.buf[s]>>e;return r}};Xo.BitString=eh;var Dv=class t{static Bool(e){let r=new t(or.UNIVERSAL,_t.BOOLEAN,Buffer.from([e?255:0]));return r._value=e,r}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error("ASN1 syntax error: invalid boolean");switch(e[0]){case 0:return!1;case 255:return!0;default:throw new Error("ASN1 syntax error: invalid boolean")}}static Integer(e){if(e instanceof Buffer){let n=new t(or.UNIVERSAL,_t.INTEGER,e);return n._value=e.toString("hex"),n}if(!Number.isSafeInteger(e))throw new Error("ASN1 syntax error: invalid integer");let r;if(e>=-128&&e<128)r=Buffer.alloc(1),r.writeInt8(e,0);else if(e>=-32768&&e<32768)r=Buffer.alloc(2),r.writeIntBE(e,0,2);else if(e>=-8388608&&e<8388608)r=Buffer.alloc(3),r.writeIntBE(e,0,3);else if(e>=-2147483648&&e<2147483648)r=Buffer.alloc(4),r.writeIntBE(e,0,4);else if(e>=-549755813888&&e<549755813888)r=Buffer.alloc(5),r.writeIntBE(e,0,5);else if(e>=-0x800000000000&&e<0x800000000000)r=Buffer.alloc(6),r.writeIntBE(e,0,6);else throw new Error("ASN1 syntax error: invalid Integer");let s=new t(or.UNIVERSAL,_t.INTEGER,r);return s._value=e,s}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Integer");return e.length>6?e.toString("hex"):e.readIntBE(0,e.length)}static parseIntegerNum(e){let r=t.parseInteger(e);if(typeof r!="number")throw new Error("ASN1 syntax error: invalid Integer number");return r}static parseIntegerStr(e){let r=t.parseInteger(e);return typeof r=="number"?r.toString(16):r}static BitString(e){e instanceof Buffer&&(e=new eh(e,e.length*8));let r=e.buf.length*8-e.bitLen,s=Buffer.alloc(e.buf.length+1);return s.writeInt8(r,0),e.buf.copy(s,1),new t(or.UNIVERSAL,_t.BITSTRING,s)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid BitString");let r=e[0];if(r>7||e.length===1&&r>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");return new eh(e.slice(1),(e.length-1)*8-r)}static Null(){let e=new t(or.UNIVERSAL,_t.NULL,Buffer.alloc(0));return e._value=null,e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error("ASN1 syntax error: invalid null");return null}static OID(e){let r=e.split(".");if(r.length===0)throw new Error("ASN1 syntax error: invalid Object Identifier");let s=[];s.push(40*vr(r[0])+vr(r[1]));let n=[];for(let o=2;o<r.length;++o){let a=vr(r[o]);for(n.length=0,n.push(a&127);a>127;)a=a>>>7,n.unshift(a&127|128);s.push(...n)}let i=new t(or.UNIVERSAL,_t.OID,Buffer.from(s));return i._value=e,i}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid OID");let r=Math.floor(e[0]/40)+"."+e[0]%40,s=0;for(let n=1;n<e.length;n++)e[n]>=128?(s+=e[n]&127,s=s<<7):(r+="."+(s+e[n]),s=0);return r}static UTF8(e){let r=new t(or.UNIVERSAL,_t.UTF8,Buffer.from(e,"utf8"));return r._value=e,r}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static NumericString(e){if(!v3(e))throw new Error("ASN1 syntax error: invalid NumericString");let r=new t(or.UNIVERSAL,_t.NUMERICSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!v3(r))throw new Error("ASN1 syntax error: invalid NumericString");return r}static PrintableString(e){let r=new t(or.UNIVERSAL,_t.PRINTABLESTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static IA5String(e){if(!_3(e))throw new Error("ASN1 syntax error: invalid IA5String");let r=new t(or.UNIVERSAL,_t.IA5STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!_3(r))throw new Error("ASN1 syntax error: invalid IA5String");return r}static T61String(e){let r=new t(or.UNIVERSAL,_t.T61STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseT61String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static GeneralString(e){let r=new t(or.UNIVERSAL,_t.GENERALSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static UTCTime(e){let r="",s=[];s.push((""+e.getUTCFullYear()).substr(2)),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(r+="0"),r+=i;r+="Z";let n=new t(or.UNIVERSAL,_t.UTCTIME,Buffer.from(r,"utf8"));return n._value=e,n}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid UTC Time");let r=e.toString("utf8"),s=new Date,n=vr(r.substr(0,2));n=n>=50?1900+n:2e3+n;let i=vr(r.substr(2,2))-1,o=vr(r.substr(4,2)),a=vr(r.substr(6,2)),c=vr(r.substr(8,2)),d=0,u=0,l="";if(r.length>11&&(u=10,l=r.charAt(u),l!=="+"&&l!=="-"&&(d=vr(r.substr(10,2)),u+=2)),s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,0),u>0&&(l=r.charAt(u),l==="+"||l==="-")){let f=vr(r.substr(u+1,2)),h=vr(r.substr(u+4,2)),m=f*60+h;m*=6e4,l==="+"?s.setTime(+s-m):s.setTime(+s+m)}return s}static GeneralizedTime(e){let r="",s=[];s.push(""+e.getUTCFullYear()),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(r+="0"),r+=i;r+="Z";let n=new t(or.UNIVERSAL,_t.GENERALIZEDTIME,Buffer.from(r,"utf8"));return n._value=e,n}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");let r=e.toString("utf8"),s=new Date,n=vr(r.substr(0,4)),i=vr(r.substr(4,2))-1,o=vr(r.substr(6,2)),a=vr(r.substr(8,2)),c=vr(r.substr(10,2)),d=vr(r.substr(12,2)),u=0,l=0,f=!1;r.charAt(r.length-1)==="Z"&&(f=!0);let h=r.length-5,m=r.charAt(h);if(m==="+"||m==="-"){let v=vr(r.substr(h+1,2)),p=vr(r.substr(h+4,2));l=v*60+p,l*=6e4,m==="+"&&(l*=-1),f=!0}return r.charAt(14)==="."&&(u=parseFloat(r.substr(14))*1e3),f?(s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,u),s.setTime(+s+l)):(s.setFullYear(n,i,o),s.setHours(a,c,d,u)),s}static parseTime(e,r){switch(e){case _t.UTCTIME:return t.parseUTCTime(r);case _t.GENERALIZEDTIME:return t.parseGeneralizedTime(r);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let r=new t(or.UNIVERSAL,_t.SET,Buffer.concat(e.map(s=>s.toDER())));return r._value=e,r}static Seq(e){let r=new t(or.UNIVERSAL,_t.SEQUENCE,Buffer.concat(e.map(s=>s.toDER())));return r._value=e,r}static Spec(e,r,s=!0){let n=Array.isArray(r)?Buffer.concat(r.map(o=>o.toDER())):r.toDER();Array.isArray(r)&&(s=!0);let i=new t(or.CONTEXT_SPECIFIC,e,n,s);return i._value=r,i}static fromDER(e,r=!1){return t._fromDER(new Vg.BufferVisitor(e),r)}static parseDER(e,r,s){let n=t._fromDER(new Vg.BufferVisitor(e),!1);if(n.class!==r&&n.tag!==s)throw new Error(`invalid ASN.1 DER for class ${r} and tag ${s}`);return n}static parseDERWithTemplate(e,r){let s=t._fromDER(new Vg.BufferVisitor(e),!0),n={},i=s.validate(r,n);if(i!=null)throw i.data=s,i;return n}static _parseCompound(e,r){let s=[],n=e.length,i=new Vg.BufferVisitor(e),o=0;for(;o<n;){let a=i.end;s.push(t._fromDER(i,r)),o+=i.end-a}return s}static _fromDER(e,r){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");e.mustWalk(1,"Too few bytes to read ASN.1 tag.");let s=e.start,n=e.buf[s],i=n&192,o=n&31,a=Sq(e);if(e.mustHas(a),a!==0&&o===_t.NULL)throw new Error("invalid value length or NULL tag.");e.mustWalk(a);let c=(n&32)===32,d=new t(i,o,e.buf.slice(e.start,e.end),c);return c&&r&&(d._value=t._parseCompound(d.bytes,r)),d._der=e.buf.slice(s,e.end),d}constructor(e,r,s,n=!1){this.class=e,this.tag=r,this.bytes=s,this.isCompound=n||r===_t.SEQUENCE||r===_t.SET,this._value=void 0,this._der=null}get value(){return this._value===void 0&&(this._value=this.valueOf()),this._value}get DER(){return this._der==null&&(this._der=this.toDER()),this._der}mustCompound(e="asn1 object value is not compound"){if(!this.isCompound||!Array.isArray(this.value)){let r=new Error(e);throw r.data=this.toJSON(),r}return this.value}equals(e){return!(!(e instanceof t)||this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound||!this.bytes.equals(e.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let r=Eq(this.bytes.length),s=Buffer.allocUnsafe(2+r+this.bytes.length);return s.writeInt8(e,0),r===0?(s.writeUInt8(this.bytes.length,1),this.bytes.copy(s,2)):(s.writeUInt8(r|128,1),s.writeUIntBE(this.bytes.length,2,r),this.bytes.copy(s,2+r)),s}valueOf(){if(this.isCompound)return t._parseCompound(this.bytes,!1);if(this.class!==or.UNIVERSAL)return this.bytes;switch(this.tag){case _t.BOOLEAN:return t.parseBool(this.bytes);case _t.INTEGER:return t.parseInteger(this.bytes);case _t.BITSTRING:return t.parseBitString(this.bytes);case _t.NULL:return t.parseNull(this.bytes);case _t.OID:return t.parseOID(this.bytes);case _t.UTF8:return t.parseUTF8(this.bytes);case _t.NUMERICSTRING:return t.parseNumericString(this.bytes);case _t.PRINTABLESTRING:return t.parsePrintableString(this.bytes);case _t.T61STRING:return t.parseT61String(this.bytes);case _t.IA5STRING:return t.parseIA5String(this.bytes);case _t.GENERALSTRING:return t.parseGeneralString(this.bytes);case _t.UTCTIME:return t.parseUTCTime(this.bytes);case _t.GENERALIZEDTIME:return t.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,r={}){if(this.class!==e.class)return new Error(`ASN.1 object validate failure for ${e.name} : error class ${or[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return new Error(`ASN.1 object validate failure for ${e.name}: error tag ${_t[this.tag]}`);if(e.capture!=null&&(r[e.capture]=this),Array.isArray(e.value)){let n=this.mustCompound(`${e.name} need compound ASN1 value`);for(let i=0,o=0;i<e.value.length;i++)if(n[o]!=null){let a=n[o].validate(e.value[i],r);if(a==null)o++;else if(e.value[i].optional!==!0)return a}else if(e.value[i].optional!==!0)return new Error(`ASN.1 object validate failure for ${e.value[i].name}: not exists`)}else if(e.value!=null){let n=this.tag===_t.BITSTRING?this.bytes.slice(1):this.bytes;return t.fromDER(n).validate(e.value,r)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(r=>r.toJSON())),{class:or[this.class],tag:this.class===or.UNIVERSAL?_t[this.tag]:this.tag,value:e}}[w3.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${w3.inspect(this.toJSON(),r)}>`}};Xo.ASN1=Dv;function Sq(t){t.mustWalk(1,"Too few bytes to read ASN.1 value length.");let e=t.buf[t.start];if((e&128)===0)return e;let r=e&127;return t.mustWalk(r,"Too few bytes to read ASN.1 value length."),t.buf.readUIntBE(t.start,r)}function Eq(t){if(t<=127)return 0;if(t<=255)return 1;if(t<=65535)return 2;if(t<=16777215)return 3;if(t<=4294967295)return 4;if(t<=0xffffffffff)return 5;if(t<=0xffffffffffff)return 6;throw new Error("invalid value length")}function v3(t){for(let e of t){let r=e.charCodeAt(0);if(r!==32&&(r<48||r>57))return!1}return!0}function _3(t){for(let e of t)if(e.charCodeAt(0)>=128)return!1;return!0}function vr(t,e=10){let r=parseInt(t,e);if(Number.isNaN(r))throw new Error(`Invalid numeric string "${t}" in radix ${e}.`);return r}});var Nv=Ne(Yo=>{"use strict";g();Object.defineProperty(Yo,"__esModule",{value:!0});var Cq=kv();Yo.BufferVisitor=Cq.BufferVisitor;var Tq=b3();Yo.PEM=Tq.PEM;var qg=S3();Yo.ASN1=qg.ASN1;Yo.Class=qg.Class;Yo.Tag=qg.Tag;Yo.BitString=qg.BitString});var Mv=Ne(Wn=>{"use strict";g();Object.defineProperty(Wn,"__esModule",{value:!0});var Qo=require("util"),th=require("crypto"),Uv=Hg(),we=Nv(),Gr=jg();Wn.publicKeyValidator={name:"PublicKeyInfo",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:we.Class.UNIVERSAL,tag:we.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:we.Class.UNIVERSAL,tag:we.Tag.BITSTRING,capture:"publicKey"}]};Wn.privateKeyValidator={name:"PrivateKeyInfo",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:we.Class.UNIVERSAL,tag:we.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:we.Class.UNIVERSAL,tag:we.Tag.OCTETSTRING,capture:"privateKey"}]};var Aq={name:"RSAPublicKey",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"publicKeyExponent"}]},kq={name:"RSAPrivateKey",class:we.Class.UNIVERSAL,tag:we.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:we.Class.UNIVERSAL,tag:we.Tag.INTEGER,capture:"privateKeyCoefficient"}]},Iq=[Gr.getOID("X25519"),Gr.getOID("X448"),Gr.getOID("Ed25519"),Gr.getOID("Ed448")],Ol=class t{constructor(e){let r={},s=e.validate(Wn.publicKeyValidator,r);if(s!=null)throw new Error("Cannot read X.509 public key: "+s.message);this.oid=we.ASN1.parseOID(r.publicKeyOID.bytes),this.algo=Gr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=we.ASN1.parseBitString(r.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let r=we.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let s=we.ASN1.fromDER(r.body,!0);switch(r.type){case"PUBLIC KEY":return new t(s);case"RSA PUBLIC KEY":let n=we.ASN1.Seq([we.ASN1.Seq([we.ASN1.OID(Gr.getOID("rsaEncryption")),we.ASN1.Null()]),we.ASN1.BitString(s.DER)]);return new t(n);default:throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM")}}static addVerifier(e,r){if(e=Gr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);t._verifiers[e]=r}get keyRaw(){return this._finalKey}verify(e,r,s){let n=t._verifiers[this.oid];if(n!=null){let o=th.createHash(s).update(e).digest();return n.call(this,o,r)}let i=th.createVerify(s);return i.update(e),i.verify(this.toPEM(),r)}getFingerprint(e,r="PublicKey"){let s;switch(r){case"PublicKeyInfo":s=this._pkcs8.DER;break;case"PublicKey":s=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${r}".`)}let n=th.createHash(e);return n.update(s),n.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new we.PEM("PUBLIC KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[Qo.inspect.custom](e,r){return`<${this.constructor.name} ${Qo.inspect(this.toJSON(),r)}>`}};Ol._verifiers=Object.create(null);Wn.PublicKey=Ol;var Ll=class t{constructor(e){let r=Object.create(null),s=e.validate(Wn.privateKeyValidator,r);if(s!=null)throw new Error("Cannot read X.509 private key: "+s.message);if(this.version=we.ASN1.parseIntegerNum(r.privateKeyVersion.bytes)+1,this.oid=we.ASN1.parseOID(r.privateKeyOID.bytes),this.algo=Gr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=r.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM="",Iq.includes(this.oid)){if(this._finalKey=this._keyRaw=we.ASN1.parseDER(this._keyRaw,we.Class.UNIVERSAL,we.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let n=Uv.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(n.publicKey),this._finalKey=Buffer.from(n.secretKey)}else if(this.version===2)for(let n of e.mustCompound())n.class===we.Class.CONTEXT_SPECIFIC&&n.tag===1&&(this._publicKeyRaw=we.ASN1.parseBitString(n.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let r=we.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let s=we.ASN1.fromDER(r.body,!0);switch(r.type){case"PRIVATE KEY":return new t(s);case"RSA PRIVATE KEY":return s=we.ASN1.Seq([s.value[0],we.ASN1.Seq([we.ASN1.OID(Gr.getOID("rsaEncryption")),we.ASN1.Null()]),new we.ASN1(we.Class.UNIVERSAL,we.Tag.OCTETSTRING,s.DER)]),new t(s);default:throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM")}}static addSigner(e,r){if(e=Gr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._signers[e]!=null)throw new Error(`Signer ${e} exists`);t._signers[e]=r}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,r){let s=t._signers[this.oid];if(s!=null){let i=th.createHash(r).update(e).digest();return s.call(this,i)}let n=th.createSign(r);return n.update(e),n.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new we.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}}[Qo.inspect.custom](e,r){return`<${this.constructor.name} ${Qo.inspect(this.toJSON(),r)}>`}};Ll._signers=Object.create(null);Wn.PrivateKey=Ll;var Ov=class t extends Ol{static fromPublicKey(e){return new t(e.toASN1())}constructor(e){if(super(e),Gr.getOID(this.oid)!==Gr.getOID("rsaEncryption"))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=we.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(Aq,r);if(s!=null)throw new Error("Cannot read RSA public key: "+s.message);this.modulus=we.ASN1.parseIntegerStr(r.publicKeyModulus.bytes),this.exponent=we.ASN1.parseIntegerNum(r.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new we.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new we.PEM("PUBLIC KEY",this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:Jo(this.modulus),exponent:this.exponent}}[Qo.inspect.custom](e,r){return`<${this.constructor.name} ${Qo.inspect(this.toJSON(),r)}>`}};Wn.RSAPublicKey=Ov;var Lv=class t extends Ll{static fromPrivateKey(e){return new t(e.toASN1())}constructor(e){if(super(e),Gr.getOID(this.oid)!==Gr.getOID("rsaEncryption"))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=we.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(kq,r);if(s!=null)throw new Error("Cannot read RSA private key: "+s.message);this.publicExponent=we.ASN1.parseIntegerNum(r.privateKeyPublicExponent.bytes),this.privateExponent=we.ASN1.parseIntegerStr(r.privateKeyPrivateExponent.bytes),this.modulus=we.ASN1.parseIntegerStr(r.privateKeyModulus.bytes),this.prime1=we.ASN1.parseIntegerStr(r.privateKeyPrime1.bytes),this.prime2=we.ASN1.parseIntegerStr(r.privateKeyPrime2.bytes),this.exponent1=we.ASN1.parseIntegerStr(r.privateKeyExponent1.bytes),this.exponent2=we.ASN1.parseIntegerStr(r.privateKeyExponent2.bytes),this.coefficient=we.ASN1.parseIntegerStr(r.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new we.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new we.PEM("PRIVATE KEY",this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:Jo(this.privateExponent),modulus:Jo(this.modulus),prime1:Jo(this.prime1),prime2:Jo(this.prime2),exponent1:Jo(this.exponent1),exponent2:Jo(this.exponent2),coefficient:Jo(this.coefficient)}}[Qo.inspect.custom](e,r){return`<${this.constructor.name} ${Qo.inspect(this.toJSON(),r)}>`}};Wn.RSAPrivateKey=Lv;function Jo(t){return t.length%8!==0&&t.startsWith("00")?t.slice(2):t}Ol.addVerifier(Gr.getOID("Ed25519"),function(t,e){return Uv.sign.detached.verify(t,e,this.keyRaw)});Ll.addSigner(Gr.getOID("Ed25519"),function(t){let e=this.keyRaw;if(e.length!==64)throw new Error("Invalid signing key.");return Buffer.from(Uv.sign.detached(t,e))})});var I3=Ne(zg=>{"use strict";g();Object.defineProperty(zg,"__esModule",{value:!0});var E3=require("util"),Rq=require("crypto"),me=Nv(),Xr=jg(),k3=Mv(),_r=Object.create(null);_r.CN=Xr.getOID("commonName");_r.commonName="CN";_r.C=Xr.getOID("countryName");_r.countryName="C";_r.L=Xr.getOID("localityName");_r.localityName="L";_r.ST=Xr.getOID("stateOrProvinceName");_r.stateOrProvinceName="ST";_r.O=Xr.getOID("organizationName");_r.organizationName="O";_r.OU=Xr.getOID("organizationalUnitName");_r.organizationalUnitName="OU";_r.E=Xr.getOID("emailAddress");_r.emailAddress="E";function Pq(t){return _r[t]==null?"":_r[t]}var Bq={name:"Certificate",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:me.Class.UNIVERSAL,tag:me.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:me.Class.UNIVERSAL,tag:me.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:me.Class.UNIVERSAL,tag:me.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:me.Class.UNIVERSAL,tag:me.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:me.Class.UNIVERSAL,tag:[me.Tag.UTCTIME,me.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:me.Class.UNIVERSAL,tag:[me.Tag.UTCTIME,me.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,capture:"certSubject"},k3.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:me.Class.UNIVERSAL,tag:me.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:me.Class.UNIVERSAL,tag:me.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:me.Class.UNIVERSAL,tag:me.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:me.Class.UNIVERSAL,tag:me.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:me.Class.UNIVERSAL,tag:me.Tag.BITSTRING,capture:"certSignature"}]},rh=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=Rq.createHash("sha1");for(let r of this.attributes)e.update(r.oid),e.update(r.value);return e.digest()}getField(e){for(let r of this.attributes)if(e===r.oid||e===r.name||e===r.shortName)return r;return null}addField(e){T3([e]),this.attributes.push(e)}setAttrs(e){T3(e),this.attributes=e}toJSON(){let e={};for(let r of this.attributes){let s=r.shortName;typeof s=="string"&&s!==""&&(e[s]=r.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let r=this.getField(e);return r!=null?r.value:""}};zg.DistinguishedName=rh;var jv=class t{static fromPEMs(e){let r=[],s=me.PEM.parse(e);for(let n of s){if(n.type!=="CERTIFICATE"&&n.type!=="X509 CERTIFICATE"&&n.type!=="TRUSTED CERTIFICATE")throw new Error("Could not convert certificate from PEM: invalid type");if(n.procType.includes("ENCRYPTED"))throw new Error("Could not convert certificate from PEM: PEM is encrypted.");let i=me.ASN1.fromDER(n.body);r.push(new t(i))}if(r.length===0)throw new Error("No Certificate");return r}static fromPEM(e){return t.fromPEMs(e)[0]}constructor(e){let r=Object.create(null),s=e.validate(Bq,r);if(s!=null)throw new Error("Cannot read X.509 certificate: "+s.message);if(this.raw=e.DER,this.version=r.certVersion==null?0:me.ASN1.parseIntegerNum(r.certVersion.bytes)+1,this.serialNumber=me.ASN1.parseIntegerStr(r.certSerialNumber.bytes),this.signatureOID=me.ASN1.parseOID(r.certSignatureOID.bytes),this.signatureAlgorithm=Xr.getOIDName(this.signatureOID),this.infoSignatureOID=me.ASN1.parseOID(r.certinfoSignatureOID.bytes),this.signature=me.ASN1.parseBitString(r.certSignature.bytes).buf,this.validFrom=me.ASN1.parseTime(r.certValidityNotBefore.tag,r.certValidityNotBefore.bytes),this.validTo=me.ASN1.parseTime(r.certValidityNotAfter.tag,r.certValidityNotAfter.bytes),this.issuer=new rh,this.issuer.setAttrs(A3(r.certIssuer)),r.certIssuerUniqueId!=null&&(this.issuer.uniqueId=me.ASN1.parseBitString(r.certIssuerUniqueId.bytes)),this.subject=new rh,this.subject.setAttrs(A3(r.certSubject)),r.certSubjectUniqueId!=null&&(this.subject.uniqueId=me.ASN1.parseBitString(r.certSubjectUniqueId.bytes)),this.extensions=[],this.subjectKeyIdentifier="",this.authorityKeyIdentifier="",this.ocspServer="",this.issuingCertificateURL="",this.isCA=!1,this.maxPathLen=-1,this.basicConstraintsValid=!1,this.keyUsage=0,this.dnsNames=[],this.emailAddresses=[],this.ipAddresses=[],this.uris=[],r.certExtensions!=null){this.extensions=Dq(r.certExtensions);for(let n of this.extensions)if(typeof n.subjectKeyIdentifier=="string"&&(this.subjectKeyIdentifier=n.subjectKeyIdentifier),typeof n.authorityKeyIdentifier=="string"&&(this.authorityKeyIdentifier=n.authorityKeyIdentifier),typeof n.authorityInfoAccessOcsp=="string"&&(this.ocspServer=n.authorityInfoAccessOcsp),typeof n.authorityInfoAccessIssuers=="string"&&(this.issuingCertificateURL=n.authorityInfoAccessIssuers),typeof n.basicConstraintsValid=="boolean"&&(this.isCA=n.isCA,this.maxPathLen=n.maxPathLen,this.basicConstraintsValid=n.basicConstraintsValid),typeof n.keyUsage=="number"&&(this.keyUsage=n.keyUsage),Array.isArray(n.altNames))for(let i of n.altNames)i.dnsName!=null&&this.dnsNames.push(i.dnsName),i.email!=null&&this.emailAddresses.push(i.email),i.ip!=null&&this.ipAddresses.push(i.ip),i.uri!=null&&this.uris.push(i.uri)}this.publicKey=new k3.PublicKey(r.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=r.tbsCertificate}getExtension(e,r=""){for(let s of this.extensions)if(e===s.oid||e===s.name)return r===""?s:s[r];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return new Error("The parent constraint violation error");if(this.getExtension("keyUsage","keyCertSign")!==!0)return new Error("The parent constraint violation error");if(!e.isIssuer(this))return new Error("The parent certificate did not issue the given child certificate");let r=zq(e.signatureOID);return r===""?new Error("Unknown child signature OID."):this.publicKey.verify(e.tbsCertificate.DER,e.signature,r)===!1?new Error("Child signature not matched"):null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint("sha1","PublicKey").toString("hex")===this.subjectKeyIdentifier}toJSON(){let e={};for(let r of Object.keys(this))e[r]=Kq(this[r]);return delete e.tbsCertificate,e}[E3.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${E3.inspect(this.toJSON(),r)}>`}};zg.Certificate=jv;function Dq(t){let e=[];for(let r of t.mustCompound())for(let s of r.mustCompound())e.push(Nq(s));return e}function Nq(t){let e={};switch(e.oid=me.ASN1.parseOID(t.value[0].bytes),e.critical=!1,t.value[1].tag===me.Tag.BOOLEAN?(e.critical=me.ASN1.parseBool(t.value[1].bytes),e.value=t.value[2].bytes):e.value=t.value[1].bytes,e.name=Xr.getOIDName(e.oid),e.name){case"keyUsage":Oq(e);break;case"basicConstraints":Lq(e);break;case"extKeyUsage":Uq(e);break;case"nsCertType":Mq(e);break;case"subjectAltName":C3(e);break;case"issuerAltName":C3(e);break;case"subjectKeyIdentifier":Fq(e);break;case"authorityKeyIdentifier":$q(e);break;case"authorityInfoAccess":qq(e);break}return e}function Oq(t){let e=me.ASN1.parseBitString(me.ASN1.fromDER(t.value).bytes),r=0,s=0;t.keyUsage=0;for(let n=0;n<9;n++)e.at(n)!==0&&(t.keyUsage|=1<<n);e.buf.length>0&&(r=e.buf[0],s=e.buf.length>1?e.buf[1]:0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(s&128)===128}function Lq(t){let r=me.ASN1.fromDER(t.value).mustCompound();r.length>0&&r[0].tag===me.Tag.BOOLEAN?t.isCA=me.ASN1.parseBool(r[0].bytes):t.isCA=!1;let s=null;r.length>0&&r[0].tag===me.Tag.INTEGER?s=r[0].bytes:r.length>1&&(s=r[1].bytes),s!==null?t.maxPathLen=me.ASN1.parseInteger(s):t.maxPathLen=-1,t.basicConstraintsValid=!0}function Uq(t){let r=me.ASN1.fromDER(t.value).mustCompound();for(let s of r)t[Xr.getOIDName(me.ASN1.parseOID(s.bytes))]=!0}function Mq(t){let e=me.ASN1.parseBitString(me.ASN1.fromDER(t.value).bytes),r=0;e.buf.length>0&&(r=e.buf[0]),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}function C3(t){t.altNames=[];let r=me.ASN1.fromDER(t.value).mustCompound();for(let s of r){let n={tag:s.tag,value:s.bytes};switch(t.altNames.push(n),s.tag){case 1:n.email=s.bytes.toString();break;case 2:n.dnsName=s.bytes.toString();break;case 6:n.uri=s.bytes.toString();break;case 7:n.ip=Xr.bytesToIP(s.bytes);break;case 8:n.oid=me.ASN1.parseOID(s.bytes);break;default:}}}var jq={name:"subjectKeyIdentifier",class:me.Class.UNIVERSAL,tag:me.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function Fq(t){let e=me.ASN1.parseDERWithTemplate(t.value,jq);t.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var Hq={name:"authorityKeyIdentifier",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.NONE,capture:"authorityKeyIdentifier"}]};function $q(t){let e=me.ASN1.parseDERWithTemplate(t.value,Hq);t.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var Vq={name:"authorityInfoAccess",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:me.Class.UNIVERSAL,tag:me.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:me.Class.UNIVERSAL,tag:me.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:me.Class.UNIVERSAL,tag:me.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:me.Class.CONTEXT_SPECIFIC,tag:me.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function qq(t){let e=me.ASN1.parseDERWithTemplate(t.value,Vq);e.authorityInfoAccessOcsp!=null&&(t.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(t.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function T3(t){for(let e of t){if((e.name==null||e.name==="")&&(e.oid!=null&&(e.name=Xr.getOIDName(e.oid)),e.name===""&&e.shortName!=null&&(e.name=Xr.getOIDName(_r[e.shortName]))),e.oid==null||e.oid==="")if(e.name!=="")e.oid=Xr.getOID(e.name);else throw new Error("Attribute oid not specified.");if((e.shortName==null||e.shortName==="")&&(e.shortName=_r[e.name]==null?"":_r[e.name]),e.value==null)throw new Error("Attribute value not specified.")}}function zq(t){switch(Xr.getOIDName(t)){case"sha1WithRsaEncryption":return"sha1";case"md5WithRsaEncryption":return"md5";case"sha256WithRsaEncryption":return"sha256";case"sha384WithRsaEncryption":return"sha384";case"sha512WithRsaEncryption":return"sha512";case"RSASSA-PSS":return"sha256";case"ecdsaWithSha1":return"sha1";case"ecdsaWithSha256":return"sha256";case"ecdsaWithSha384":return"sha384";case"ecdsaWithSha512":return"sha512";case"dsaWithSha1":return"sha1";case"dsaWithSha256":return"sha256";default:return""}}function A3(t){let e=[];for(let r of t.mustCompound())for(let s of r.mustCompound()){let n=s.mustCompound(),i={};i.oid=me.ASN1.parseOID(n[0].bytes),i.value=n[1].value,i.valueTag=n[1].tag,i.name=Xr.getOIDName(i.oid),i.shortName=Pq(i.name),e.push(i)}return e}function Kq(t){return t!=null&&!(t instanceof Buffer)&&typeof t.toJSON=="function"?t.toJSON():t}});var Fv=Ne(qs=>{"use strict";g();Object.defineProperty(qs,"__esModule",{value:!0});var Kg=jg();qs.bytesFromIP=Kg.bytesFromIP;qs.bytesToIP=Kg.bytesToIP;qs.getOID=Kg.getOID;qs.getOIDName=Kg.getOIDName;var Wg=Mv();qs.PublicKey=Wg.PublicKey;qs.PrivateKey=Wg.PrivateKey;qs.RSAPublicKey=Wg.RSAPublicKey;qs.RSAPrivateKey=Wg.RSAPrivateKey;var R3=I3();qs.Certificate=R3.Certificate;qs.DistinguishedName=R3.DistinguishedName});function P3(...t){let e=t.map(n=>n.byteLength).reduce((n,i)=>n+i),r=new Uint8Array(e),s=0;return t.map(n=>new Uint8Array(n)).forEach(n=>{for(let i of n)r[s++]=i}),r.buffer}function B3(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),s=new Uint8Array(e);for(let n=0;n<t.byteLength;n++)if(r[n]!==s[n])return!1;return!0}var Wq,Ce,Hv,Gq,Xq,Yq,Gg,zs,Ve,$v=z(()=>{"use strict";g();Wq="[object ArrayBuffer]",Ce=class t{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Wq}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){let s=t.toUint8Array(e),n=t.toUint8Array(r);if(s.length!==n.byteLength)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let s=0;for(let o of r)s+=o.byteLength;let n=new Uint8Array(s),i=0;for(let o of r){let a=this.toUint8Array(o);n.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}},Hv="string",Gq=/^[0-9a-f\s]+$/i,Xq=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Yq=/^[a-zA-Z0-9-_]+$/,Gg=class{static fromString(e){let r=unescape(encodeURIComponent(e)),s=new Uint8Array(r.length);for(let n=0;n<r.length;n++)s[n]=r.charCodeAt(n);return s.buffer}static toString(e){let r=Ce.toUint8Array(e),s="";for(let i=0;i<r.length;i++)s+=String.fromCharCode(r[i]);return decodeURIComponent(escape(s))}},zs=class{static toString(e,r=!1){let s=Ce.toArrayBuffer(e),n=new DataView(s),i="";for(let o=0;o<s.byteLength;o+=2){let a=n.getUint16(o,r);i+=String.fromCharCode(a)}return i}static fromString(e,r=!1){let s=new ArrayBuffer(e.length*2),n=new DataView(s);for(let i=0;i<e.length;i++)n.setUint16(i*2,e.charCodeAt(i),r);return s}},Ve=class t{static isHex(e){return typeof e===Hv&&Gq.test(e)}static isBase64(e){return typeof e===Hv&&Xq.test(e)}static isBase64Url(e){return typeof e===Hv&&Yq.test(e)}static ToString(e,r="utf8"){let s=Ce.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(s);case"binary":return this.ToBinary(s);case"hex":return this.ToHex(s);case"base64":return this.ToBase64(s);case"base64url":return this.ToBase64Url(s);case"utf16le":return zs.toString(s,!0);case"utf16":case"utf16be":return zs.toString(s);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return zs.fromString(e,!0);case"utf16":case"utf16be":return zs.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){let r=Ce.toUint8Array(e);if(typeof btoa<"u"){let s=this.ToString(r,"binary");return btoa(s)}else return Buffer.from(r).toString("base64")}static FromBase64(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Gg.fromString(e);case"utf16":case"utf16be":return zs.fromString(e);case"utf16le":case"usc2":return zs.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Gg.toString(e);case"utf16":case"utf16be":return zs.toString(e);case"utf16le":case"usc2":return zs.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){let r=e.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=e.charCodeAt(n);return s.buffer}static ToBinary(e){let r=Ce.toUint8Array(e),s="";for(let n=0;n<r.length;n++)s+=String.fromCharCode(r[n]);return s}static ToHex(e){let r=Ce.toUint8Array(e),s="",n=r.length;for(let i=0;i<n;i++){let o=r[i];o<16&&(s+="0"),s+=o.toString(16)}return s}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);let s=new Uint8Array(r.length/2);for(let n=0;n<r.length;n=n+2){let i=r.slice(n,n+2);s[n/2]=parseInt(i,16)}return s.buffer}static ToUtf16String(e,r=!1){return zs.toString(e,r)}static FromUtf16String(e,r=!1){return zs.fromString(e,r)}static Base64Padding(e){let r=4-e.length%4;if(r<4)for(let s=0;s<r;s++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ve.DEFAULT_UTF8_ENCODING="utf8"});function _c(t,e){let r=0;if(t.length===1)return t[0];for(let s=t.length-1;s>=0;s--)r+=t[t.length-1-s]*Math.pow(2,e*s);return r}function Zo(t,e,r=-1){let s=r,n=t,i=0,o=Math.pow(2,e);for(let a=1;a<8;a++){if(t<o){let c;if(s<0)c=new ArrayBuffer(a),i=a;else{if(s<a)return new ArrayBuffer(0);c=new ArrayBuffer(s),i=s}let d=new Uint8Array(c);for(let u=a-1;u>=0;u--){let l=Math.pow(2,u*e);d[i-u-1]=Math.floor(n/l),n-=d[i-u-1]*l}return c}o*=Math.pow(2,e)}return new ArrayBuffer(0)}function Xg(...t){let e=0,r=0;for(let i of t)e+=i.length;let s=new ArrayBuffer(e),n=new Uint8Array(s);for(let i of t)n.set(i,r),r+=i.length;return n}function Vv(){let t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;let s=_c(r,8),n=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(n);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=t[a];return i[0]&=127,_c(i,8)-s}function D3(t){let e=t<0?t*-1:t,r=128;for(let s=1;s<8;s++){if(e<=r){if(t<0){let o=r-e,a=Zo(o,8,s),c=new Uint8Array(a);return c[0]|=128,a}let n=Zo(e,8,s),i=new Uint8Array(n);if(i[0]&128){let o=n.slice(0),a=new Uint8Array(o);n=new ArrayBuffer(n.byteLength+1),i=new Uint8Array(n);for(let c=0;c<o.byteLength;c++)i[c+1]=a[c];i[0]=0}return n}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function N3(t,e){if(t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),s=new Uint8Array(e);for(let n=0;n<r.length;n++)if(r[n]!==s[n])return!1;return!0}function ls(t,e){let r=t.toString(10);if(e<r.length)return"";let s=e-r.length,n=new Array(s);for(let o=0;o<s;o++)n[o]="0";return n.join("").concat(r)}var iie,O3=z(()=>{"use strict";g();iie=Math.log(2)});var Qn={};ic(Qn,{Any:()=>Xn,BaseBlock:()=>lr,BaseStringBlock:()=>oh,BitString:()=>yn,BmpString:()=>Tc,Boolean:()=>Sc,CharacterString:()=>Oc,Choice:()=>Ml,Constructed:()=>ur,DATE:()=>fh,DEFAULT_MAX_CONTENT_LENGTH:()=>z3,DEFAULT_MAX_DEPTH:()=>V3,DEFAULT_MAX_NODES:()=>q3,DateTime:()=>ph,Duration:()=>mh,EndOfContent:()=>ah,Enumerated:()=>Ec,GeneralString:()=>Nc,GeneralizedTime:()=>Lc,GraphicString:()=>Dc,HexBlock:()=>Jn,IA5String:()=>Bc,Integer:()=>qi,Null:()=>mn,NumericString:()=>kc,ObjectIdentifier:()=>Cc,OctetString:()=>gn,Primitive:()=>Vi,PrintableString:()=>Ic,RawData:()=>zv,RelativeObjectIdentifier:()=>uh,Repeated:()=>Uc,Sequence:()=>Yr,Set:()=>ts,TIME:()=>gh,TeletexString:()=>Rc,TimeOfDay:()=>hh,UTCTime:()=>ta,UniversalString:()=>Ac,Utf8String:()=>Ks,ValueBlock:()=>Rr,VideotexString:()=>Pc,ViewWriter:()=>Ul,VisibleString:()=>ea,compareSchema:()=>Hi,fromBER:()=>Ki,verifySchema:()=>yz});function Yg(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Kv(t){let e=0,r=0;for(let n=0;n<t.length;n++){let i=t[n];e+=i.byteLength}let s=new Uint8Array(e);for(let n=0;n<t.length;n++){let i=t[n];s.set(new Uint8Array(i),r),r+=i.byteLength}return s.buffer}function zi(t,e,r,s){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):s<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-s<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}function Jn(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(s){this.valueHexView=new Uint8Array(s)}constructor(...s){var n;super(...s);let i=s[0]||{};this.isHexOnly=(n=i.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=i.valueHex?Ce.toUint8Array(i.valueHex):uy}fromBER(s,n,i,o){let a=s instanceof ArrayBuffer?new Uint8Array(s):s;if(!zi(this,a,n,i))return-1;let c=n+i;return this.valueHexView=a.subarray(n,c),this.valueHexView.length?(this.blockLength=i,c):(this.warnings.push("Zero buffer length"),n)}toBER(s=!1){return this.isHexOnly?s?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",Yn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ve.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}function H3(t){var e;if(t instanceof Pe.Constructed)for(let r of t.valueBlock.value)H3(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}function yh(t={}){var e,r,s;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:V3,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:q3,maxContentLength:(s=t.maxContentLength)!==null&&s!==void 0?s:z3}}function lz(t){let e=new lr({},Rr);return e.error=t,{offset:-1,result:e}}function uz(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return cz}function fz(t,e){if(t>e.maxContentLength)return dz}function Wv(t,e,r,s){let n=s.depth+1;if(n>s.maxDepth)return lz(az);s.depth=n;try{return fy(t,e,r,s)}finally{s.depth-=1}}function hz(t,e){if(t instanceof e)return t;let r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function fy(t,e=0,r=t.length,s=yh()){let n=e,i=new lr({},Rr),o=new $i;if(!zi(o,t,e,r))return i.error=o.error,{offset:-1,result:i};if(!t.subarray(e,e+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=uz(s);if(c)return i.error=c,{offset:-1,result:i};let d=i.idBlock.fromBER(t,e,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),d===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=d,r-=i.idBlock.blockLength,d=i.lenBlock.fromBER(t,e,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),d===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=d,r-=i.lenBlock.blockLength;let u=i.lenBlock.isIndefiniteForm?r:i.lenBlock.length,l=fz(u,s);if(l)return i.error=l,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let f=lr;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};f=Pe.EndOfContent;break;case 1:f=Pe.Boolean;break;case 2:f=Pe.Integer;break;case 3:f=Pe.BitString;break;case 4:f=Pe.OctetString;break;case 5:f=Pe.Null;break;case 6:f=Pe.ObjectIdentifier;break;case 10:f=Pe.Enumerated;break;case 12:f=Pe.Utf8String;break;case 13:f=Pe.RelativeObjectIdentifier;break;case 14:f=Pe.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:f=Pe.Sequence;break;case 17:f=Pe.Set;break;case 18:f=Pe.NumericString;break;case 19:f=Pe.PrintableString;break;case 20:f=Pe.TeletexString;break;case 21:f=Pe.VideotexString;break;case 22:f=Pe.IA5String;break;case 23:f=Pe.UTCTime;break;case 24:f=Pe.GeneralizedTime;break;case 25:f=Pe.GraphicString;break;case 26:f=Pe.VisibleString;break;case 27:f=Pe.GeneralString;break;case 28:f=Pe.UniversalString;break;case 29:f=Pe.CharacterString;break;case 30:f=Pe.BmpString;break;case 31:f=Pe.DATE;break;case 32:f=Pe.TimeOfDay;break;case 33:f=Pe.DateTime;break;case 34:f=Pe.Duration;break;default:{let h=i.idBlock.isConstructed?new Pe.Constructed:new Pe.Primitive;h.idBlock=i.idBlock,h.lenBlock=i.lenBlock,h.warnings=i.warnings,i=h}}break;default:f=i.idBlock.isConstructed?Pe.Constructed:Pe.Primitive}return i=hz(i,f),d=i.fromBER(t,e,u,s),i.valueBeforeDecodeView=t.subarray(n,n+i.blockLength),{offset:d,result:i}}function Ki(t,e={}){if(!t.byteLength){let r=new lr({},Rr);return r.error="Input buffer has zero length",{offset:-1,result:r}}return fy(Ce.toUint8Array(t).slice(),0,t.byteLength,yh(e))}function pz(t,e){return t?1:e}function mz(t,e){let r=new Uint8Array([0]),s=new Uint8Array(t),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d=0,u=c<o?o:c,l=0;for(let f=u;f>=0;f--,l++)!0===l<a.length?d=i[o-l]+a[c-l]+r[0]:d=i[o-l]+r[0],r[0]=d/10,!0===l>=i.length?i=Xg(new Uint8Array([d%10]),i):i[o-l]=d%10;return r[0]>0&&(i=Xg(r,i)),i}function M3(t){if(t>=sh.length)for(let e=sh.length;e<=t;e++){let r=new Uint8Array([0]),s=sh[e-1].slice(0);for(let n=s.length-1;n>=0;n--){let i=new Uint8Array([(s[n]<<1)+r[0]]);r[0]=i[0]/10,s[n]=i[0]%10}r[0]>0&&(s=Xg(r,s)),sh.push(s)}return sh[t]}function gz(t,e){let r=0,s=new Uint8Array(t),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d,u=0;for(let l=c;l>=0;l--,u++)d=i[o-u]-a[c-u]-r,!0===d<0?(r=1,i[o-u]=d+10):(r=0,i[o-u]=d);if(r>0)for(let l=o-c+1;l>=0;l--,u++)if(d=i[o-u]-r,d<0)r=1,i[o-u]=d+10;else{r=0,i[o-u]=d;break}return i.slice()}function Hi(t,e,r){if(r instanceof Ml){for(let i of r.value)if(Hi(t,e,i).verified)return{verified:!0,result:t};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(qv)&&(i.name=r.name),i}}if(r instanceof Xn)return r.hasOwnProperty(qv)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(ez in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(nz in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(iz in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let s=r.idBlock.toBER(!1);if(s.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(s,0,s.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(tz)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(rz)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(sz)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(Zq in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(U3 in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=r.idBlock.valueHexView,o=e.idBlock.valueHexView;if(i.length!==o.length)return{verified:!1,result:t};for(let a=0;a<i.length;a++)if(i[a]!==o[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&(t[r.name]=e)),r instanceof Pe.Constructed){let i=0,o={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof Uc&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let d=0;d<r.valueBlock.value.length;d++)c=c&&(r.valueBlock.value[d].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-i>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){let d={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&(delete t[r.name],d.name=r.name)),d}}else if(r.valueBlock.value[0]instanceof Uc){if(o=Hi(t,e.valueBlock.value[c],r.valueBlock.value[0].value),o.verified===!1)if(r.valueBlock.value[0].optional)i++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&delete t[r.name]),o;if(qv in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let d={};oz in r.valueBlock.value[0]&&r.valueBlock.value[0].local?d=e:d=t,typeof d[r.valueBlock.value[0].name]>"u"&&(d[r.valueBlock.value[0].name]=[]),d[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(o=Hi(t,e.valueBlock.value[c-i],r.valueBlock.value[c]),o.verified===!1)if(r.valueBlock.value[c].optional)i++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&delete t[r.name]),o;if(o.verified===!1){let c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&U3 in e.valueBlock){let i=fy(e.valueBlock.valueHexView);if(i.offset===-1){let o={verified:!1,result:i.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,us),r.name&&(delete t[r.name],o.name=r.name)),o}return Hi(t,i.result,r.primitiveSchema)}return{verified:!0,result:t}}function yz(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let r=fy(Ce.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:Hi(r.result,r.result,e)}var Ul,sh,L3,qv,U3,Zq,ez,tz,rz,sz,nz,iz,oz,us,Yn,uy,ih,j3,F3,$i,Rr,Jg,Qg,Pe,lr,oh,Zg,$3,Vi,V3,q3,z3,az,cz,dz,Gn,K3,ur,ey,W3,ah,G3,mn,ty,X3,Sc,ry,Gv,gn,sy,Y3,yn,J3,ch,nh,qi,Q3,Ec,dh,ny,Z3,Cc,lh,iy,e8,uh,t8,Yr,r8,ts,oy,ay,rs,cy,s8,Ks,dy,n8,Tc,ly,i8,Ac,o8,kc,a8,Ic,c8,Rc,d8,Pc,l8,Bc,u8,Dc,f8,ea,h8,Nc,p8,Oc,m8,ta,g8,Lc,y8,fh,x8,hh,b8,ph,w8,mh,v8,gh,Xn,Ml,Uc,zv,ra=z(()=>{"use strict";g();$v();O3();Ul=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Kv(this.items)}},sh=[new Uint8Array([1])],L3="0123456789",qv="name",U3="valueHexView",Zq="isHexOnly",ez="idBlock",tz="tagClass",rz="tagNumber",sz="isConstructed",nz="fromBER",iz="toBER",oz="local",us="",Yn=new ArrayBuffer(0),uy=new Uint8Array(0),ih="EndOfContent",j3="OCTET STRING",F3="BIT STRING";$i=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=us,warnings:s=[],valueBeforeDecode:n=uy}={}){this.blockLength=e,this.error=r,this.warnings=s,this.valueBeforeDecodeView=Ce.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ve.ToHex(this.valueBeforeDecodeView)}}};$i.NAME="baseBlock";Rr=class extends $i{fromBER(e,r,s,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Rr.NAME="valueBlock";Jg=class extends Jn($i){constructor({idBlock:e={}}={}){var r,s,n,i;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?Ce.toUint8Array(e.valueHex):uy,this.tagClass=(s=e.tagClass)!==null&&s!==void 0?s:-1,this.tagNumber=(n=e.tagNumber)!==null&&n!==void 0?n:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",Yn}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,r|=i,n[0]=r}return n.buffer}if(!this.isHexOnly){let n=Zo(this.tagNumber,7),i=new Uint8Array(n),o=n.byteLength,a=new Uint8Array(o+1);if(a[0]=r|31,!e){for(let c=0;c<o-1;c++)a[c+1]=i[c]|128;a[o]=i[o-1]}return a.buffer}let s=new Uint8Array(this.valueHexView.byteLength+1);if(s[0]=r|31,!e){let n=this.valueHexView;for(let i=0;i<n.length-1;i++)s[i+1]=n[i]|128;s[this.valueHexView.byteLength]=n[n.length-1]}return s.buffer}fromBER(e,r,s){let n=Ce.toUint8Array(e);if(!zi(this,n,r,s))return-1;let i=n.subarray(r,r+s);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[u]&128)===0)break}this.blockLength=c+1;let d=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)d[u]=i[u+1]&127;this.blockLength<=9?this.tagNumber=_c(d,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Jg.NAME="identificationBlock";Qg=class extends $i{constructor({lenBlock:e={}}={}){var r,s,n;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(s=e.longFormUsed)!==null&&s!==void 0?s:!1,this.length=(n=e.length)!==null&&n!==void 0?n:0}fromBER(e,r,s){let n=Ce.toUint8Array(e);if(!zi(this,n,r,s))return-1;let i=n.subarray(r,r+s);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,r+this.blockLength;let o=i[0]&127;if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=r+1,c=n.subarray(a,a+o);return c[o-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=_c(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,r+this.blockLength}toBER(e=!1){let r,s;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(r),s[0]=128),r;if(this.longFormUsed){let n=Zo(this.length,8);if(n.byteLength>127)return this.error="Too big length",Yn;if(r=new ArrayBuffer(n.byteLength+1),e)return r;let i=new Uint8Array(n);s=new Uint8Array(r),s[0]=n.byteLength|128;for(let o=0;o<n.byteLength;o++)s[o+1]=i[o];return r}return r=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(r),s[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Qg.NAME="lengthBlock";Pe={},lr=class extends $i{constructor({name:e=us,optional:r=!1,primitiveSchema:s,...n}={},i){super(n),this.name=e,this.optional=r,s&&(this.primitiveSchema=s),this.idBlock=new Jg(n),this.lenBlock=new Qg(n),this.valueBlock=i?new i(n):new Rr(n)}fromBER(e,r,s,n){let i=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(e,r){let s=r||new Ul;r||H3(this);let n=this.idBlock.toBER(e);if(s.write(n),this.lenBlock.isIndefiniteForm)s.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,s),s.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let o=this.lenBlock.toBER(e);s.write(o),s.write(i)}return r?Yn:s.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():Ve.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,r=Ve.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let r=this.toBER(),s=e.toBER();return N3(r,s)}};lr.NAME="BaseBlock";oh=class extends lr{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=us,...r}={},s){super(r,s),e&&this.fromString(e)}fromBER(e,r,s){let n=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return n===-1?(this.error=this.valueBlock.error,n):(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),n)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};oh.NAME="BaseStringBlock";Zg=class extends Jn(Rr){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}};Zg.NAME="PrimitiveValueBlock";Vi=class extends lr{constructor(e={}){super(e,Zg),this.idBlock.isConstructed=!1}};$3=Vi;Pe.Primitive=$3;Vi.NAME="PRIMITIVE";V3=100,q3=1e4,z3=16*1024*1024,az="Maximum ASN.1 nesting depth exceeded",cz="Maximum ASN.1 node count exceeded",dz="Maximum ASN.1 content length exceeded";Gn=class extends Rr{constructor({value:e=[],isIndefiniteForm:r=!1,...s}={}){super(s),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,s,n){let i=Ce.toUint8Array(e),o=n??yh();if(!zi(this,i,r,s))return-1;if(this.valueBeforeDecodeView=i.subarray(r,r+s),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;pz(this.isIndefiniteForm,s)>0;){let c=Wv(i,a,s,o);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,s-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===ih)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ih?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){let s=r||new Ul;for(let n=0;n<this.value.length;n++)this.value[n].toBER(e,s);return r?Yn:s.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let r of this.value)e.value.push(r.toJSON());return e}};Gn.NAME="ConstructedValueBlock";ur=class extends lr{constructor(e={}){super(e,Gn),this.idBlock.isConstructed=!0}fromBER(e,r,s,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);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 s of this.valueBlock.value)e.push(s.toString("ascii").split(`
19
+ `).map(n=>` ${n}`).join(`
20
+ `));let r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
21
+ ${e.join(`
22
+ `)}`:`${r} :`}};K3=ur;Pe.Constructed=K3;ur.NAME="CONSTRUCTED";ey=class extends Rr{fromBER(e,r,s){return r}toBER(e){return Yn}};ey.override="EndOfContentValueBlock";ah=class extends lr{constructor(e={}){super(e,ey),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};W3=ah;Pe.EndOfContent=W3;ah.NAME=ih;mn=class extends lr{constructor(e={}){super(e,Rr),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,s){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+=s,r+s>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+s}toBER(e,r){let s=new ArrayBuffer(2);if(!e){let n=new Uint8Array(s);n[0]=5,n[1]=0}return r&&r.write(s),s}onAsciiEncoding(){return`${this.constructor.NAME}`}};G3=mn;Pe.Null=G3;mn.NAME="NULL";ty=class extends Jn(Rr){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=Ce.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,s){let n=Ce.toUint8Array(e);return zi(this,n,r,s)?(this.valueHexView=n.subarray(r,r+s),s>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Vv.call(this),this.blockLength=s,r+s):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ty.NAME="BooleanValueBlock";Sc=class extends lr{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ty),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};X3=Sc;Pe.Boolean=X3;Sc.NAME="BOOLEAN";ry=class extends Jn(Gn){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,s,n){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=Gn.prototype.fromBER.call(this,e,r,s,n),i===-1)return i;for(let o=0;o<this.value.length;o++){let a=this.value[o].constructor.NAME;if(a===ih){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==j3)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,r,s),this.blockLength=s;return i}toBER(e,r){return this.isConstructed?Gn.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ry.NAME="OctetStringValueBlock";gn=class extends lr{constructor({idBlock:e={},lenBlock:r={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!s.isIndefiniteForm},...s},ry),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,s,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,s===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+s);try{if(o.byteLength){let a=n??yh(),c=Wv(o,0,o.byteLength,a);c.offset!==-1&&c.offset===s&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ur.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,r=Ve.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let r of this.valueBlock.value)r instanceof Gv&&e.push(r.valueBlock.valueHexView);return Ce.concat(e)}};Gv=gn;Pe.OctetString=Gv;gn.NAME=j3;sy=class extends Jn(Gn){constructor({unusedBits:e=0,isConstructed:r=!1,...s}={}){super(s),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,s,n){if(!s)return r;let i=-1;if(this.isConstructed){if(i=Gn.prototype.fromBER.call(this,e,r,s,n),i===-1)return i;for(let c of this.value){let d=c.constructor.NAME;if(d===ih){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(d!==F3)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return i}let o=Ce.toUint8Array(e);if(!zi(this,o,r,s))return-1;let a=o.subarray(r,r+s);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let d=n??yh(),u=Wv(c,0,c.byteLength,d);u.offset!==-1&&u.offset===s-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+s}toBER(e,r){if(this.isConstructed)return Gn.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let n=new Uint8Array(1);return n[0]=0,n.buffer}let s=new Uint8Array(this.valueHexView.length+1);return s[0]=this.unusedBits,s.set(this.valueHexView,1),s.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};sy.NAME="BitStringValueBlock";yn=class extends lr{constructor({idBlock:e={},lenBlock:r={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!s.isIndefiniteForm},...s},sy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,s,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ur.prototype.onAsciiEncoding.call(this);{let e=[],r=this.valueBlock.valueHexView;for(let o of r)e.push(o.toString(2).padStart(8,"0"));let s=e.join(""),n=this.constructor.NAME,i=s.substring(0,s.length-this.valueBlock.unusedBits);return`${n} : ${i}`}}};Y3=yn;Pe.BitString=Y3;yn.NAME=F3;ch=class extends Jn(Rr){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=Vv.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(D3(e))}get valueDec(){return this._valueDec}fromDER(e,r,s,n=0){let i=this.fromBER(e,r,s);if(i===-1)return i;let o=this.valueHexView;return o[0]===0&&(o[1]&128)!==0?this.valueHexView=o.subarray(1):n!==0&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(e=!1){let r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{let s=new Uint8Array(this.valueHexView.length+1);s[0]=0,s.set(r,1),this.valueHexView=s}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,s){let n=super.fromBER(e,r,s);return n===-1||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,r=new Uint8Array(this.valueHexView.length*8/3),s=0,n,i=this.valueHexView,o="",a=!1;for(let c=i.byteLength-1;c>=0;c--){n=i[c];for(let d=0;d<8;d++)(n&1)===1&&(s===e?(r=gz(M3(s),r),o="-"):r=mz(r,M3(s))),s++,n>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(o+=L3.charAt(r[c]));return a===!1&&(o+=L3.charAt(0)),o}};J3=ch;ch.NAME="IntegerValueBlock";Object.defineProperty(J3.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});qi=class extends lr{constructor(e={}){super(e,ch),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Yg(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Yg();let r=BigInt(e),s=new Ul,n=r.toString(16).replace(/^-/,""),i=new Uint8Array(Ve.FromHex(n));if(r<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let d=BigInt(`0x${Ve.ToHex(a)}`)+r,u=Ce.toUint8Array(Ve.FromHex(d.toString(16)));u[0]|=128,s.write(u)}else i[0]&128&&s.write(new Uint8Array([0])),s.write(i);return new nh({valueHex:s.final()})}convertToDER(){let e=new nh({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new nh({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};nh=qi;Pe.Integer=nh;qi.NAME="INTEGER";Ec=class extends qi{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Q3=Ec;Pe.Enumerated=Q3;Ec.NAME="ENUMERATED";dh=class extends Jn(Rr){constructor({valueDec:e=-1,isFirstSid:r=!1,...s}={}){super(s),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,s){if(!s)return r;let n=Ce.toUint8Array(e);if(!zi(this,n,r,s))return-1;let i=n.subarray(r,r+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_c(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){Yg();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;let s=new Uint8Array(r.length/7);for(let n=0;n<s.length;n++)s[n]=parseInt(r.slice(n*7,n*7+7),2)+(n+1<s.length?128:0);this.fromBER(s.buffer,0,s.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let r=Zo(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yn;let s=new Uint8Array(r.byteLength);if(!e){let n=new Uint8Array(r),i=r.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s}toString(){let e="";if(this.isHexOnly)e=Ve.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};dh.NAME="sidBlock";ny=class extends Rr{constructor({value:e=us,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,s){let n=r;for(;s>0;){let i=new dh;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e){let r=[];for(let s=0;s<this.value.length;s++){let n=this.value[s].toBER(e);if(n.byteLength===0)return this.error=this.value[s].error,Yn;r.push(n)}return Kv(r)}fromString(e){this.value=[];let r=0,s=0,n="",i=!1;do if(s=e.indexOf(".",r),s===-1?n=e.substring(r):n=e.substring(r,s),r=s+1,i){let o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(n,10);if(isNaN(c))return;o.valueDec=c+a,i=!1}else{let o=new dh;if(n>Number.MAX_SAFE_INTEGER){Yg();let a=BigInt(n);o.valueBigInt=a}else if(o.valueDec=parseInt(n,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(s!==-1)}toString(){let e="",r=!1;for(let s=0;s<this.value.length;s++){r=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),r?(n=`{${n}}`,this.value[s].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};ny.NAME="ObjectIdentifierValueBlock";Cc=class extends lr{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ny),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Z3=Cc;Pe.ObjectIdentifier=Z3;Cc.NAME="OBJECT IDENTIFIER";lh=class extends Jn($i){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,s){if(s===0)return r;let n=Ce.toUint8Array(e);if(!zi(this,n,r,s))return-1;let i=n.subarray(r,r+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_c(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let r=Zo(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yn;let s=new Uint8Array(r.byteLength);if(!e){let n=new Uint8Array(r),i=r.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s.buffer}toString(){let e="";return this.isHexOnly?e=Ve.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};lh.NAME="relativeSidBlock";iy=class extends Rr{constructor({value:e=us,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,s){let n=r;for(;s>0;){let i=new lh;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e,r){let s=[];for(let n=0;n<this.value.length;n++){let i=this.value[n].toBER(e);if(i.byteLength===0)return this.error=this.value[n].error,Yn;s.push(i)}return Kv(s)}fromString(e){this.value=[];let r=0,s=0,n="";do{s=e.indexOf(".",r),s===-1?n=e.substring(r):n=e.substring(r,s),r=s+1;let i=new lh;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(s!==-1);return!0}toString(){let e="",r=!1;for(let s=0;s<this.value.length;s++){r=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),r&&(n=`{${n}}`),e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};iy.NAME="RelativeObjectIdentifierValueBlock";uh=class extends lr{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,iy),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};e8=uh;Pe.RelativeObjectIdentifier=e8;uh.NAME="RelativeObjectIdentifier";Yr=class extends ur{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};t8=Yr;Pe.Sequence=t8;Yr.NAME="SEQUENCE";ts=class extends ur{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};r8=ts;Pe.Set=r8;ts.NAME="SET";oy=class extends Jn(Rr){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=us}toJSON(){return{...super.toJSON(),value:this.value}}};oy.NAME="StringValueBlock";ay=class extends oy{};ay.NAME="SimpleStringValueBlock";rs=class extends oh{constructor({...e}={}){super(e,ay)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Ce.toUint8Array(e))}fromString(e){let r=e.length,s=this.valueBlock.valueHexView=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=e.charCodeAt(n);this.valueBlock.value=e}};rs.NAME="SIMPLE STRING";cy=class extends rs{fromBuffer(e){this.valueBlock.valueHexView=Ce.toUint8Array(e);try{this.valueBlock.value=Ve.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=Ve.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ve.FromUtf8String(e)),this.valueBlock.value=e}};cy.NAME="Utf8StringValueBlock";Ks=class extends cy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};s8=Ks;Pe.Utf8String=s8;Ks.NAME="UTF8String";dy=class extends rs{fromBuffer(e){this.valueBlock.value=Ve.ToUtf16String(e),this.valueBlock.valueHexView=Ce.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ve.FromUtf16String(e))}};dy.NAME="BmpStringValueBlock";Tc=class extends dy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};n8=Tc;Pe.BmpString=n8;Tc.NAME="BMPString";ly=class extends rs{fromBuffer(e){let r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),s=new Uint8Array(r);for(let n=0;n<s.length;n+=4)s[n]=s[n+3],s[n+1]=s[n+2],s[n+2]=0,s[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){let r=e.length,s=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let n=0;n<r;n++){let i=Zo(e.charCodeAt(n),8),o=new Uint8Array(i);if(o.length>4)continue;let a=4-o.length;for(let c=o.length-1;c>=0;c--)s[n*4+c+a]=o[c]}this.valueBlock.value=e}};ly.NAME="UniversalStringValueBlock";Ac=class extends ly{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};i8=Ac;Pe.UniversalString=i8;Ac.NAME="UniversalString";kc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};o8=kc;Pe.NumericString=o8;kc.NAME="NumericString";Ic=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};a8=Ic;Pe.PrintableString=a8;Ic.NAME="PrintableString";Rc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};c8=Rc;Pe.TeletexString=c8;Rc.NAME="TeletexString";Pc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};d8=Pc;Pe.VideotexString=d8;Pc.NAME="VideotexString";Bc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};l8=Bc;Pe.IA5String=l8;Bc.NAME="IA5String";Dc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};u8=Dc;Pe.GraphicString=u8;Dc.NAME="GraphicString";ea=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};f8=ea;Pe.VisibleString=f8;ea.NAME="VisibleString";Nc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};h8=Nc;Pe.GeneralString=h8;Nc.NAME="GeneralString";Oc=class extends rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};p8=Oc;Pe.CharacterString=p8;Oc.NAME="CharacterString";ta=class extends ea{constructor({value:e,valueDate:r,...s}={}){if(super(s),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 n=0;n<e.length;n++)this.valueBlock.valueHexView[n]=e.charCodeAt(n)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Ce.toUint8Array(e)))}toBuffer(){let e=this.toString(),r=new ArrayBuffer(e.length),s=new Uint8Array(r);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let s=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(s===null){this.error="Wrong input string for conversion";return}let n=parseInt(s[1],10);n>=50?this.year=1900+n:this.year=2e3+n,this.month=parseInt(s[2],10),this.day=parseInt(s[3],10),this.hour=parseInt(s[4],10),this.minute=parseInt(s[5],10),this.second=parseInt(s[6],10)}toString(e="iso"){if(e==="iso"){let r=new Array(7);return r[0]=ls(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=ls(this.month,2),r[2]=ls(this.day,2),r[3]=ls(this.hour,2),r[4]=ls(this.minute,2),r[5]=ls(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};m8=ta;Pe.UTCTime=m8;ta.NAME="UTCTime";Lc=class extends ta{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,s="",n="",i=0,o,a=0,c=0;if(e[e.length-1]==="Z")s=e.substring(0,e.length-1),r=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(r){if(s.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(s.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,f=s.indexOf("+"),h="";if(f===-1&&(f=s.indexOf("-"),l=-1),f!==-1){if(h=s.substring(f+1),s=s.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=l*m}}}let d=s.indexOf(".");if(d===-1&&(d=s.indexOf(",")),d!==-1){let l=new Number(`0${s.substring(d)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");i=l.valueOf(),n=s.substring(0,d)}else n=s;switch(!0){case n.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,d!==-1)throw new Error("Wrong input string for conversion");break;case n.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let l=60*i;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case n.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let l=60*i;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case n.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let l=1e3*i;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let u=o.exec(n);if(u===null)throw new Error("Wrong input string for conversion");for(let l=1;l<u.length;l++)switch(l){case 1:this.year=parseInt(u[l],10);break;case 2:this.month=parseInt(u[l],10);break;case 3:this.day=parseInt(u[l],10);break;case 4:this.hour=parseInt(u[l],10)+a;break;case 5:this.minute=parseInt(u[l],10)+c;break;case 6:this.second=parseInt(u[l],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let r=[];return r.push(ls(this.year,4)),r.push(ls(this.month,2)),r.push(ls(this.day,2)),r.push(ls(this.hour,2)),r.push(ls(this.minute,2)),r.push(ls(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(ls(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};g8=Lc;Pe.GeneralizedTime=g8;Lc.NAME="GeneralizedTime";fh=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};y8=fh;Pe.DATE=y8;fh.NAME="DATE";hh=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};x8=hh;Pe.TimeOfDay=x8;hh.NAME="TimeOfDay";ph=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};b8=ph;Pe.DateTime=b8;ph.NAME="DateTime";mh=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};w8=mh;Pe.Duration=w8;mh.NAME="Duration";gh=class extends Ks{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};v8=gh;Pe.TIME=v8;gh.NAME="TIME";Xn=class{constructor({name:e=us,optional:r=!1}={}){this.name=e,this.optional=r}},Ml=class extends Xn{constructor({value:e=[],...r}={}){super(r),this.value=e}},Uc=class extends Xn{constructor({value:e=new Xn,local:r=!1,...s}={}){super(s),this.value=e,this.local=r}},zv=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Ce.toUint8Array(e)}constructor({data:e=uy}={}){this.dataView=Ce.toUint8Array(e)}fromBER(e,r,s){let n=r+s;return this.dataView=Ce.toUint8Array(e).subarray(r,n),n}toBER(e){return this.dataView.slice().buffer}}});function _8(t){return Object.prototype.toString.call(t)}function wz(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;let e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&hy(e.buffer)}function Xv(t){return _8(t)===xz}function S8(t){return typeof SharedArrayBuffer<"u"&&_8(t)===bz}function hy(t){return Xv(t)||S8(t)}function E8(t){return wz(t)}function Wi(t){return hy(t)||E8(t)}function Yv(t){if(!Wi(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function Ws(t){return Yv(t),hy(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Sr(t){if(Yv(t),Xv(t))return t;let e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(Ws(t)),e}var xz,bz,xh=z(()=>{"use strict";g();xz="[object ArrayBuffer]",bz="[object SharedArrayBuffer]"});var C8=z(()=>{"use strict";g();xh()});function Jv(t,e,r={}){let s=Ws(t),n=Ws(e);if(!r.constantTime&&s.byteLength!==n.byteLength)return!1;let i=Math.max(s.byteLength,n.byteLength),o=s.byteLength^n.byteLength;for(let a=0;a<i;a++)o|=(s[a]??0)^(n[a]??0);return o===0}var T8=z(()=>{"use strict";g();xh()});var A8=z(()=>{"use strict";g();xh()});var Rs=z(()=>{"use strict";g();xh();C8();T8();A8()});var Z,U,Mc=z(()=>{"use strict";g();(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(Z||(Z={}));(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null"})(U||(U={}))});var Zn,k8=z(()=>{"use strict";g();ra();Rs();Zn=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Wi(e))this.unusedBits=r,this.value=Sr(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof yn))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=Sr(e.valueBlock.valueHex),this}toASN(){return new yn({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new yn({name:e})}toNumber(){let e="",r=new Uint8Array(this.value);for(let s of r)e+=s.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2),s=r.length+7>>3;this.unusedBits=(s<<3)-r.length;let n=new Uint8Array(s);r=r.padStart(s<<3,"0").split("").reverse().join("");let i=0;for(;i<s;)n[i]=parseInt(r.slice(i<<3,(i<<3)+8),2),i++;this.value=n.buffer}}});var We,I8=z(()=>{"use strict";g();ra();Rs();We=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Wi(e)?this.buffer=Sr(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof gn))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=Sr(e.valueBlock.valueHex),this}toASN(){return new gn({valueHex:this.buffer})}toSchema(e){return new gn({name:e})}}});var Qv=z(()=>{"use strict";g();k8();I8()});function Gs(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}function sa(t){switch(t){case U.Any:return Sz;case U.BitString:return Tz;case U.BmpString:return Iz;case U.Boolean:return kz;case U.CharacterString:return jz;case U.Enumerated:return Cz;case U.GeneralString:return Mz;case U.GeneralizedTime:return Hz;case U.GraphicString:return Lz;case U.IA5String:return Oz;case U.Integer:return Ez;case U.Null:return $z;case U.NumericString:return Pz;case U.ObjectIdentifier:return Az;case U.OctetString:return jl;case U.PrintableString:return Bz;case U.TeletexString:return Dz;case U.UTCTime:return Fz;case U.UniversalString:return Rz;case U.Utf8String:return Zv;case U.VideotexString:return Nz;case U.VisibleString:return Uz;default:return null}}var Sz,Ez,Cz,St,Tz,Az,kz,jl,R8,Zv,Iz,Rz,Pz,Bz,Dz,Nz,Oz,Lz,Uz,Mz,jz,Fz,Hz,$z,bh=z(()=>{"use strict";g();ra();Rs();Mc();Qv();Sz={fromASN:t=>t instanceof mn?null:Sr(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new mn;let e=Ki(t);if(e.result.error)throw new Error(e.result.error);return e.result}},Ez={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new qi({value:+t})},Cz={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new Ec({value:t})},St={fromASN:t=>Sr(t.valueBlock.valueHexView),toASN:t=>new qi({valueHex:t})},Tz={fromASN:t=>Sr(t.valueBlock.valueHexView),toASN:t=>new yn({valueHex:t})},Az={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Cc({value:t})},kz={fromASN:t=>t.valueBlock.value,toASN:t=>new Sc({value:t})},jl={fromASN:t=>Sr(t.valueBlock.valueHexView),toASN:t=>new gn({valueHex:t})},R8={fromASN:t=>new We(t.getValue()),toASN:t=>t.toASN()};Zv=Gs(Ks),Iz=Gs(Tc),Rz=Gs(Ac),Pz=Gs(kc),Bz=Gs(Ic),Dz=Gs(Rc),Nz=Gs(Pc),Oz=Gs(Bc),Lz=Gs(Dc),Uz=Gs(ea),Mz=Gs(Nc),jz=Gs(Oc),Fz={fromASN:t=>t.toDate(),toASN:t=>new ta({valueDate:t})},Hz={fromASN:t=>t.toDate(),toASN:t=>new Lc({valueDate:t})},$z={fromASN:()=>null,toASN:()=>new mn}});function Xs(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:Xs(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function t_(t){if(t){let e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:t_(e)}return!1}function P8(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),s=new Uint8Array(e);for(let n=0;n<t.byteLength;n++)if(r[n]!==s[n])return!1;return!0}var py=z(()=>{"use strict";g()});var my,B8=z(()=>{"use strict";g();ra();Mc();py();my=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){let s=this.items.get(e);if(!s)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!s.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return s}cache(e){let r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){let r={type:Z.Sequence,items:{}},s=this.findParentSchema(e);return s&&(Object.assign(r,s),r.items=Object.assign({},r.items,s.items)),r}create(e,r){let s=this.items.get(e)||this.createDefault(e),n=[];for(let i in s.items){let o=s.items[i],a=r?i:"",c;if(typeof o.type=="number"){let u=U[o.type],l=Qn[u];if(!l)throw new Error(`Cannot get ASN1 class by name '${u}'`);c=new l({name:a})}else Xs(o.type)?c=new o.type().toSchema(a):o.optional?this.get(o.type).type===Z.Choice?c=new Xn({name:a}):(c=this.create(o.type,!1),c.name=a):c=new Xn({name:a});let d=!!o.optional||o.defaultValue!==void 0;if(o.repeated){c.name="";let u=o.repeated==="set"?ts:Yr;c=new u({name:"",value:[new Uc({name:a,value:c})]})}if(o.context!==null&&o.context!==void 0)if(o.implicit)if(typeof o.type=="number"||Xs(o.type)){let u=o.repeated?ur:Vi;n.push(new u({name:a,optional:d,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);let u=!!o.repeated,l=u?c:this.get(o.type,!0).schema;l="valueBlock"in l?l.valueBlock.value:l.value,n.push(new ur({name:u?"":a,optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:l}))}else n.push(new ur({optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}));else c.optional=d,n.push(c)}switch(s.type){case Z.Sequence:return new Yr({value:n,name:""});case Z.Set:return new ts({value:n,name:""});case Z.Choice:return new Ml({value:n,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){let r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}});var fr,gy=z(()=>{"use strict";g();B8();fr=new my});var re,C,D8=z(()=>{"use strict";g();bh();Mc();gy();re=t=>e=>{let r;fr.has(e)?r=fr.get(e):(r=fr.createDefault(e),fr.set(e,r)),Object.assign(r,t)},C=t=>(e,r)=>{let s;fr.has(e.constructor)?s=fr.get(e.constructor):(s=fr.createDefault(e.constructor),fr.set(e.constructor,s));let n=Object.assign({},t);if(typeof n.type=="number"&&!n.converter){let i=sa(t.type);if(!i)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);n.converter=i}n.raw=t.raw,s.items[r]=n}});var na,N8=z(()=>{"use strict";g();na=class extends Error{schemas=[]}});var r_=z(()=>{"use strict";g();N8()});var wh,s_=z(()=>{"use strict";g();ra();Rs();Mc();bh();r_();py();gy();wh=class{static parse(e,r,s){let n=Ki(Sr(e),s?.berOptions);if(n.result.error)throw new Error(n.result.error);return this.fromASN(n.result,r,s)}static fromASN(e,r,s){try{if(Xs(r))return new r().fromASN(e);let n=fr.get(r);fr.cache(r);let i=n.schema,o=this.handleChoiceTypes(e,n,r,i,s);if(o?.result)return o.result;o?.targetSchema&&(i=o.targetSchema);let a=this.handleSequenceTypes(e,n,r,i),c=new r;return t_(r)?this.handleArrayTypes(e,n,r,s):(this.processSchemaItems(n,a,c,s),c)}catch(n){throw n instanceof na&&n.schemas.push(r.name),n}}static handleChoiceTypes(e,r,s,n,i){if(e.constructor===ur&&r.type===Z.Choice&&e.idBlock.tagClass===3)for(let o in r.items){let a=r.items[o];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&fr.has(a.type)){let c=fr.get(a.type);if(c&&c.type===Z.Sequence){let d=new Yr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in d.valueBlock){d.valueBlock.value=e.valueBlock.value;let u=this.fromASN(d,a.type,i),l=new s;return l[o]=u,{result:l}}}}}else if(e.constructor===ur&&r.type!==Z.Choice){let o=new ur({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(let a in r.items)delete e[a];return{targetSchema:o}}return null}static handleSequenceTypes(e,r,s,n){if(r.type===Z.Sequence){let i=Hi({},e,n);if(!i.verified)throw new na(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}else{let i=Hi({},e,n);if(!i.verified)throw new na(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}}static processRepeatedField(e,r,s){let n=e.slice(r);if(n.length===1&&n[0].constructor.name==="Sequence"){let i=n[0];i.valueBlock&&i.valueBlock.value&&Array.isArray(i.valueBlock.value)&&(n=i.valueBlock.value)}if(typeof s.type=="number"){let i=sa(s.type);if(!i)throw new Error(`No converter for ASN.1 type ${s.type}`);return n.filter(o=>o&&o.valueBlock).map(o=>{try{return i.fromASN(o)}catch{return}}).filter(o=>o!==void 0)}else return n.filter(i=>i&&i.valueBlock).map(i=>{try{return this.fromASN(i,s.type)}catch{return}}).filter(i=>i!==void 0)}static processPrimitiveField(e,r){let s=sa(r.type);if(!s)throw new Error(`No converter for ASN.1 type ${r.type}`);return s.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&fr.has(e.type)&&fr.get(e.type).type===Z.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(s){if(s instanceof na&&/Wrong values for Choice type/.test(s.message))return{processed:!1};throw s}}static handleArrayTypes(e,r,s,n){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let i=r.itemType;if(typeof i=="number"){let o=sa(i);if(!o)throw new Error(`Cannot get default converter for array item of ${s.name} ASN1 schema`);return s.from(e.valueBlock.value,a=>o.fromASN(a))}else return s.from(e.valueBlock.value,o=>this.fromASN(o,i,n))}static processSchemaItems(e,r,s,n){for(let i in e.items){let o=r.result[i];if(!o)continue;let a=e.items[i],c=a.type,d;typeof c=="number"||Xs(c)?d=this.processPrimitiveSchemaItem(o,a,c,n):d=this.processComplexSchemaItem(o,a,c,n),d&&typeof d=="object"&&"value"in d&&"raw"in d?(s[i]=d.value,s[`${i}Raw`]=d.raw):s[i]=d}}static processPrimitiveSchemaItem(e,r,s,n){let i=r.converter??(Xs(s)?new s:null);if(!i)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,i,n):this.processSinglePrimitiveItem(e,r,s,i,n)}static processRepeatedPrimitiveItem(e,r,s,n){if(r.implicit){let i=r.repeated==="sequence"?Yr:ts,o=new i;o.valueBlock=e.valueBlock;let a=Ki(o.toBER(!1),n?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=a.result.valueBlock.value;return Array.from(c,d=>s.fromASN(d))}else return Array.from(e,i=>s.fromASN(i))}static processSinglePrimitiveItem(e,r,s,n,i){let o=e;if(r.implicit){let a;if(Xs(s))a=new s().toSchema("");else{let c=U[s],d=Qn[c];if(!d)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new d}a.valueBlock=o.valueBlock,o=Ki(a.toBER(!1),i?.berOptions).result}return n.fromASN(o)}static processComplexSchemaItem(e,r,s,n){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,s,n))}else{let i=this.handleImplicitTagging(e,r,s);if(this.isOptionalChoiceField(r))try{return this.fromASN(i,s,n)}catch(o){if(o instanceof na&&/Wrong values for Choice type/.test(o.message))return;throw o}else{let o=this.fromASN(i,s,n);return r.raw?{value:o,raw:e.valueBeforeDecodeView}:o}}}static handleImplicitTagging(e,r,s){if(r.implicit&&typeof r.context=="number"){let n=fr.get(s);if(n.type===Z.Sequence){let i=new Yr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}else if(n.type===Z.Set){let i=new ts;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}}return e}}});var vh,n_=z(()=>{"use strict";g();ra();Rs();bh();Mc();py();gy();vh=class t{static serialize(e){return e instanceof lr?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&Xs(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let r=e.constructor,s=fr.get(r);fr.cache(r);let n=[];if(s.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof s.itemType=="number"){let o=sa(s.itemType);if(!o)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);n=e.map(a=>o.toASN(a))}else n=e.map(o=>this.toAsnItem({type:s.itemType},"[]",r,o))}else for(let o in s.items){let a=s.items[o],c=e[o];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&P8(this.serialize(a.defaultValue),this.serialize(c)))continue;let d=t.toAsnItem(a,o,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||Xs(a.type))){let u={};u.valueHex=d instanceof mn?Sr(d.valueBeforeDecodeView):d.valueBlock.toBER(),n.push(new Vi({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...u}))}else n.push(new ur({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:d.valueBlock.value}));else n.push(new ur({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[d]}));else a.repeated?n=n.concat(d):n.push(d)}let i;switch(s.type){case Z.Sequence:i=new Yr({value:n});break;case Z.Set:i=new ts({value:n});break;case Z.Choice:if(!n[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);i=n[0];break}return i}static toAsnItem(e,r,s,n){let i;if(typeof e.type=="number"){let o=e.converter;if(!o)throw new Error(`Property '${r}' doesn't have converter for type ${U[e.type]} in schema '${s.name}'`);if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(n,d=>o.toASN(d)),c=e.repeated==="sequence"?Yr:ts;i=new c({value:a})}else i=o.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let o=Array.from(n,c=>this.toASN(c)),a=e.repeated==="sequence"?Yr:ts;i=new a({value:o})}else i=this.toASN(n);return i}}});var qe,O8=z(()=>{"use strict";g();qe=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let r of e)this.push(r)}}}});var _e,L8=z(()=>{"use strict";g();ra();Rs();s_();n_();_e=class t{static serialize(e){return vh.serialize(e)}static parse(e,r,s){return wh.parse(e,r,s)}static toString(e,r){let s=Wi(e)?Sr(e):t.serialize(e),n=Ki(s,r?.berOptions);if(n.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}}});var le=z(()=>{"use strict";g();bh();Qv();D8();Mc();s_();n_();r_();O8();L8()});function b(t,e,r,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,r):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,s);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(n<3?o(i):n>3?o(e,r,i):o(e,r))||i);return n>3&&i&&Object.defineProperty(e,r,i),i}function ft(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}function Wt(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}var fe=z(()=>{"use strict";g()});var i_=z(()=>{"use strict";g();Rs()});var Fl={};ic(Fl,{decode:()=>a_,encode:()=>o_,format:()=>H8,formats:()=>$8,hex:()=>eK,is:()=>j8,normalize:()=>_h,parse:()=>F8});function Kz(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?zz:t.separators}function Wz(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function Gz(t,e,r){for(let s of r)if(t.startsWith(s,e))return s}function Xz(t){let e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function Yz(t){let e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
23
+ `?`\r
24
+ `:`
25
+ `}function U8(t){return t.replace(/[^0-9a-f]/gi,"")}function Jz(t){let e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let r=e.filter((o,a)=>a%2===0),s=e.filter((o,a)=>a%2===1),n=s[0];if(!n||s.some(o=>o!==n)||r.some(o=>o.length===0||o.length%2!==0))return;let i=r[0]?.length??0;if(i&&!r.slice(0,-1).some(o=>o.length!==i)&&!((r[r.length-1]?.length??0)>i))return{size:i/2,separator:n}}function Qz(t){let e=t.trim(),r=/^0x/i.test(e)?"0x":"",s=r?e.slice(2):e,n=Yz(s),i=s.split(/\r\n|\n/).filter(d=>d.length>0),o=i[0]?.trim()??"",a=Jz(o),c={case:Xz(e),prefix:r};if(a&&(c.group=a),n&&i.length>1){let d=U8(i[0]??"").length/2;d>0&&i.slice(0,-1).every(u=>U8(u).length/2===d)&&(c.line={bytesPerLine:d,separator:n})}return c}function Zz(t,e){let r=e.allowPrefix??!0,s=[...Kz(e)].sort((a,c)=>c.length-a.length);for(let a of s)Wz(a);let n=t.trim();if(/^0x/i.test(n)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");n=n.slice(2)}let i="",o=!1;for(let a=0;a<n.length;){let c=n[a]??"";if(qz.test(c)){i+=c,o=!1,a+=1;continue}let d=Gz(n,a,s);if(!d)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(o||i.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");o=!0,a+=d.length}if(e.strict&&o&&i.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(i.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");i=`0${i}`}return i.toLowerCase()}function M8(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let r=[];for(let s=0;s<t.length;s+=e.size)r.push(t.slice(s,s+e.size).join(""));return r.join(e.separator)}function _h(t,e={}){return Zz(t,e)}function j8(t,e={}){if(typeof t!="string")return!1;try{return _h(t,e),!0}catch{return!1}}function o_(t,e={}){let r=Ws(t),s=e.case??"lower",n=Array.from(r,o=>{let a=o.toString(16).padStart(2,"0");return s==="upper"?a.toUpperCase():a}),i="";if(e.line){let o=e.line.bytesPerLine;if(!Number.isInteger(o)||o<1)throw new RangeError("Hex bytesPerLine must be a positive integer");let a=e.line.separator??`
26
+ `,c=[];for(let d=0;d<n.length;d+=o)c.push(M8(n.slice(d,d+o),e.group));i=c.join(a)}else i=M8(n,e.group);return`${e.prefix??""}${i}`}function a_(t,e={}){let r=_h(t,e),s=new Uint8Array(r.length/2);for(let n=0;n<r.length;n+=2)s[n/2]=Number.parseInt(r.slice(n,n+2),16);return s}function F8(t,e={}){let r=_h(t,e);return{bytes:a_(r),format:Qz(t),normalized:r}}function H8(t,e){return o_(t,e)}var qz,zz,$8,eK,V8=z(()=>{"use strict";g();Rs();qz=/^[0-9a-f]$/i,zz=[" "," ",`
27
+ `,"\r",":","-","."];$8={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})},eK={encode:o_,decode:a_,format:H8,formats:$8,is:j8,normalize:_h,parse:F8}});var q8=z(()=>{"use strict";g();Rs()});var z8=z(()=>{"use strict";g();Rs()});var c_=z(()=>{"use strict";g();Rs();i_()});var K8=z(()=>{"use strict";g();c_()});var d_=z(()=>{"use strict";g();i_();V8();q8();z8();c_();K8()});var Sh,W8=z(()=>{"use strict";g();d_();Sh=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(s=>{let n=parseInt(s,10);if(isNaN(n)||n<0||n>255)throw new Error("Invalid IPv4 address part");return n})}static parseIPv6(e){let s=this.expandIPv6(e).split(":");if(s.length!==8)throw new Error("Invalid IPv6 address");return s.reduce((n,i)=>{let o=parseInt(i,16);if(isNaN(o)||o<0||o>65535)throw new Error("Invalid IPv6 address part");return n.push(o>>8&255),n.push(o&255),n},[])}static expandIPv6(e){if(!e.includes("::"))return e;let r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");let s=r[0]?r[0].split(":"):[],n=r[1]?r[1].split(":"):[],i=8-(s.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...s,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){let r=[];for(let s=0;s<16;s+=2)r.push((e[s]<<8|e[s+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){let r=e.split(":"),s=-1,n=0,i=-1,o=0;for(let a=0;a<r.length;a++)r[a]==="0"?(i===-1&&(i=a),o++):(o>n&&(s=i,n=o),i=-1,o=0);if(o>n&&(s=i,n=o),n>1){let a=r.slice(0,s).join(":"),c=r.slice(s+n).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[r,s]=e.split("/"),n=parseInt(s,10);if(this.isIPv4(r)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),n]}else{if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let r=parseInt(e.slice(8),16).toString(2).split("").reduce((n,i)=>n+ +i,0),s=e.slice(0,8).replace(/(.{2})/g,n=>`${parseInt(n,16)}.`);return s=s.slice(0,-1),`${s}/${r}`}static toString(e){let r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){let s=r.length/2,n=r.slice(0,s),i=r.slice(s);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,d)=>c+(d.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(n).join(".")}/${a}`:`${this.formatIPv6(n)}/${a}`}return this.decodeIP(Fl.encode(e))}static fromString(e){if(e.includes("/")){let[s,n]=this.parseCIDR(e),i=new Uint8Array(s.length),o=n;for(let c=0;c<i.length;c++)o>=8?(i[c]=255,o-=8):o>0&&(i[c]=255<<8-o,o=0);let a=new Uint8Array(s.length*2);return a.set(s,0),a.set(i,s.length),a.buffer}let r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}});var l_,u_,f_,hr,Hl,jc,ia,h_,jt,$l=z(()=>{"use strict";g();fe();le();d_();hr=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};b([C({type:U.TeletexString})],hr.prototype,"teletexString",void 0);b([C({type:U.PrintableString})],hr.prototype,"printableString",void 0);b([C({type:U.UniversalString})],hr.prototype,"universalString",void 0);b([C({type:U.Utf8String})],hr.prototype,"utf8String",void 0);b([C({type:U.BmpString})],hr.prototype,"bmpString",void 0);hr=b([re({type:Z.Choice})],hr);Hl=class extends hr{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Fl.encode(this.anyValue):super.toString())}};b([C({type:U.IA5String})],Hl.prototype,"ia5String",void 0);b([C({type:U.Any})],Hl.prototype,"anyValue",void 0);Hl=b([re({type:Z.Choice})],Hl);jc=class{type="";value=new Hl;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],jc.prototype,"type",void 0);b([C({type:Hl})],jc.prototype,"value",void 0);ia=l_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,l_.prototype)}};ia=l_=b([re({type:Z.Set,itemType:jc})],ia);h_=u_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,u_.prototype)}};h_=u_=b([re({type:Z.Sequence,itemType:ia})],h_);jt=f_=class extends h_{constructor(e){super(e),Object.setPrototypeOf(this,f_.prototype)}};jt=f_=b([re({type:Z.Sequence})],jt)});var iK,oa,Eh,Je,Fc=z(()=>{"use strict";g();fe();le();W8();$l();iK={fromASN:t=>Sh.toString(jl.fromASN(t)),toASN:t=>jl.toASN(Sh.fromString(t))},oa=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],oa.prototype,"typeId",void 0);b([C({type:U.Any,context:0})],oa.prototype,"value",void 0);Eh=class{nameAssigner;partyName=new hr;constructor(e={}){Object.assign(this,e)}};b([C({type:hr,optional:!0,context:0,implicit:!0})],Eh.prototype,"nameAssigner",void 0);b([C({type:hr,context:1,implicit:!0})],Eh.prototype,"partyName",void 0);Je=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};b([C({type:oa,context:0,implicit:!0})],Je.prototype,"otherName",void 0);b([C({type:U.IA5String,context:1,implicit:!0})],Je.prototype,"rfc822Name",void 0);b([C({type:U.IA5String,context:2,implicit:!0})],Je.prototype,"dNSName",void 0);b([C({type:U.Any,context:3,implicit:!0})],Je.prototype,"x400Address",void 0);b([C({type:jt,context:4,implicit:!1})],Je.prototype,"directoryName",void 0);b([C({type:Eh,context:5})],Je.prototype,"ediPartyName",void 0);b([C({type:U.IA5String,context:6,implicit:!0})],Je.prototype,"uniformResourceIdentifier",void 0);b([C({type:U.OctetString,context:7,implicit:!0,converter:iK})],Je.prototype,"iPAddress",void 0);b([C({type:U.ObjectIdentifier,context:8,implicit:!0})],Je.prototype,"registeredID",void 0);Je=b([re({type:Z.Choice})],Je)});var aa,ca,G8,Hc,yy,jae,Fae,p_,m_,g_,y_,ot,qt=z(()=>{"use strict";g();aa="1.3.6.1.5.5.7",ca=`${aa}.1`,G8=`${aa}.2`,Hc=`${aa}.3`,yy=`${aa}.48`,jae=`${G8}.1`,Fae=`${G8}.2`,p_=`${yy}.1`,m_=`${yy}.2`,g_=`${yy}.3`,y_=`${yy}.5`,ot="2.5.29"});var x_,xy,Gi,$c,b_=z(()=>{"use strict";g();fe();le();Fc();qt();xy=`${ca}.1`,Gi=class{accessMethod="";accessLocation=new Je;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Gi.prototype,"accessMethod",void 0);b([C({type:Je})],Gi.prototype,"accessLocation",void 0);$c=x_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,x_.prototype)}};$c=x_=b([re({type:Z.Sequence,itemType:Gi})],$c)});var by,Vc,ei,w_=z(()=>{"use strict";g();fe();le();Fc();qt();by=`${ot}.35`,Vc=class extends We{},ei=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};b([C({type:Vc,context:0,optional:!0,implicit:!0})],ei.prototype,"keyIdentifier",void 0);b([C({type:Je,context:1,optional:!0,implicit:!0,repeated:"sequence"})],ei.prototype,"authorityCertIssuer",void 0);b([C({type:U.Integer,context:2,optional:!0,implicit:!0,converter:St})],ei.prototype,"authorityCertSerialNumber",void 0)});var wy,qc,X8=z(()=>{"use strict";g();fe();le();qt();wy=`${ot}.19`,qc=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Boolean,defaultValue:!1})],qc.prototype,"cA",void 0);b([C({type:U.Integer,optional:!0})],qc.prototype,"pathLenConstraint",void 0)});var v_,Gt,Ch=z(()=>{"use strict";g();fe();le();Fc();Gt=v_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,v_.prototype)}};Gt=v_=b([re({type:Z.Sequence,itemType:Je})],Gt)});var __,oK,Y8,J8=z(()=>{"use strict";g();fe();le();Ch();qt();oK=`${ot}.29`,Y8=__=class extends Gt{constructor(e){super(e),Object.setPrototypeOf(this,__.prototype)}};Y8=__=b([re({type:Z.Sequence})],Y8)});var S_,_y,Sce,Xi,Th,Ah,vy,kh,zc,Ih,Q8=z(()=>{"use strict";g();fe();le();qt();_y=`${ot}.32`,Sce=`${_y}.0`,Xi=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};b([C({type:U.IA5String})],Xi.prototype,"ia5String",void 0);b([C({type:U.VisibleString})],Xi.prototype,"visibleString",void 0);b([C({type:U.BmpString})],Xi.prototype,"bmpString",void 0);b([C({type:U.Utf8String})],Xi.prototype,"utf8String",void 0);Xi=b([re({type:Z.Choice})],Xi);Th=class{organization=new Xi;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};b([C({type:Xi})],Th.prototype,"organization",void 0);b([C({type:U.Integer,repeated:"sequence"})],Th.prototype,"noticeNumbers",void 0);Ah=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};b([C({type:Th,optional:!0})],Ah.prototype,"noticeRef",void 0);b([C({type:Xi,optional:!0})],Ah.prototype,"explicitText",void 0);vy=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};b([C({type:U.IA5String})],vy.prototype,"cPSuri",void 0);b([C({type:Ah})],vy.prototype,"userNotice",void 0);vy=b([re({type:Z.Choice})],vy);kh=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],kh.prototype,"policyQualifierId",void 0);b([C({type:U.Any})],kh.prototype,"qualifier",void 0);zc=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],zc.prototype,"policyIdentifier",void 0);b([C({type:kh,repeated:"sequence",optional:!0})],zc.prototype,"policyQualifiers",void 0);Ih=S_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,S_.prototype)}};Ih=S_=b([re({type:Z.Sequence,itemType:zc})],Ih)});var Bce,Rh,E_=z(()=>{"use strict";g();fe();le();qt();Bce=`${ot}.20`,Rh=class{value;constructor(e=0){this.value=e}};b([C({type:U.Integer})],Rh.prototype,"value",void 0);Rh=b([re({type:Z.Choice})],Rh)});var Fce,Z8,e4=z(()=>{"use strict";g();fe();le();qt();E_();Fce=`${ot}.27`,Z8=class extends Rh{};Z8=b([re({type:Z.Choice})],Z8)});var C_,Sy,xn,Ph,Yi,ti,da,Ey=z(()=>{"use strict";g();fe();le();$l();Fc();qt();Sy=`${ot}.31`;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(xn||(xn={}));Ph=class extends Zn{toJSON(){let e=[],r=this.toNumber();return r&xn.aACompromise&&e.push("aACompromise"),r&xn.affiliationChanged&&e.push("affiliationChanged"),r&xn.cACompromise&&e.push("cACompromise"),r&xn.certificateHold&&e.push("certificateHold"),r&xn.cessationOfOperation&&e.push("cessationOfOperation"),r&xn.keyCompromise&&e.push("keyCompromise"),r&xn.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&xn.superseded&&e.push("superseded"),r&xn.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Yi=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};b([C({type:Je,context:0,repeated:"sequence",implicit:!0})],Yi.prototype,"fullName",void 0);b([C({type:ia,context:1,implicit:!0})],Yi.prototype,"nameRelativeToCRLIssuer",void 0);Yi=b([re({type:Z.Choice})],Yi);ti=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};b([C({type:Yi,context:0,optional:!0})],ti.prototype,"distributionPoint",void 0);b([C({type:Ph,context:1,optional:!0,implicit:!0})],ti.prototype,"reasons",void 0);b([C({type:Je,context:2,optional:!0,repeated:"sequence",implicit:!0})],ti.prototype,"cRLIssuer",void 0);da=C_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,C_.prototype)}};da=C_=b([re({type:Z.Sequence,itemType:ti})],da)});var T_,sde,t4,r4=z(()=>{"use strict";g();fe();le();qt();Ey();sde=`${ot}.46`,t4=T_=class extends da{constructor(e){super(e),Object.setPrototypeOf(this,T_.prototype)}};t4=T_=b([re({type:Z.Sequence,itemType:ti})],t4)});var ude,Ys,s4=z(()=>{"use strict";g();fe();le();qt();Ey();ude=`${ot}.28`,Ys=class t{static ONLY=!1;distributionPoint;onlyContainsUserCerts=t.ONLY;onlyContainsCACerts=t.ONLY;onlySomeReasons;indirectCRL=t.ONLY;onlyContainsAttributeCerts=t.ONLY;constructor(e={}){Object.assign(this,e)}};b([C({type:Yi,context:0,optional:!0})],Ys.prototype,"distributionPoint",void 0);b([C({type:U.Boolean,context:1,defaultValue:Ys.ONLY,implicit:!0})],Ys.prototype,"onlyContainsUserCerts",void 0);b([C({type:U.Boolean,context:2,defaultValue:Ys.ONLY,implicit:!0})],Ys.prototype,"onlyContainsCACerts",void 0);b([C({type:Ph,context:3,optional:!0,implicit:!0})],Ys.prototype,"onlySomeReasons",void 0);b([C({type:U.Boolean,context:4,defaultValue:Ys.ONLY,implicit:!0})],Ys.prototype,"indirectCRL",void 0);b([C({type:U.Boolean,context:5,defaultValue:Ys.ONLY,implicit:!0})],Ys.prototype,"onlyContainsAttributeCerts",void 0)});var n4,Bh,Dh,i4=z(()=>{"use strict";g();fe();le();qt();n4=`${ot}.21`;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Bh||(Bh={}));Dh=class{reason=Bh.unspecified;constructor(e=Bh.unspecified){this.reason=e}toJSON(){return Bh[this.reason]}toString(){return this.toJSON()}};b([C({type:U.Enumerated})],Dh.prototype,"reason",void 0);Dh=b([re({type:Z.Choice})],Dh)});var A_,Cy,Nh,Ede,o4,a4,c4,d4,l4,u4,f4=z(()=>{"use strict";g();fe();le();qt();Cy=`${ot}.37`,Nh=A_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,A_.prototype)}};Nh=A_=b([re({type:Z.Sequence,itemType:U.ObjectIdentifier})],Nh);Ede=`${Cy}.0`,o4=`${Hc}.1`,a4=`${Hc}.2`,c4=`${Hc}.3`,d4=`${Hc}.4`,l4=`${Hc}.8`,u4=`${Hc}.9`});var Rde,k_,h4=z(()=>{"use strict";g();fe();le();qt();Rde=`${ot}.54`,k_=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};b([C({type:U.Integer,converter:St})],k_.prototype,"value",void 0);k_=b([re({type:Z.Choice})],k_)});var p4,Oh,m4=z(()=>{"use strict";g();fe();le();qt();p4=`${ot}.24`,Oh=class{value=new Date;constructor(e){e&&(this.value=e)}};b([C({type:U.GeneralizedTime})],Oh.prototype,"value",void 0);Oh=b([re({type:Z.Choice})],Oh)});var I_,R_,g4,y4=z(()=>{"use strict";g();fe();le();Ch();qt();R_=`${ot}.18`,g4=I_=class extends Gt{constructor(e){super(e),Object.setPrototypeOf(this,I_.prototype)}};g4=I_=b([re({type:Z.Sequence})],g4)});var Ty,bn,Vl,x4=z(()=>{"use strict";g();le();qt();Ty=`${ot}.15`;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(bn||(bn={}));Vl=class extends Zn{toJSON(){let e=this.toNumber(),r=[];return e&bn.cRLSign&&r.push("crlSign"),e&bn.dataEncipherment&&r.push("dataEncipherment"),e&bn.decipherOnly&&r.push("decipherOnly"),e&bn.digitalSignature&&r.push("digitalSignature"),e&bn.encipherOnly&&r.push("encipherOnly"),e&bn.keyAgreement&&r.push("keyAgreement"),e&bn.keyCertSign&&r.push("keyCertSign"),e&bn.keyEncipherment&&r.push("keyEncipherment"),e&bn.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}});var P_,tle,ql,Ay,ky,b4=z(()=>{"use strict";g();fe();le();Fc();qt();tle=`${ot}.30`,ql=class{base=new Je;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};b([C({type:Je})],ql.prototype,"base",void 0);b([C({type:U.Integer,context:0,defaultValue:0,implicit:!0})],ql.prototype,"minimum",void 0);b([C({type:U.Integer,context:1,optional:!0,implicit:!0})],ql.prototype,"maximum",void 0);Ay=P_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,P_.prototype)}};Ay=P_=b([re({type:Z.Sequence,itemType:ql})],Ay);ky=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};b([C({type:Ay,context:0,optional:!0,implicit:!0})],ky.prototype,"permittedSubtrees",void 0);b([C({type:Ay,context:1,optional:!0,implicit:!0})],ky.prototype,"excludedSubtrees",void 0)});var cle,Iy,w4=z(()=>{"use strict";g();fe();le();qt();cle=`${ot}.36`,Iy=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,context:0,implicit:!0,optional:!0,converter:St})],Iy.prototype,"requireExplicitPolicy",void 0);b([C({type:U.Integer,context:1,implicit:!0,optional:!0,converter:St})],Iy.prototype,"inhibitPolicyMapping",void 0)});var B_,ple,Lh,v4,_4=z(()=>{"use strict";g();fe();le();qt();ple=`${ot}.33`,Lh=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Lh.prototype,"issuerDomainPolicy",void 0);b([C({type:U.ObjectIdentifier})],Lh.prototype,"subjectDomainPolicy",void 0);v4=B_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,B_.prototype)}};v4=B_=b([re({type:Z.Sequence,itemType:Lh})],v4)});var D_,N_,Ry,S4=z(()=>{"use strict";g();fe();le();Ch();qt();N_=`${ot}.17`,Ry=D_=class extends Gt{constructor(e){super(e),Object.setPrototypeOf(this,D_.prototype)}};Ry=D_=b([re({type:Z.Sequence})],Ry)});var Br,O_=z(()=>{"use strict";g();fe();le();Br=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Br.prototype,"type",void 0);b([C({type:U.Any,repeated:"set"})],Br.prototype,"values",void 0)});var L_,Dle,E4,C4=z(()=>{"use strict";g();fe();le();O_();qt();Dle=`${ot}.9`,E4=L_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,L_.prototype)}};E4=L_=b([re({type:Z.Sequence,itemType:Br})],E4)});var U_,fs,T4=z(()=>{"use strict";g();qt();w_();U_=`${ot}.14`,fs=class extends Vc{}});var qle,Py,A4=z(()=>{"use strict";g();fe();le();qt();qle=`${ot}.16`,Py=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};b([C({type:U.GeneralizedTime,context:0,implicit:!0,optional:!0})],Py.prototype,"notBefore",void 0);b([C({type:U.GeneralizedTime,context:1,implicit:!0,optional:!0})],Py.prototype,"notAfter",void 0)});var Uh,By,Dy,k4=z(()=>{"use strict";g();fe();le();(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(Uh||(Uh={}));By=class extends Zn{toJSON(){let e=[],r=this.toNumber();return r&Uh.pKIXCertificate&&e.push("pKIXCertificate"),r&Uh.newExtensions&&e.push("newExtensions"),r&Uh.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Dy=class{entrustVers="";entrustInfoFlags=new By;constructor(e={}){Object.assign(this,e)}};b([C({type:U.GeneralString})],Dy.prototype,"entrustVers",void 0);b([C({type:By})],Dy.prototype,"entrustInfoFlags",void 0)});var M_,tue,I4,R4=z(()=>{"use strict";g();fe();le();qt();b_();tue=`${ca}.11`,I4=M_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,M_.prototype)}};I4=M_=b([re({type:Z.Sequence,itemType:Gi})],I4)});var P4=z(()=>{"use strict";g();b_();w_();X8();J8();Q8();e4();Ey();r4();s4();E_();i4();f4();h4();m4();y4();x4();b4();w4();_4();S4();C4();T4();A4();k4();R4()});var be,Kc=z(()=>{"use strict";g();fe();le();Rs();be=class t{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof t&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Jv(e.parameters,this.parameters)||e.parameters===this.parameters)}};b([C({type:U.ObjectIdentifier})],be.prototype,"algorithm",void 0);b([C({type:U.Any,optional:!0})],be.prototype,"parameters",void 0)});var Dr,j_=z(()=>{"use strict";g();fe();le();Kc();Dr=class{algorithm=new be;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:be})],Dr.prototype,"algorithm",void 0);b([C({type:U.BitString})],Dr.prototype,"subjectPublicKey",void 0)});var ar,Ny=z(()=>{"use strict";g();fe();le();ar=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};b([C({type:U.UTCTime})],ar.prototype,"utcTime",void 0);b([C({type:U.GeneralizedTime})],ar.prototype,"generalTime",void 0);ar=b([re({type:Z.Choice})],ar)});var Ji,F_=z(()=>{"use strict";g();fe();le();Ny();Ji=class{notBefore=new ar(new Date);notAfter=new ar(new Date);constructor(e){e&&(this.notBefore=new ar(e.notBefore),this.notAfter=new ar(e.notAfter))}};b([C({type:ar})],Ji.prototype,"notBefore",void 0);b([C({type:ar})],Ji.prototype,"notAfter",void 0)});var H_,Jr,Ps,Oy=z(()=>{"use strict";g();fe();le();Jr=class t{static CRITICAL=!1;extnID="";critical=t.CRITICAL;extnValue=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Jr.prototype,"extnID",void 0);b([C({type:U.Boolean,defaultValue:Jr.CRITICAL})],Jr.prototype,"critical",void 0);b([C({type:We})],Jr.prototype,"extnValue",void 0);Ps=H_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,H_.prototype)}};Ps=H_=b([re({type:Z.Sequence,itemType:Jr})],Ps)});var ri,$_=z(()=>{"use strict";g();(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(ri||(ri={}))});var Nr,V_=z(()=>{"use strict";g();fe();le();Kc();$l();j_();F_();Oy();$_();Nr=class{version=ri.v1;serialNumber=new ArrayBuffer(0);signature=new be;issuer=new jt;validity=new Ji;subject=new jt;subjectPublicKeyInfo=new Dr;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,context:0,defaultValue:ri.v1})],Nr.prototype,"version",void 0);b([C({type:U.Integer,converter:St})],Nr.prototype,"serialNumber",void 0);b([C({type:be})],Nr.prototype,"signature",void 0);b([C({type:jt})],Nr.prototype,"issuer",void 0);b([C({type:Ji})],Nr.prototype,"validity",void 0);b([C({type:jt})],Nr.prototype,"subject",void 0);b([C({type:Dr})],Nr.prototype,"subjectPublicKeyInfo",void 0);b([C({type:U.BitString,context:1,implicit:!0,optional:!0})],Nr.prototype,"issuerUniqueID",void 0);b([C({type:U.BitString,context:2,implicit:!0,optional:!0})],Nr.prototype,"subjectUniqueID",void 0);b([C({type:Ps,context:3,optional:!0})],Nr.prototype,"extensions",void 0)});var Js,B4=z(()=>{"use strict";g();fe();le();Kc();V_();Js=class{tbsCertificate=new Nr;tbsCertificateRaw;signatureAlgorithm=new be;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:Nr,raw:!0})],Js.prototype,"tbsCertificate",void 0);b([C({type:be})],Js.prototype,"signatureAlgorithm",void 0);b([C({type:U.BitString})],Js.prototype,"signatureValue",void 0)});var Wc,Bs,q_=z(()=>{"use strict";g();fe();le();Kc();$l();Ny();Oy();Wc=class{userCertificate=new ArrayBuffer(0);revocationDate=new ar;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,converter:St})],Wc.prototype,"userCertificate",void 0);b([C({type:ar})],Wc.prototype,"revocationDate",void 0);b([C({type:Jr,optional:!0,repeated:"sequence"})],Wc.prototype,"crlEntryExtensions",void 0);Bs=class{version;signature=new be;issuer=new jt;thisUpdate=new ar;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,optional:!0})],Bs.prototype,"version",void 0);b([C({type:be})],Bs.prototype,"signature",void 0);b([C({type:jt})],Bs.prototype,"issuer",void 0);b([C({type:ar})],Bs.prototype,"thisUpdate",void 0);b([C({type:ar,optional:!0})],Bs.prototype,"nextUpdate",void 0);b([C({type:Wc,repeated:"sequence",optional:!0})],Bs.prototype,"revokedCertificates",void 0);b([C({type:Jr,optional:!0,context:0,repeated:"sequence"})],Bs.prototype,"crlExtensions",void 0)});var Gc,D4=z(()=>{"use strict";g();fe();le();Kc();q_();Gc=class{tbsCertList=new Bs;tbsCertListRaw;signatureAlgorithm=new be;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:Bs,raw:!0})],Gc.prototype,"tbsCertList",void 0);b([C({type:be})],Gc.prototype,"signatureAlgorithm",void 0);b([C({type:U.BitString})],Gc.prototype,"signature",void 0)});var Ct=z(()=>{"use strict";g();P4();Kc();O_();B4();D4();Oy();Fc();Ch();$l();qt();j_();q_();V_();Ny();$_();F_()});var wn,Mh=z(()=>{"use strict";g();fe();le();Ct();wn=class{issuer=new jt;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:jt})],wn.prototype,"issuer",void 0);b([C({type:U.Integer,converter:St})],wn.prototype,"serialNumber",void 0)});var Xc,z_=z(()=>{"use strict";g();fe();le();Ct();Mh();Xc=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};b([C({type:fs,context:0,implicit:!0})],Xc.prototype,"subjectKeyIdentifier",void 0);b([C({type:wn})],Xc.prototype,"issuerAndSerialNumber",void 0);Xc=b([re({type:Z.Choice})],Xc)});var Or,Yc,jh,hs,Fh,O4,Ly,si=z(()=>{"use strict";g();fe();Ct();le();(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(Or||(Or={}));Yc=class extends be{};Yc=b([re({type:Z.Sequence})],Yc);jh=class extends be{};jh=b([re({type:Z.Sequence})],jh);hs=class extends be{};hs=b([re({type:Z.Sequence})],hs);Fh=class extends be{};Fh=b([re({type:Z.Sequence})],Fh);O4=class extends be{};O4=b([re({type:Z.Sequence})],O4);Ly=class extends be{};Ly=b([re({type:Z.Sequence})],Ly)});var vn,Uy=z(()=>{"use strict";g();fe();le();vn=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],vn.prototype,"attrType",void 0);b([C({type:U.Any,repeated:"set"})],vn.prototype,"attrValues",void 0)});var K_,ps,Hh,My=z(()=>{"use strict";g();fe();le();z_();si();Uy();ps=class{version=Or.v0;sid=new Xc;digestAlgorithm=new Yc;signedAttrs;signedAttrsRaw;signatureAlgorithm=new jh;signature=new We;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],ps.prototype,"version",void 0);b([C({type:Xc})],ps.prototype,"sid",void 0);b([C({type:Yc})],ps.prototype,"digestAlgorithm",void 0);b([C({type:vn,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],ps.prototype,"signedAttrs",void 0);b([C({type:jh})],ps.prototype,"signatureAlgorithm",void 0);b([C({type:We})],ps.prototype,"signature",void 0);b([C({type:vn,repeated:"set",context:1,implicit:!0,optional:!0})],ps.prototype,"unsignedAttrs",void 0);Hh=K_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,K_.prototype)}};Hh=K_=b([re({type:Z.Set,itemType:ps})],Hh)});var L4,U4=z(()=>{"use strict";g();fe();le();My();L4=class extends ps{};L4=b([re({type:Z.Sequence})],L4)});var M4=z(()=>{"use strict";g();le()});var j4,F4=z(()=>{"use strict";g();fe();Ct();le();j4=class extends ar{};j4=b([re({type:Z.Choice})],j4)});var H4=z(()=>{"use strict";g();U4();M4();F4()});var $h,$4=z(()=>{"use strict";g();fe();le();Ct();$h=class{acIssuer=new Je;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};b([C({type:Je})],$h.prototype,"acIssuer",void 0);b([C({type:U.Integer})],$h.prototype,"acSerial",void 0);b([C({type:Br,repeated:"sequence"})],$h.prototype,"attrs",void 0)});var W_,Vh,G_=z(()=>{"use strict";g();fe();le();Vh=W_=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,W_.prototype)}};Vh=W_=b([re({type:Z.Sequence,itemType:U.ObjectIdentifier})],Vh)});var zl,V4=z(()=>{"use strict";g();fe();le();G_();zl=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,optional:!0})],zl.prototype,"pathLenConstraint",void 0);b([C({type:Vh,implicit:!0,context:0,optional:!0})],zl.prototype,"permittedAttrs",void 0);b([C({type:Vh,implicit:!0,context:1,optional:!0})],zl.prototype,"excludedAttrs",void 0);b([C({type:U.Boolean,defaultValue:!0})],zl.prototype,"permitUnSpecified",void 0)});var Qs,qh=z(()=>{"use strict";g();fe();le();Ct();Qs=class{issuer=new Gt;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:Gt})],Qs.prototype,"issuer",void 0);b([C({type:U.Integer,converter:St})],Qs.prototype,"serial",void 0);b([C({type:U.BitString,optional:!0})],Qs.prototype,"issuerUID",void 0)});var X_,Zs,zh=z(()=>{"use strict";g();fe();le();Ct();(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(X_||(X_={}));Zs=class{digestedObjectType=X_.publicKey;otherObjectTypeID;digestAlgorithm=new be;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.Enumerated})],Zs.prototype,"digestedObjectType",void 0);b([C({type:U.ObjectIdentifier,optional:!0})],Zs.prototype,"otherObjectTypeID",void 0);b([C({type:be})],Zs.prototype,"digestAlgorithm",void 0);b([C({type:U.BitString})],Zs.prototype,"objectDigest",void 0)});var Jc,Y_=z(()=>{"use strict";g();fe();le();Ct();qh();zh();Jc=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};b([C({type:Gt,optional:!0})],Jc.prototype,"issuerName",void 0);b([C({type:Qs,context:0,implicit:!0,optional:!0})],Jc.prototype,"baseCertificateID",void 0);b([C({type:Zs,context:1,implicit:!0,optional:!0})],Jc.prototype,"objectDigestInfo",void 0)});var Qc,J_=z(()=>{"use strict";g();fe();le();Ct();Y_();Qc=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};b([C({type:Je,repeated:"sequence"})],Qc.prototype,"v1Form",void 0);b([C({type:Jc,context:0,implicit:!0})],Qc.prototype,"v2Form",void 0);Qc=b([re({type:Z.Choice})],Qc)});var Zc,Q_=z(()=>{"use strict";g();fe();le();Zc=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};b([C({type:U.GeneralizedTime})],Zc.prototype,"notBeforeTime",void 0);b([C({type:U.GeneralizedTime})],Zc.prototype,"notAfterTime",void 0)});var la,Z_=z(()=>{"use strict";g();fe();le();Ct();qh();zh();la=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};b([C({type:Qs,implicit:!0,context:0,optional:!0})],la.prototype,"baseCertificateID",void 0);b([C({type:Gt,implicit:!0,context:1,optional:!0})],la.prototype,"entityName",void 0);b([C({type:Zs,implicit:!0,context:2,optional:!0})],la.prototype,"objectDigestInfo",void 0)});var eS,ms,tS=z(()=>{"use strict";g();fe();le();Ct();Z_();J_();Q_();(function(t){t[t.v2=1]="v2"})(eS||(eS={}));ms=class{version=eS.v2;holder=new la;issuer=new Qc;signature=new be;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Zc;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],ms.prototype,"version",void 0);b([C({type:la})],ms.prototype,"holder",void 0);b([C({type:Qc})],ms.prototype,"issuer",void 0);b([C({type:be})],ms.prototype,"signature",void 0);b([C({type:U.Integer,converter:St})],ms.prototype,"serialNumber",void 0);b([C({type:Zc})],ms.prototype,"attrCertValidityPeriod",void 0);b([C({type:Br,repeated:"sequence"})],ms.prototype,"attributes",void 0);b([C({type:U.BitString,optional:!0})],ms.prototype,"issuerUniqueID",void 0);b([C({type:Ps,optional:!0})],ms.prototype,"extensions",void 0)});var ed,q4=z(()=>{"use strict";g();fe();le();Ct();tS();ed=class{acinfo=new ms;signatureAlgorithm=new be;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:ms})],ed.prototype,"acinfo",void 0);b([C({type:be})],ed.prototype,"signatureAlgorithm",void 0);b([C({type:U.BitString})],ed.prototype,"signatureValue",void 0)});var Kh,Kl,rS=z(()=>{"use strict";g();le();(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(Kh||(Kh={}));Kl=class extends Zn{}});var Wl,sS=z(()=>{"use strict";g();fe();le();Wl=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier,implicit:!0,context:0})],Wl.prototype,"type",void 0);b([C({type:U.Any,implicit:!0,context:1})],Wl.prototype,"value",void 0)});var Wh,z4=z(()=>{"use strict";g();fe();le();rS();sS();Wh=class{policyId="";classList=new Kl(Kh.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Wh.prototype,"policyId",void 0);b([C({type:Kl,defaultValue:new Kl(Kh.unclassified)})],Wh.prototype,"classList",void 0);b([C({type:Wl,repeated:"set"})],Wh.prototype,"securityCategories",void 0)});var Gl,jy,K4=z(()=>{"use strict";g();fe();le();Ct();Gl=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};b([C({type:We})],Gl.prototype,"cotets",void 0);b([C({type:U.ObjectIdentifier})],Gl.prototype,"oid",void 0);b([C({type:U.Utf8String})],Gl.prototype,"string",void 0);jy=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};b([C({type:Gt,implicit:!0,context:0,optional:!0})],jy.prototype,"policyAuthority",void 0);b([C({type:Gl,repeated:"sequence"})],jy.prototype,"values",void 0)});var k0e,I0e,R0e,P0e,Gh,B0e,D0e,N0e,O0e,L0e,nS,U0e,W4=z(()=>{"use strict";g();Ct();k0e=`${ca}.4`,I0e=`${ca}.6`,R0e=`${ca}.10`,P0e=`${ot}.55`,Gh=`${aa}.10`,B0e=`${Gh}.1`,D0e=`${Gh}.2`,N0e=`${Gh}.3`,O0e=`${Gh}.4`,L0e=`${Gh}.6`,nS="2.5.4",U0e=`${nS}.72`});var iS,Xl,Yl,Fy,oS=z(()=>{"use strict";g();fe();le();Ct();qh();zh();Xl=class{targetCertificate=new Qs;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};b([C({type:Qs})],Xl.prototype,"targetCertificate",void 0);b([C({type:Je,optional:!0})],Xl.prototype,"targetName",void 0);b([C({type:Zs,optional:!0})],Xl.prototype,"certDigestInfo",void 0);Yl=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};b([C({type:Je,context:0,implicit:!0})],Yl.prototype,"targetName",void 0);b([C({type:Je,context:1,implicit:!0})],Yl.prototype,"targetGroup",void 0);b([C({type:Xl,context:2,implicit:!0})],Yl.prototype,"targetCert",void 0);Yl=b([re({type:Z.Choice})],Yl);Fy=iS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,iS.prototype)}};Fy=iS=b([re({type:Z.Sequence,itemType:Yl})],Fy)});var aS,G4,X4=z(()=>{"use strict";g();fe();le();oS();G4=aS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,aS.prototype)}};G4=aS=b([re({type:Z.Sequence,itemType:Fy})],G4)});var Hy,Y4=z(()=>{"use strict";g();fe();le();Ct();Hy=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};b([C({type:Gt,implicit:!0,context:0,optional:!0})],Hy.prototype,"roleAuthority",void 0);b([C({type:Je,implicit:!0,context:1})],Hy.prototype,"roleName",void 0)});var Xh,J4=z(()=>{"use strict";g();fe();le();Ct();Xh=class{service=new Je;ident=new Je;authInfo;constructor(e={}){Object.assign(this,e)}};b([C({type:Je})],Xh.prototype,"service",void 0);b([C({type:Je})],Xh.prototype,"ident",void 0);b([C({type:We,optional:!0})],Xh.prototype,"authInfo",void 0)});var cS=z(()=>{"use strict";g();$4();V4();J_();Q_();G_();q4();tS();rS();z4();Z_();K4();qh();zh();W4();X4();Y4();sS();J4();oS();Y_()});var dS,Yh,td,rd,$y=z(()=>{"use strict";g();fe();le();Ct();cS();Yh=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],Yh.prototype,"otherCertFormat",void 0);b([C({type:U.Any})],Yh.prototype,"otherCert",void 0);td=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};b([C({type:Js})],td.prototype,"certificate",void 0);b([C({type:ed,context:2,implicit:!0})],td.prototype,"v2AttrCert",void 0);b([C({type:Yh,context:3,implicit:!0})],td.prototype,"other",void 0);td=b([re({type:Z.Choice})],td);rd=dS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,dS.prototype)}};rd=dS=b([re({type:Z.Set,itemType:td})],rd)});var en,Q4=z(()=>{"use strict";g();fe();le();en=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],en.prototype,"contentType",void 0);b([C({type:U.Any,context:0})],en.prototype,"content",void 0)});var Jl,sd,lS=z(()=>{"use strict";g();fe();le();Jl=class{single;any;constructor(e={}){Object.assign(this,e)}};b([C({type:We})],Jl.prototype,"single",void 0);b([C({type:U.Any})],Jl.prototype,"any",void 0);Jl=b([re({type:Z.Choice})],Jl);sd=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],sd.prototype,"eContentType",void 0);b([C({type:Jl,context:0,optional:!0})],sd.prototype,"eContent",void 0)});var Jh,ua,uS=z(()=>{"use strict";g();fe();le();si();Jh=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};b([C({type:We,context:0,implicit:!0,optional:!0})],Jh.prototype,"value",void 0);b([C({type:We,converter:R8,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Jh.prototype,"constructedValue",void 0);Jh=b([re({type:Z.Choice})],Jh);ua=class{contentType="";contentEncryptionAlgorithm=new Fh;encryptedContent;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],ua.prototype,"contentType",void 0);b([C({type:Fh})],ua.prototype,"contentEncryptionAlgorithm",void 0);b([C({type:Jh,optional:!0})],ua.prototype,"encryptedContent",void 0)});var fa,fS=z(()=>{"use strict";g();fe();le();fa=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],fa.prototype,"keyAttrId",void 0);b([C({type:U.Any,optional:!0})],fa.prototype,"keyAttr",void 0)});var hS,Ql,Zl,Qh,Vy,Zh,nd,Qi,pS=z(()=>{"use strict";g();fe();le();Ct();si();Mh();fS();Ql=class{subjectKeyIdentifier=new fs;date;other;constructor(e={}){Object.assign(this,e)}};b([C({type:fs})],Ql.prototype,"subjectKeyIdentifier",void 0);b([C({type:U.GeneralizedTime,optional:!0})],Ql.prototype,"date",void 0);b([C({type:fa,optional:!0})],Ql.prototype,"other",void 0);Zl=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};b([C({type:Ql,context:0,implicit:!0,optional:!0})],Zl.prototype,"rKeyId",void 0);b([C({type:wn,optional:!0})],Zl.prototype,"issuerAndSerialNumber",void 0);Zl=b([re({type:Z.Choice})],Zl);Qh=class{rid=new Zl;encryptedKey=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:Zl})],Qh.prototype,"rid",void 0);b([C({type:We})],Qh.prototype,"encryptedKey",void 0);Vy=hS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,hS.prototype)}};Vy=hS=b([re({type:Z.Sequence,itemType:Qh})],Vy);Zh=class{algorithm=new be;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:be})],Zh.prototype,"algorithm",void 0);b([C({type:U.BitString})],Zh.prototype,"publicKey",void 0);nd=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};b([C({type:fs,context:0,implicit:!0,optional:!0})],nd.prototype,"subjectKeyIdentifier",void 0);b([C({type:Zh,context:1,implicit:!0,optional:!0})],nd.prototype,"originatorKey",void 0);b([C({type:wn,optional:!0})],nd.prototype,"issuerAndSerialNumber",void 0);nd=b([re({type:Z.Choice})],nd);Qi=class{version=Or.v3;originator=new nd;ukm;keyEncryptionAlgorithm=new hs;recipientEncryptedKeys=new Vy;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],Qi.prototype,"version",void 0);b([C({type:nd,context:0})],Qi.prototype,"originator",void 0);b([C({type:We,context:1,optional:!0})],Qi.prototype,"ukm",void 0);b([C({type:hs})],Qi.prototype,"keyEncryptionAlgorithm",void 0);b([C({type:Vy})],Qi.prototype,"recipientEncryptedKeys",void 0)});var eu,ha,mS=z(()=>{"use strict";g();fe();le();Ct();si();Mh();eu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};b([C({type:fs,context:0,implicit:!0})],eu.prototype,"subjectKeyIdentifier",void 0);b([C({type:wn})],eu.prototype,"issuerAndSerialNumber",void 0);eu=b([re({type:Z.Choice})],eu);ha=class{version=Or.v0;rid=new eu;keyEncryptionAlgorithm=new hs;encryptedKey=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],ha.prototype,"version",void 0);b([C({type:eu})],ha.prototype,"rid",void 0);b([C({type:hs})],ha.prototype,"keyEncryptionAlgorithm",void 0);b([C({type:We})],ha.prototype,"encryptedKey",void 0)});var id,pa,gS=z(()=>{"use strict";g();fe();le();fS();si();id=class{keyIdentifier=new We;date;other;constructor(e={}){Object.assign(this,e)}};b([C({type:We})],id.prototype,"keyIdentifier",void 0);b([C({type:U.GeneralizedTime,optional:!0})],id.prototype,"date",void 0);b([C({type:fa,optional:!0})],id.prototype,"other",void 0);pa=class{version=Or.v4;kekid=new id;keyEncryptionAlgorithm=new hs;encryptedKey=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],pa.prototype,"version",void 0);b([C({type:id})],pa.prototype,"kekid",void 0);b([C({type:hs})],pa.prototype,"keyEncryptionAlgorithm",void 0);b([C({type:We})],pa.prototype,"encryptedKey",void 0)});var ma,yS=z(()=>{"use strict";g();fe();le();si();ma=class{version=Or.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new hs;encryptedKey=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],ma.prototype,"version",void 0);b([C({type:Ly,context:0,optional:!0})],ma.prototype,"keyDerivationAlgorithm",void 0);b([C({type:hs})],ma.prototype,"keyEncryptionAlgorithm",void 0);b([C({type:We})],ma.prototype,"encryptedKey",void 0)});var ep,Zi,xS=z(()=>{"use strict";g();fe();le();pS();mS();gS();yS();ep=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],ep.prototype,"oriType",void 0);b([C({type:U.Any})],ep.prototype,"oriValue",void 0);Zi=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};b([C({type:ha,optional:!0})],Zi.prototype,"ktri",void 0);b([C({type:Qi,context:1,implicit:!0,optional:!0})],Zi.prototype,"kari",void 0);b([C({type:pa,context:2,implicit:!0,optional:!0})],Zi.prototype,"kekri",void 0);b([C({type:ma,context:3,implicit:!0,optional:!0})],Zi.prototype,"pwri",void 0);b([C({type:ep,context:4,implicit:!0,optional:!0})],Zi.prototype,"ori",void 0);Zi=b([re({type:Z.Choice})],Zi)});var bS,tp,wS=z(()=>{"use strict";g();fe();le();xS();tp=bS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,bS.prototype)}};tp=bS=b([re({type:Z.Set,itemType:Zi})],tp)});var vS,Z4,Zge,eye,tu,qy,ru,zy=z(()=>{"use strict";g();fe();le();Ct();Z4=`${aa}.16`,Zge=`${Z4}.2`,eye=`${Z4}.4`,tu=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],tu.prototype,"otherRevInfoFormat",void 0);b([C({type:U.Any})],tu.prototype,"otherRevInfo",void 0);qy=class{other=new tu;constructor(e={}){Object.assign(this,e)}};b([C({type:tu,context:1,implicit:!0})],qy.prototype,"other",void 0);qy=b([re({type:Z.Choice})],qy);ru=vS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,vS.prototype)}};ru=vS=b([re({type:Z.Set,itemType:qy})],ru)});var su,_S=z(()=>{"use strict";g();fe();le();$y();zy();su=class{certs;crls;constructor(e={}){Object.assign(this,e)}};b([C({type:rd,context:0,implicit:!0,optional:!0})],su.prototype,"certs",void 0);b([C({type:ru,context:1,implicit:!0,optional:!0})],su.prototype,"crls",void 0)});var SS,ES,od,eR=z(()=>{"use strict";g();fe();le();si();Uy();wS();_S();uS();ES=SS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,SS.prototype)}};ES=SS=b([re({type:Z.Set,itemType:vn})],ES);od=class{version=Or.v0;originatorInfo;recipientInfos=new tp;encryptedContentInfo=new ua;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],od.prototype,"version",void 0);b([C({type:su,context:0,implicit:!0,optional:!0})],od.prototype,"originatorInfo",void 0);b([C({type:tp})],od.prototype,"recipientInfos",void 0);b([C({type:ua})],od.prototype,"encryptedContentInfo",void 0);b([C({type:ES,context:1,implicit:!0,optional:!0})],od.prototype,"unprotectedAttrs",void 0)});var tR,rR=z(()=>{"use strict";g();tR="1.2.840.113549.1.7.2"});var CS,Ky,eo,sR=z(()=>{"use strict";g();fe();le();$y();si();lS();zy();My();Ky=CS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,CS.prototype)}};Ky=CS=b([re({type:Z.Set,itemType:Yc})],Ky);eo=class{version=Or.v0;digestAlgorithms=new Ky;encapContentInfo=new sd;certificates;crls;signerInfos=new Hh;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],eo.prototype,"version",void 0);b([C({type:Ky})],eo.prototype,"digestAlgorithms",void 0);b([C({type:sd})],eo.prototype,"encapContentInfo",void 0);b([C({type:rd,context:0,implicit:!0,optional:!0})],eo.prototype,"certificates",void 0);b([C({type:ru,context:1,implicit:!0,optional:!0})],eo.prototype,"crls",void 0);b([C({type:Hh})],eo.prototype,"signerInfos",void 0)});var rp=z(()=>{"use strict";g();H4();Uy();$y();Q4();lS();uS();eR();Mh();gS();pS();mS();rR();_S();yS();xS();wS();zy();sR();z_();My();si()});var ad,sp,Wy,np,ip,op,TS,AS,kS,IS=z(()=>{"use strict";g();ad="1.2.840.10045.2.1",sp="1.2.840.10045.4.1",Wy="1.2.840.10045.4.3.1",np="1.2.840.10045.4.3.2",ip="1.2.840.10045.4.3.3",op="1.2.840.10045.4.3.4",TS="1.2.840.10045.3.1.7",AS="1.3.132.0.34",kS="1.3.132.0.35"});function ap(t){return new be({algorithm:t})}var iR,sxe,oR,aR,cR,dR=z(()=>{"use strict";g();Ct();IS();iR=ap(sp),sxe=ap(Wy),oR=ap(np),aR=ap(ip),cR=ap(op)});var cp,RS,nu,PS,ni,BS=z(()=>{"use strict";g();fe();le();cp=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],cp.prototype,"fieldType",void 0);b([C({type:U.Any})],cp.prototype,"parameters",void 0);cp=b([re({type:Z.Sequence})],cp);RS=class extends We{},nu=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};b([C({type:U.OctetString})],nu.prototype,"a",void 0);b([C({type:U.OctetString})],nu.prototype,"b",void 0);b([C({type:U.BitString,optional:!0})],nu.prototype,"seed",void 0);nu=b([re({type:Z.Sequence})],nu);(function(t){t[t.ecpVer1=1]="ecpVer1"})(PS||(PS={}));ni=class{version=PS.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],ni.prototype,"version",void 0);b([C({type:cp})],ni.prototype,"fieldID",void 0);b([C({type:nu})],ni.prototype,"curve",void 0);b([C({type:RS})],ni.prototype,"base",void 0);b([C({type:U.Integer,converter:St})],ni.prototype,"order",void 0);b([C({type:U.Integer,optional:!0})],ni.prototype,"cofactor",void 0);ni=b([re({type:Z.Sequence})],ni)});var ii,DS=z(()=>{"use strict";g();fe();le();BS();ii=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],ii.prototype,"namedCurve",void 0);b([C({type:U.Null})],ii.prototype,"implicitCurve",void 0);b([C({type:ni})],ii.prototype,"specifiedCurve",void 0);ii=b([re({type:Z.Choice})],ii)});var iu,lR=z(()=>{"use strict";g();fe();le();DS();iu=class{version=1;privateKey=new We;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],iu.prototype,"version",void 0);b([C({type:We})],iu.prototype,"privateKey",void 0);b([C({type:ii,context:0,optional:!0})],iu.prototype,"parameters",void 0);b([C({type:U.BitString,context:1,optional:!0})],iu.prototype,"publicKey",void 0)});var cd,uR=z(()=>{"use strict";g();fe();le();cd=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,converter:St})],cd.prototype,"r",void 0);b([C({type:U.Integer,converter:St})],cd.prototype,"s",void 0)});var NS=z(()=>{"use strict";g();dR();DS();lR();uR();IS();BS()});var gs,oi,fR,hR,ga,pR,mR,ou,gR,Gy,au,cu,OS,LS,dd,Xy,ld,ud,fd,yR,xR,bR,wR,ya,dp=z(()=>{"use strict";g();gs="1.2.840.113549.1.1",oi=`${gs}.1`,fR=`${gs}.7`,hR=`${gs}.9`,ga=`${gs}.10`,pR=`${gs}.2`,mR=`${gs}.4`,ou=`${gs}.5`,gR=`${gs}.14`,Gy=`${gs}.11`,au=`${gs}.12`,cu=`${gs}.13`,OS=`${gs}.15`,LS=`${gs}.16`,dd="1.3.14.3.2.26",Xy="2.16.840.1.101.3.4.2.4",ld="2.16.840.1.101.3.4.2.1",ud="2.16.840.1.101.3.4.2.2",fd="2.16.840.1.101.3.4.2.3",yR="2.16.840.1.101.3.4.2.5",xR="2.16.840.1.101.3.4.2.6",bR="1.2.840.113549.2.2",wR="1.2.840.113549.2.5",ya=`${gs}.8`});function Er(t){return new be({algorithm:t,parameters:null})}var Mxe,jxe,to,Fxe,Hxe,$xe,Vxe,qxe,zxe,Yy,US,Kxe,Wxe,Gxe,Xxe,Yxe,Jxe,Qxe,Zxe,ebe,tbe,Jy=z(()=>{"use strict";g();le();Ct();dp();Mxe=Er(bR),jxe=Er(wR),to=Er(dd),Fxe=Er(Xy),Hxe=Er(ld),$xe=Er(ud),Vxe=Er(fd),qxe=Er(yR),zxe=Er(xR),Yy=new be({algorithm:ya,parameters:_e.serialize(to)}),US=new be({algorithm:hR,parameters:_e.serialize(jl.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),Kxe=Er(oi),Wxe=Er(pR),Gxe=Er(mR),Xxe=Er(ou),Yxe=Er(OS),Jxe=Er(LS),Qxe=Er(au),Zxe=Er(cu),ebe=Er(OS),tbe=Er(LS)});var du,dbe,vR=z(()=>{"use strict";g();fe();le();Ct();dp();Jy();du=class{hashAlgorithm=new be(to);maskGenAlgorithm=new be({algorithm:ya,parameters:_e.serialize(to)});pSourceAlgorithm=new be(US);constructor(e={}){Object.assign(this,e)}};b([C({type:be,context:0,defaultValue:to})],du.prototype,"hashAlgorithm",void 0);b([C({type:be,context:1,defaultValue:Yy})],du.prototype,"maskGenAlgorithm",void 0);b([C({type:be,context:2,defaultValue:US})],du.prototype,"pSourceAlgorithm",void 0);dbe=new be({algorithm:fR,parameters:_e.serialize(new du)})});var ai,ybe,_R=z(()=>{"use strict";g();fe();le();Ct();dp();Jy();ai=class{hashAlgorithm=new be(to);maskGenAlgorithm=new be({algorithm:ya,parameters:_e.serialize(to)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};b([C({type:be,context:0,defaultValue:to})],ai.prototype,"hashAlgorithm",void 0);b([C({type:be,context:1,defaultValue:Yy})],ai.prototype,"maskGenAlgorithm",void 0);b([C({type:U.Integer,context:2,defaultValue:20})],ai.prototype,"saltLength",void 0);b([C({type:U.Integer,context:3,defaultValue:1})],ai.prototype,"trailerField",void 0);ybe=new be({algorithm:ga,parameters:_e.serialize(new ai)})});var hd,SR=z(()=>{"use strict";g();fe();Ct();le();hd=class{digestAlgorithm=new be;digest=new We;constructor(e={}){Object.assign(this,e)}};b([C({type:be})],hd.prototype,"digestAlgorithm",void 0);b([C({type:We})],hd.prototype,"digest",void 0)});var ER=z(()=>{"use strict";g();vR();_R();SR()});var MS,lu,Qy,jS=z(()=>{"use strict";g();fe();le();lu=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,converter:St})],lu.prototype,"prime",void 0);b([C({type:U.Integer,converter:St})],lu.prototype,"exponent",void 0);b([C({type:U.Integer,converter:St})],lu.prototype,"coefficient",void 0);Qy=MS=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,MS.prototype)}};Qy=MS=b([re({type:Z.Sequence,itemType:lu})],Qy)});var tn,CR=z(()=>{"use strict";g();fe();le();jS();tn=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)}};b([C({type:U.Integer})],tn.prototype,"version",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"modulus",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"publicExponent",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"privateExponent",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"prime1",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"prime2",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"exponent1",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"exponent2",void 0);b([C({type:U.Integer,converter:St})],tn.prototype,"coefficient",void 0);b([C({type:Qy,optional:!0})],tn.prototype,"otherPrimeInfos",void 0)});var uu,TR=z(()=>{"use strict";g();fe();le();uu=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer,converter:St})],uu.prototype,"modulus",void 0);b([C({type:U.Integer,converter:St})],uu.prototype,"publicExponent",void 0)});var Zy=z(()=>{"use strict";g();ER();Jy();dp();jS();CR();TR()});var FS,Lr,HS=z(()=>{"use strict";g();(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(FS||(FS={}));Lr=FS});var AR=z(()=>{"use strict";g();HS()});function lp(t,e){$S(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function kR(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{d(s.next(u))}catch(l){o(l)}}function c(u){try{d(s.throw(u))}catch(l){o(l)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((s=s.apply(t,e||[])).next())})}function IR(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(d){return function(u){return c([d,u])}}function c(d){if(s)throw new TypeError("Generator is already executing.");for(;r;)try{if(s=1,n&&(i=d[0]&2?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[d[0]&2,i.value]),d[0]){case 0:case 1:i=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,n=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){r.label=d[1];break}if(d[0]===6&&r.label<i[1]){r.label=i[1],i=d;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(d);break}i[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(u){d=[6,u],n=0}finally{s=i=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function up(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function fu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function ci(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(fu(arguments[e]));return t}var $S,hu=z(()=>{"use strict";g();$S=function(t,e){return $S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)s.hasOwnProperty(n)&&(r[n]=s[n])},$S(t,e)}});function VS(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(fK,t)||{};return Object.keys(r).forEach(function(s){e[+s]=r[s]}),e}var fK,pd=z(()=>{"use strict";g();fK="injectionTokens"});function fp(t){return!!t.useClass}var qS=z(()=>{"use strict";g()});function pu(t){return!!t.useFactory}var zS=z(()=>{"use strict";g()});var ex,tx=z(()=>{"use strict";g();hu();ex=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,s={},n=!1,i,o=function(){return n||(i=e(r.wrap()),n=!0),i};return new Proxy(s,this.createHandler(o))},t.prototype.createHandler=function(e){var r={},s=function(n){r[n]=function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];i[0]=e();var a=Reflect[n];return a.apply(void 0,ci(i))}};return this.reflectMethods.forEach(s),r},t})()});function xa(t){return typeof t=="string"||typeof t=="symbol"}function KS(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function rx(t){return typeof t=="object"&&"token"in t&&"transform"in t}function RR(t){return typeof t=="function"||t instanceof ex}var sx=z(()=>{"use strict";g();tx()});function md(t){return!!t.useToken}var WS=z(()=>{"use strict";g()});function gd(t){return t.useValue!=null}var GS=z(()=>{"use strict";g()});var XS=z(()=>{"use strict";g();qS();zS();sx();WS();GS()});function PR(t){return fp(t)||gd(t)||md(t)||pu(t)}var BR=z(()=>{"use strict";g();qS();GS();WS();zS()});var hK,hp,YS=z(()=>{"use strict";g();hK=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),hp=hK});var pK,DR,NR=z(()=>{"use strict";g();hu();YS();pK=(function(t){lp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(hp),DR=pK});var mK,pp,OR=z(()=>{"use strict";g();mK=(function(){function t(){this.scopedResolutions=new Map}return t})(),pp=mK});function gK(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function yK(t,e,r){return r===void 0&&(r=" "),ci([t],e.message.split(`
28
+ `).map(function(s){return r+s})).join(`
29
+ `)}function JS(t,e,r){var s=fu(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=gK(i,e);return yK("Cannot inject the dependency "+o+' of "'+t.name+'" constructor. Reason:',r)}var QS=z(()=>{"use strict";g();hu()});function LR(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var UR=z(()=>{"use strict";g()});var xK,bK,wK,MR,jR=z(()=>{"use strict";g();hu();YS();xK=(function(t){lp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(hp),bK=(function(t){lp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(hp),wK=(function(){function t(){this.preResolution=new xK,this.postResolution=new bK}return t})(),MR=wK});var ZS,vK,zt,ba=z(()=>{"use strict";g();hu();XS();BR();sx();NR();HS();OR();QS();tx();UR();jR();ZS=new Map,vK=(function(){function t(e){this.parent=e,this._registry=new DR,this.interceptors=new MR,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,s){s===void 0&&(s={lifecycle:Lr.Transient}),this.ensureNotDisposed();var n;if(PR(r)?n=r:n={useClass:r},md(n))for(var i=[e],o=n;o!=null;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+ci(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&md(c.provider)?o=c.provider:o=null}if((s.lifecycle===Lr.Singleton||s.lifecycle==Lr.ContainerScoped||s.lifecycle==Lr.ResolutionScoped)&&(gd(n)||pu(n)))throw new Error('Cannot use lifecycle "'+Lr[s.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:s}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),xa(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),xa(e)){if(xa(r))return this.register(e,{useToken:r},{lifecycle:Lr.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:Lr.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var s=e;return r&&!xa(r)&&(s=r),this.register(e,{useClass:s},{lifecycle:Lr.Singleton})},t.prototype.resolve=function(e,r,s){r===void 0&&(r=new pp),s===void 0&&(s=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&xa(e)){if(s)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(RR(e)){var i=this.construct(e,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var s,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=up(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;c.options.frequency!="Once"&&i.push(c),c.callback(e,r)}}catch(d){s={error:d}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}this.interceptors.preResolution.setAll(e,i)}},t.prototype.executePostResolutionInterceptor=function(e,r,s){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=up(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var d=c.value;d.options.frequency!="Once"&&o.push(d),d.callback(e,r,s)}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===Lr.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var s=e.options.lifecycle===Lr.Singleton,n=e.options.lifecycle===Lr.ContainerScoped,i=s||n,o;return gd(e.provider)?o=e.provider.useValue:md(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):fp(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):pu(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,r),e.options.lifecycle===Lr.ResolutionScoped&&r.scopedResolutions.set(e,o),o},t.prototype.resolveAll=function(e,r,s){var n=this;r===void 0&&(r=new pp),s===void 0&&(s=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&xa(e)){if(s)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map(function(c){return n.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var s=up(this._registry.entries()),n=s.next();!n.done;n=s.next()){var i=fu(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter(function(c){return!gd(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var s=new t(this);try{for(var n=up(this._registry.entries()),i=n.next();!i.done;i=n.next()){var o=fu(i.value,2),a=o[0],c=o[1];c.some(function(d){var u=d.options;return u.lifecycle===Lr.ContainerScoped})&&s._registry.setAll(a,c.map(function(d){return d.options.lifecycle===Lr.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}return s},t.prototype.beforeResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:s})},t.prototype.afterResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:s})},t.prototype.dispose=function(){return kR(this,void 0,void 0,function(){var e;return IR(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(s){var n=s.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var s=this;if(e instanceof ex)return e.createProxy(function(i){return s.resolve(i,r)});var n=(function(){var i=ZS.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var o=i.map(s.resolveParams(r,e));return new(e.bind.apply(e,ci([void 0],o)))})();return LR(n)&&this.disposables.add(n),n},t.prototype.resolveParams=function(e,r){var s=this;return function(n,i){var o,a,c;try{return KS(n)?rx(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,ci([s.resolveAll(n.token,new pp,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,ci([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new pp,n.isOptional):s.resolve(n.token,e,n.isOptional):rx(n)?(c=s.resolve(n.transform,e)).transform.apply(c,ci([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(JS(r,i,d))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),zt=new vK});var FR=z(()=>{"use strict";g();pd();ba();sx();QS()});var HR=z(()=>{"use strict";g();pd()});function _K(t){return function(e){ZS.set(e,VS(e)),t&&t.token&&(Array.isArray(t.token)?t.token.forEach(function(r){zt.register(r,e)}):zt.register(t.token,e))}}var wa,nx=z(()=>{"use strict";g();pd();ba();ba();wa=_K});var $R=z(()=>{"use strict";g();ba()});var VR=z(()=>{"use strict";g();nx();ba()});var qR=z(()=>{"use strict";g();pd()});var zR=z(()=>{"use strict";g();pd()});var KR=z(()=>{"use strict";g();pd()});var WR=z(()=>{"use strict";g();nx();ba()});var GR=z(()=>{"use strict";g();FR();HR();nx();$R();VR();qR();zR();KR();WR()});var XR=z(()=>{"use strict";g()});var YR=z(()=>{"use strict";g()});var JR=z(()=>{"use strict";g()});var QR=z(()=>{"use strict";g();XR();YR();JR()});var ZR=z(()=>{"use strict";g();AR();GR();QR();XS();tx();ba();if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`)});var t2,yd,e5,r2=z(()=>{"use strict";g();fe();le();yd=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};b([C({type:U.ObjectIdentifier})],yd.prototype,"attrId",void 0);b([C({type:U.Any,repeated:"set"})],yd.prototype,"attrValues",void 0);e5=t2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,t2.prototype)}};e5=t2=b([re({type:Z.Sequence,itemType:yd})],e5)});var s2,t5,r5=z(()=>{"use strict";g();fe();le();rp();t5=s2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,s2.prototype)}};t5=s2=b([re({type:Z.Sequence,itemType:en})],t5)});var SK,EK,s5,mu,Vve,qve,zve,Kve,Wve,Gve,xd,n2=z(()=>{"use strict";g();SK="1.2.840.113549",EK=`${SK}.1`,s5=`${EK}.12`,mu=`${s5}.1`,Vve=`${mu}.1`,qve=`${mu}.2`,zve=`${mu}.3`,Kve=`${mu}.4`,Wve=`${mu}.5`,Gve=`${mu}.6`,xd=`${s5}.10.1`});var Qve,Zve,e_e,t_e,r_e,s_e,ix,ox=z(()=>{"use strict";g();n2();Qve=`${xd}.1`,Zve=`${xd}.2`,e_e=`${xd}.3`,t_e=`${xd}.4`,r_e=`${xd}.5`,s_e=`${xd}.6`,ix="1.2.840.113549.1.9"});var ax,n5,d_e,l_e,i5=z(()=>{"use strict";g();fe();le();ox();ax=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],ax.prototype,"certId",void 0);b([C({type:U.Any,context:0})],ax.prototype,"certValue",void 0);n5=`${ix}.22`,d_e=`${n5}.1`,l_e=`${n5}.2`});var cx,CK,g_e,o5=z(()=>{"use strict";g();fe();le();ox();cx=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],cx.prototype,"crlId",void 0);b([C({type:U.Any,context:0})],cx.prototype,"crltValue",void 0);CK=`${ix}.23`,g_e=`${CK}.1`});var dx,va,a5=z(()=>{"use strict";g();fe();le();Ct();dx=class extends We{},va=class{encryptionAlgorithm=new be;encryptedData=new dx;constructor(e={}){Object.assign(this,e)}};b([C({type:be})],va.prototype,"encryptionAlgorithm",void 0);b([C({type:dx})],va.prototype,"encryptedData",void 0)});var i2,o2,lx,a2,_a,c5=z(()=>{"use strict";g();fe();le();Ct();(function(t){t[t.v1=0]="v1"})(o2||(o2={}));lx=class extends We{},a2=i2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,i2.prototype)}};a2=i2=b([re({type:Z.Sequence,itemType:Br})],a2);_a=class{version=o2.v1;privateKeyAlgorithm=new be;privateKey=new lx;attributes;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],_a.prototype,"version",void 0);b([C({type:be})],_a.prototype,"privateKeyAlgorithm",void 0);b([C({type:lx})],_a.prototype,"privateKey",void 0);b([C({type:a2,implicit:!0,context:0,optional:!0})],_a.prototype,"attributes",void 0)});var ux=z(()=>{"use strict";g();a5();c5()});var d5,l5=z(()=>{"use strict";g();fe();ux();le();d5=class extends _a{};d5=b([re({type:Z.Sequence})],d5)});var u5,f5=z(()=>{"use strict";g();fe();ux();le();u5=class extends va{};u5=b([re({type:Z.Sequence})],u5)});var fx,h5=z(()=>{"use strict";g();fe();le();fx=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],fx.prototype,"secretTypeId",void 0);b([C({type:U.Any,context:0})],fx.prototype,"secretValue",void 0)});var p5=z(()=>{"use strict";g();i5();o5();l5();f5();h5();ox()});var Sa,c2=z(()=>{"use strict";g();fe();Zy();le();Sa=class{mac=new hd;macSalt=new We;iterations=1;constructor(e={}){Object.assign(this,e)}};b([C({type:hd})],Sa.prototype,"mac",void 0);b([C({type:We})],Sa.prototype,"macSalt",void 0);b([C({type:U.Integer,defaultValue:1})],Sa.prototype,"iterations",void 0)});var bd,m5=z(()=>{"use strict";g();fe();le();rp();c2();bd=class{version=3;authSafe=new en;macData=new Sa;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],bd.prototype,"version",void 0);b([C({type:en})],bd.prototype,"authSafe",void 0);b([C({type:Sa,optional:!0})],bd.prototype,"macData",void 0)});var d2,gu,g5,y5=z(()=>{"use strict";g();fe();le();r2();gu=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};b([C({type:U.ObjectIdentifier})],gu.prototype,"bagId",void 0);b([C({type:U.Any,context:0})],gu.prototype,"bagValue",void 0);b([C({type:yd,repeated:"set",optional:!0})],gu.prototype,"bagAttributes",void 0);g5=d2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,d2.prototype)}};g5=d2=b([re({type:Z.Sequence,itemType:gu})],g5)});var x5=z(()=>{"use strict";g();r2();r5();p5();c2();n2();m5();y5()});var l2,u2,f2,cr,RSe,B5,gp,D5,N5,PSe,BSe,DSe,NSe,OSe,LSe,USe,MSe,w2,jSe,FSe,HSe,yp,$Se,VSe,qSe,zSe,KSe,WSe,GSe,XSe,xp,YSe,JSe,QSe,ZSe,e2e,t2e,r2e,s2e,n2e,i2e,o2e,a2e,c2e,hx,b5,w5,v5,h2,_5,S5,p2,E5,m2,px,C5,T5,g2,A5,y2,k5,mp,I5,R5,x2,b2,P5,v2=z(()=>{"use strict";g();fe();le();rp();x5();ux();Ct();cS();cr="1.2.840.113549.1.9",RSe=`${cr}.0`,B5=`${cr}.24`,gp=`${cr}.25`,D5=`${cr}.26`,N5=`${cr}.27`,PSe=`${B5}.1`,BSe=`${B5}.2`,DSe=`${cr}.1`,NSe=`${cr}.2`,OSe=`${cr}.3`,LSe=`${cr}.4`,USe=`${cr}.5`,MSe=`${cr}.6`,w2=`${cr}.7`,jSe=`${cr}.8`,FSe=`${cr}.9`,HSe=`${cr}.13`,yp=`${cr}.14`,$Se=`${cr}.15`,VSe=`${cr}.20`,qSe=`${cr}.21`,zSe=`${gp}.1`,KSe=`${gp}.2`,WSe=`${gp}.3`,GSe=`${gp}.4`,XSe=`${gp}.5`,xp="1.3.6.1.5.5.7.9",YSe=`${xp}.1`,JSe=`${xp}.2`,QSe=`${xp}.3`,ZSe=`${xp}.4`,e2e=`${xp}.5`,t2e=`${D5}.1`,r2e=`${D5}.2`,s2e=`${N5}.1`,n2e=`${N5}.2`,i2e=`${cr}.16`,o2e=`${cr}.22`,a2e=`${cr}.23`,c2e=`${nS}.65`,hx=class extends hr{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};b([C({type:U.IA5String})],hx.prototype,"ia5String",void 0);hx=b([re({type:Z.Choice})],hx);b5=class extends en{};b5=b([re({type:Z.Sequence})],b5);w5=class extends bd{};w5=b([re({type:Z.Sequence})],w5);v5=class extends va{};v5=b([re({type:Z.Sequence})],v5);h2=class{value;constructor(e=""){this.value=e}toString(){return this.value}};b([C({type:U.IA5String})],h2.prototype,"value",void 0);h2=b([re({type:Z.Choice})],h2);_5=class extends hx{};_5=b([re({type:Z.Choice})],_5);S5=class extends hr{};S5=b([re({type:Z.Choice})],S5);p2=class{value;constructor(e=new Date){this.value=e}};b([C({type:U.GeneralizedTime})],p2.prototype,"value",void 0);p2=b([re({type:Z.Choice})],p2);E5=class extends hr{};E5=b([re({type:Z.Choice})],E5);m2=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};b([C({type:U.PrintableString})],m2.prototype,"value",void 0);m2=b([re({type:Z.Choice})],m2);px=class{value;constructor(e=""){this.value=e}toString(){return this.value}};b([C({type:U.PrintableString})],px.prototype,"value",void 0);px=b([re({type:Z.Choice})],px);C5=class extends px{};C5=b([re({type:Z.Choice})],C5);T5=class extends hr{};T5=b([re({type:Z.Choice})],T5);g2=class{value;constructor(e=""){this.value=e}toString(){return this.value}};b([C({type:U.ObjectIdentifier})],g2.prototype,"value",void 0);g2=b([re({type:Z.Choice})],g2);A5=class extends ar{};A5=b([re({type:Z.Choice})],A5);y2=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};b([C({type:U.Integer})],y2.prototype,"value",void 0);y2=b([re({type:Z.Choice})],y2);k5=class extends ps{};k5=b([re({type:Z.Sequence})],k5);mp=class extends hr{};mp=b([re({type:Z.Choice})],mp);I5=l2=class extends Ps{constructor(e){super(e),Object.setPrototypeOf(this,l2.prototype)}};I5=l2=b([re({type:Z.Sequence})],I5);R5=u2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,u2.prototype)}};R5=u2=b([re({type:Z.Set,itemType:vn})],R5);x2=class{value;constructor(e=""){this.value=e}toString(){return this.value}};b([C({type:U.BmpString})],x2.prototype,"value",void 0);x2=b([re({type:Z.Choice})],x2);b2=class extends be{};b2=b([re({type:Z.Sequence})],b2);P5=f2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,f2.prototype)}};P5=f2=b([re({type:Z.Sequence,itemType:b2})],P5)});var _2,bp,S2=z(()=>{"use strict";g();fe();le();Ct();bp=_2=class extends qe{constructor(e){super(e),Object.setPrototypeOf(this,_2.prototype)}};bp=_2=b([re({type:Z.Sequence,itemType:Br})],bp)});var di,E2=z(()=>{"use strict";g();fe();le();Ct();S2();di=class{version=0;subject=new jt;subjectPKInfo=new Dr;attributes=new bp;constructor(e={}){Object.assign(this,e)}};b([C({type:U.Integer})],di.prototype,"version",void 0);b([C({type:jt})],di.prototype,"subject",void 0);b([C({type:Dr})],di.prototype,"subjectPKInfo",void 0);b([C({type:bp,implicit:!0,context:0,optional:!0})],di.prototype,"attributes",void 0)});var Ea,O5=z(()=>{"use strict";g();fe();le();Ct();E2();Ea=class{certificationRequestInfo=new di;certificationRequestInfoRaw;signatureAlgorithm=new be;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};b([C({type:di,raw:!0})],Ea.prototype,"certificationRequestInfo",void 0);b([C({type:be})],Ea.prototype,"signatureAlgorithm",void 0);b([C({type:U.BitString})],Ea.prototype,"signature",void 0)});var L5=z(()=>{"use strict";g();S2();O5();E2()});function RK(t){return new RegExp(IK).test(t)}function PK(t,e){return`\\${Ve.ToHex(Ve.FromUtf8String(e)).toUpperCase()}`}function BK(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,PK)}function HK(t,e){return t.algorithm=new be({algorithm:oi,parameters:null}),e=_e.serialize(t),e}function gx(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{let s=new kt("");r.forEach((n,i)=>{let o=n.toTextObject(),a=`${o[kt.NAME]} ${i+1}`,c=s[a];Array.isArray(c)||(c=[],s[a]=c),c.push(o)}),t[e]=s}}function yx(t,e,r,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new li("url",o)),t.push(new Gi({accessMethod:r,accessLocation:_e.parse(o.rawData,Je)}))})}function $K(t,e=pr.get()){let r=Ce.toUint8Array(Ve.FromHex(t||"")),s=r&&r.length&&r.some(i=>i>0)?new Uint8Array(r):void 0;s||(s=e.getRandomValues(new Uint8Array(16)));let n=0;for(;n<s.length-1&&s[n]===0;)n++;if(s=s.slice(n),s[0]>127){let i=new Uint8Array(s.length+1);i[0]=0,i.set(s,1),s=i}return s.buffer}var sEe,Vp,N2,wd,xx,xs,U5,M5,j5,F5,H5,$5,V5,q5,z5,K5,W5,G5,X5,Y5,J5,Q5,Z5,eP,tP,rP,sP,nP,iP,oP,aP,cP,dP,lP,rr,jp,vP,_P,kt,O2,ui,so,yu,Ca,Ds,SP,Fp,pr,IK,wx,ys,_n,EP,uP,DK,fP,hP,pP,C2,T2,A2,k2,I2,R2,P2,mx,li,no,Mp,Hp,NK,OK,LK,wu,UK,MK,jK,FK,mP,Ur,Ta,ro,vx,_x,gP,Sx,yP,Ex,Cx,Tx,ss,Ax,kx,Ix,Rx,vu,Px,$p,_u,qp,L2,bx,U2,M2,io,B2,xP,D2,bP,j2,wp,vp,_p,Sp,Ep,Cp,Tp,xu,F2,Ap,kp,Ip,Rp,Pp,Bp,Dp,Np,Op,Lp,bu,Up,Bx,Dx,VK,qK,zK,KK,WK,wP,GK,XK,YK,JK,QK,ZK,eW,CP=z(()=>{"use strict";g();sEe=Fe(Y1());le();Ct();Ct();$v();fe();rp();NS();NS();Zy();Zy();ZR();v2();v2();L5();Vp="crypto.algorithm",N2=class{getAlgorithms(){return zt.resolveAll(Vp)}toAsnAlgorithm(e){({...e});for(let r of this.getAlgorithms()){let s=r.toAsnAlgorithm(e);if(s)return s}if(/^[0-9.]+$/.test(e.name)){let r=new be({algorithm:e.name});if("parameters"in e){let s=e;r.parameters=s.parameters}return r}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let s of this.getAlgorithms()){let n=s.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},wd="crypto.algorithmProvider";zt.registerSingleton(wd,N2);xs="1.3.36.3.3.2.8.1.1",U5=`${xs}.1`,M5=`${xs}.2`,j5=`${xs}.3`,F5=`${xs}.4`,H5=`${xs}.5`,$5=`${xs}.6`,V5=`${xs}.7`,q5=`${xs}.8`,z5=`${xs}.9`,K5=`${xs}.10`,W5=`${xs}.11`,G5=`${xs}.12`,X5=`${xs}.13`,Y5=`${xs}.14`,J5="brainpoolP160r1",Q5="brainpoolP160t1",Z5="brainpoolP192r1",eP="brainpoolP192t1",tP="brainpoolP224r1",rP="brainpoolP224t1",sP="brainpoolP256r1",nP="brainpoolP256t1",iP="brainpoolP320r1",oP="brainpoolP320t1",aP="brainpoolP384r1",cP="brainpoolP384t1",dP="brainpoolP512r1",lP="brainpoolP512t1",rr="ECDSA",jp=xx=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case rr.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return iR;case"sha-256":return oR;case"sha-384":return aR;case"sha-512":return cR}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=TS;break;case"K-256":r=xx.SECP256K1;break;case"P-384":r=AS;break;case"P-521":r=kS;break;case J5:r=U5;break;case Q5:r=M5;break;case Z5:r=j5;break;case eP:r=F5;break;case tP:r=H5;break;case rP:r=$5;break;case sP:r=V5;break;case nP:r=q5;break;case iP:r=z5;break;case oP:r=K5;break;case aP:r=W5;break;case cP:r=G5;break;case dP:r=X5;break;case lP:r=Y5;break}if(r)return new be({algorithm:ad,parameters:_e.serialize(new ii({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case sp:return{name:rr,hash:{name:"SHA-1"}};case np:return{name:rr,hash:{name:"SHA-256"}};case ip:return{name:rr,hash:{name:"SHA-384"}};case op:return{name:rr,hash:{name:"SHA-512"}};case ad:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(_e.parse(e.parameters,ii).namedCurve){case TS:return{name:rr,namedCurve:"P-256"};case xx.SECP256K1:return{name:rr,namedCurve:"K-256"};case AS:return{name:rr,namedCurve:"P-384"};case kS:return{name:rr,namedCurve:"P-521"};case U5:return{name:rr,namedCurve:J5};case M5:return{name:rr,namedCurve:Q5};case j5:return{name:rr,namedCurve:Z5};case F5:return{name:rr,namedCurve:eP};case H5:return{name:rr,namedCurve:tP};case $5:return{name:rr,namedCurve:rP};case V5:return{name:rr,namedCurve:sP};case q5:return{name:rr,namedCurve:nP};case z5:return{name:rr,namedCurve:iP};case K5:return{name:rr,namedCurve:oP};case W5:return{name:rr,namedCurve:aP};case G5:return{name:rr,namedCurve:cP};case X5:return{name:rr,namedCurve:dP};case Y5:return{name:rr,namedCurve:lP}}}}return null}};jp.SECP256K1="1.3.132.0.10";jp=xx=b([wa()],jp);zt.registerSingleton(Vp,jp);vP=Symbol("name"),_P=Symbol("value"),kt=class{constructor(e,r={},s=""){this[vP]=e,this[_P]=s;for(let n in r)this[n]=r[n]}};kt.NAME=vP;kt.VALUE=_P;O2=class{static toTextObject(e){let r=new kt("Algorithm Identifier",{},ui.toString(e.algorithm));if(e.parameters)if(e.algorithm===ad){let s=new jp().toWebAlgorithm(e);s&&"namedCurve"in s?r["Named Curve"]=s.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}},ui=class{static toString(e){let r=this.items[e];return r||e}};ui.items={[dd]:"sha1",[Xy]:"sha224",[ld]:"sha256",[ud]:"sha384",[fd]:"sha512",[oi]:"rsaEncryption",[ou]:"sha1WithRSAEncryption",[gR]:"sha224WithRSAEncryption",[Gy]:"sha256WithRSAEncryption",[au]:"sha384WithRSAEncryption",[cu]:"sha512WithRSAEncryption",[ad]:"ecPublicKey",[sp]:"ecdsaWithSHA1",[Wy]:"ecdsaWithSHA224",[np]:"ecdsaWithSHA256",[ip]:"ecdsaWithSHA384",[op]:"ecdsaWithSHA512",[o4]:"TLS WWW server authentication",[a4]:"TLS WWW client authentication",[c4]:"Code Signing",[d4]:"E-mail Protection",[l4]:"Time Stamping",[u4]:"OCSP Signing",[tR]:"Signed Data"};so=class{static serialize(e){return this.serializeObj(e).join(`
30
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){let s=[],n=this.pad(r++),i="",o=e[kt.VALUE];o&&(i=` ${o}`),s.push(`${n}${e[kt.NAME]}:${i}`),n=this.pad(r);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],d=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")s.push(`${n}${d}${c}`);else if(c instanceof Date)s.push(`${n}${d}${c.toUTCString()}`);else if(Array.isArray(c))for(let u of c)u[kt.NAME]=a,s.push(...this.serializeObj(u,r));else if(c instanceof kt)c[kt.NAME]=a,s.push(...this.serializeObj(c,r));else if(Ce.isBufferSource(c))a?(s.push(`${n}${d}`),s.push(...this.serializeBufferSource(c,r+1))):s.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){let u=c.toTextObject();u[kt.NAME]=a,s.push(...this.serializeObj(u,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return s}static serializeBufferSource(e,r=0){let s=this.pad(r),n=Ce.toUint8Array(e),i=[];for(let o=0;o<n.length;){let a=[];for(let c=0;c<16&&o<n.length;c++){c===8&&a.push("");let d=n[o++].toString(16).padStart(2,"0");a.push(d)}i.push(`${s}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};so.oidSerializer=ui;so.algorithmSerializer=O2;Ca=class t{get rawData(){return ft(this,yu,"f")||Wt(this,yu,_e.serialize(this.asn),"f"),ft(this,yu,"f")}constructor(...e){yu.set(this,void 0),Ce.isBufferSource(e[0])?(this.asn=_e.parse(e[0],e[1]),Wt(this,yu,Ce.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof t?B3(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return _e.toString(this.rawData);case"text":return so.serialize(this.toTextObject());case"hex":return Ve.ToHex(this.rawData);case"base64":return Ve.ToBase64(this.rawData);case"base64url":return Ve.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 kt(this.getTextName(),{},e)}};yu=new WeakMap;Ca.NAME="ASN";Ds=class t extends Ca{constructor(...e){let r;Ce.isBufferSource(e[0])?r=Ce.toArrayBuffer(e[0]):r=_e.serialize(new Jr({extnID:e[0],critical:e[1],extnValue:new We(Ce.toArrayBuffer(e[2]))})),super(r,Jr)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[kt.NAME]===t.NAME&&(e[kt.NAME]=ui.toString(this.type)),e}},Fp=class t{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[SP]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(t.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(t.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=t.DEFAULT){let r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(t.DEFAULT,e);return this}};SP=Symbol.toStringTag;Fp.DEFAULT="default";pr=new Fp,IK=/^[0-2](?:\.[1-9][0-9]*)+$/;wx=class{constructor(e={}){this.items={};for(let r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return RK(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}},ys=new wx;ys.register("CN","2.5.4.3");ys.register("L","2.5.4.7");ys.register("ST","2.5.4.8");ys.register("O","2.5.4.10");ys.register("OU","2.5.4.11");ys.register("C","2.5.4.6");ys.register("DC","0.9.2342.19200300.100.1.25");ys.register("E","1.2.840.113549.1.9.1");ys.register("G","2.5.4.42");ys.register("I","2.5.4.43");ys.register("SN","2.5.4.4");ys.register("T","2.5.4.12");_n=class t{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new wx,this.asn=new jt;for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let n=r[s];this.extraNames.register(s,n)}typeof e=="string"?this.asn=this.fromString(e):e instanceof jt?this.asn=e:Ce.isBufferSource(e)?this.asn=_e.parse(e,jt):this.asn=this.fromJSON(e)}getField(e){let r=this.extraNames.findId(e)||ys.findId(e),s=[];for(let n of this.asn)for(let i of n)i.type===r&&s.push(i.value.toString());return s}getName(e){return this.extraNames.get(e)||ys.get(e)}toString(){return this.asn.map(e=>e.map(r=>{let s=this.getName(r.type)||r.type,n=r.value.anyValue?`#${Ve.ToHex(r.value.anyValue)}`:BK(r.value.toString());return`${s}=${n}`}).join("+")).join(", ")}toJSON(){var e;let r=[];for(let s of this.asn){let n={};for(let i of s){let o=this.getName(i.type)||i.type;(e=n[o])!==null&&e!==void 0||(n[o]=[]),n[o].push(i.value.anyValue?`#${Ve.ToHex(i.value.anyValue)}`:i.value.toString())}r.push(n)}return r}fromString(e){let r=new jt,s=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";for(;n=s.exec(`${e},`);){let[,o,a]=n,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),n[3]=c);let d=n[3];o=this.getTypeOid(o);let u=this.createAttribute(o,a);i==="+"?r[r.length-1].push(u):r.push(new ia([u])),i=d}return r}fromJSON(e){let r=new jt;for(let s of e){let n=new ia;for(let i in s){let o=this.getTypeOid(i),a=s[i];for(let c of a){let d=this.createAttribute(o,c);n.push(d)}}r.push(n)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){let s=new jc({type:e});if(typeof r=="object")for(let n in r)switch(n){case"ia5String":s.value.ia5String=r[n];break;case"utf8String":s.value.utf8String=r[n];break;case"universalString":s.value.universalString=r[n];break;case"bmpString":s.value.bmpString=r[n];break;case"printableString":s.value.printableString=r[n];break}else if(r[0]==="#")s.value.anyValue=Ve.FromHex(r.slice(1));else{let n=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?s.value.ia5String=n:t.isPrintableString(n)?s.value.printableString=n:s.value.utf8String=n}return s}processStringValue(e){let r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/ig,`
31
+ `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return _e.serialize(this.asn)}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.toArrayBuffer())}},EP="Cannot initialize GeneralName from ASN.1 data.",uP=`${EP} Unsupported string format in use.`,DK=`${EP} Value doesn't match to GUID regular expression.`,fP=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,hP="1.3.6.1.4.1.311.25.1",pP="1.3.6.1.4.1.311.20.2.3",C2="dns",T2="dn",A2="email",k2="ip",I2="url",R2="guid",P2="upn",mx="id",li=class extends Ca{constructor(...e){let r;if(e.length===2)switch(e[0]){case T2:{let s=new _n(e[1]).toArrayBuffer(),n=_e.parse(s,jt);r=new Je({directoryName:n});break}case C2:r=new Je({dNSName:e[1]});break;case A2:r=new Je({rfc822Name:e[1]});break;case R2:{let s=new RegExp(fP,"i").exec(e[1]);if(!s)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let n=s.slice(1).map((i,o)=>o<3?Ve.ToHex(new Uint8Array(Ve.FromHex(i)).reverse()):i).join("");r=new Je({otherName:new oa({typeId:hP,value:_e.serialize(new We(Ve.FromHex(n)))})});break}case k2:r=new Je({iPAddress:e[1]});break;case mx:r=new Je({registeredID:e[1]});break;case P2:{r=new Je({otherName:new oa({typeId:pP,value:_e.serialize(Zv.toASN(e[1]))})});break}case I2:r=new Je({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else Ce.isBufferSource(e[0])?r=_e.parse(e[0],Je):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=C2,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=A2,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=k2,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=I2,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=mx,this.value=e.registeredID;else if(e.directoryName!=null)this.type=T2,this.value=new _n(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===hP){this.type=R2;let r=_e.parse(e.otherName.value,We),s=new RegExp(fP,"i").exec(Ve.ToHex(r));if(!s)throw new Error(DK);this.value=s.slice(1).map((n,i)=>i<3?Ve.ToHex(new Uint8Array(Ve.FromHex(n)).reverse()):n).join("-")}else if(e.otherName.typeId===pP)this.type=P2,this.value=_e.parse(e.otherName.value,hr).toString();else throw new Error(uP);else throw new Error(uP)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case T2:case C2:case R2:case k2:case mx:case P2:case I2:e=this.type.toUpperCase();break;case A2:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===mx&&(r=ui.toString(r)),new kt(e,void 0,r)}},no=class extends Ca{constructor(e){let r;if(e instanceof Gt)r=e;else if(Array.isArray(e)){let s=[];for(let n of e)if(n instanceof Je)s.push(n);else{let i=_e.parse(new li(n.type,n.value).rawData,Je);s.push(i)}r=new Gt(s)}else if(Ce.isBufferSource(e))r=_e.parse(e,Gt);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){let r=[];for(let s of e){let n=null;try{n=new li(s)}catch{continue}r.push(n)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let r of this.items){let s=r.toTextObject(),n=e[s[kt.NAME]];Array.isArray(n)||(n=[],e[s[kt.NAME]]=n),n.push(s)}return e}};no.NAME="GeneralNames";Mp="-{5}",Hp="\\n",NK=`[^${Hp}]+`,OK=`${Mp}BEGIN (${NK}(?=${Mp}))${Mp}`,LK=`${Mp}END \\1${Mp}`,wu="\\n",UK=`[^:${Hp}]+`,MK=`(?:[^${Hp}]+${wu}(?: +[^${Hp}]+${wu})*)`,jK="[a-zA-Z0-9=+/]+",FK=`(?:${jK}${wu})+`,mP=`${OK}${wu}(?:((?:${UK}: ${MK})+))?${wu}?(${FK})${LK}`,Ur=class{static isPem(e){return typeof e=="string"&&new RegExp(mP,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let r=new RegExp(mP,"g"),s=[],n=null;for(;n=r.exec(e);){let i=n[3].replace(new RegExp(`[${Hp}]+`,"g"),""),o={type:n[1],headers:[],rawData:Ve.FromBase64(i)},a=n[2];if(a){let c=a.split(new RegExp(wu,"g")),d=null;for(let u of c){let[l,f]=u.split(/:(.*)/);if(f===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=l.trim()}else d&&o.headers.push(d),d={key:l,value:f.trim()}}d&&o.headers.push(d)}s.push(o)}return s}static decode(e){return this.decodeWithHeaders(e).map(s=>s.rawData)}static decodeFirst(e){let r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){let s=new Array;return r?e.forEach(n=>{if(!Ce.isBufferSource(n))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");s.push(this.encodeStruct({type:r,rawData:Ce.toArrayBuffer(n)}))}):e.forEach(n=>{if(!("type"in n))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");s.push(this.encodeStruct(n))}),s.join(`
32
+ `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:Ce.toArrayBuffer(e)})}}static encodeStruct(e){var r;let s=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${s}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(let d of e.headers)n.push(`${d.key}: ${d.value}`);n.push("")}let i=Ve.ToBase64(e.rawData),o,a=0,c=Array();for(;a<i.length&&(i.length-a<64?o=i.substring(a):(o=i.substring(a,a+64),a+=64),o.length!==0);)if(c.push(o),o.length<64)break;return n.push(...c),n.push(`-----END ${s}-----`),n.join(`
33
+ `)}};Ur.CertificateTag="CERTIFICATE";Ur.CrlTag="CRL";Ur.CertificateRequestTag="CERTIFICATE REQUEST";Ur.PublicKeyTag="PUBLIC KEY";Ur.PrivateKeyTag="PRIVATE KEY";Ta=class t extends Ca{static isAsnEncoded(e){return Ce.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Ur.isPem(e))return Ur.decode(e)[0];if(Ve.isHex(e))return Ve.FromHex(e);if(Ve.isBase64(e))return Ve.FromBase64(e);if(Ve.isBase64Url(e))return Ve.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let r=Ce.toUint8Array(e);if(r.length>0&&r[0]===48)return Ce.toArrayBuffer(e);let s=Ve.ToBinary(e);if(Ur.isPem(s))return Ur.decode(s)[0];if(Ve.isHex(s))return Ve.FromHex(s);if(Ve.isBase64(s))return Ve.FromBase64(s);if(Ve.isBase64Url(s))return Ve.FromBase64Url(s);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){t.isAsnEncoded(e[0])?super(t.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Ur.encode(this.rawData,this.tag):super.toString(e)}},ro=class t extends Ta{static async create(e,r=pr.get()){if(e instanceof t)return e;if(Fp.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let s=await r.subtle.exportKey("spki",e);return new t(s)}else{if(e.publicKey)return e.publicKey;if(Ce.isBufferSource(e))return new t(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Ta.isAsnEncoded(e)?super(e,Dr):super(e),this.tag=Ur.PublicKeyTag}async export(...e){let r,s=["verify"],n={hash:"SHA-256",...this.algorithm};e.length>1?(n=e[0]||n,s=e[1]||s,r=e[2]||pr.get()):r=e[0]||pr.get();let i=this.rawData,o=_e.parse(this.rawData,Dr);return o.algorithm.algorithm===ga&&(i=HK(o,i)),r.subtle.importKey("spki",i,n,!0,s)}onInit(e){let r=zt.resolve(wd),s=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===oi){let n=_e.parse(e.subjectPublicKey,uu),i=Ce.toUint8Array(n.modulus);s.publicExponent=Ce.toUint8Array(n.publicExponent),s.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let r,s="SHA-1";e.length===1?typeof e[0]=="string"?(s=e[0],r=pr.get()):r=e[0]:e.length===2?(s=e[0],r=e[1]):r=pr.get();let n=_e.parse(this.rawData,Dr);return await r.subtle.digest(s,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),r=_e.parse(this.rawData,Dr);switch(e.Algorithm=so.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case ad:e["EC Point"]=r.subjectPublicKey;break;case oi:default:e["Raw Data"]=r.subjectPublicKey}return e}};vx=class t extends Ds{static async create(e,r=!1,s=pr.get()){if("name"in e&&"serialNumber"in e)return new t(e,r);let i=await(await ro.create(e,s)).getKeyIdentifier(s);return new t(Ve.ToHex(i),r)}constructor(...e){if(Ce.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let r=new ei({keyIdentifier:new Vc(Ve.FromHex(e[0]))});super(by,e[1],_e.serialize(r))}else{let r=e[0],s=r.name instanceof no?_e.parse(r.name.rawData,Gt):r.name,n=new ei({authorityCertIssuer:s,authorityCertSerialNumber:Ve.FromHex(r.serialNumber)});super(by,e[1],_e.serialize(n))}}onInit(e){super.onInit(e);let r=_e.parse(e.extnValue,ei);r.keyIdentifier&&(this.keyId=Ve.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?Ve.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),r=_e.parse(this.value,ei);return r.authorityCertIssuer&&(e["Authority Issuer"]=new no(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}};vx.NAME="Authority Key Identifier";_x=class extends Ds{constructor(...e){if(Ce.isBufferSource(e[0])){super(e[0]);let r=_e.parse(this.value,qc);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{let r=new qc({cA:e[0],pathLenConstraint:e[1]});super(wy,e[2],_e.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};_x.NAME="Basic Constraints";(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(gP||(gP={}));Sx=class extends Ds{constructor(...e){if(Ce.isBufferSource(e[0])){super(e[0]);let r=_e.parse(this.value,Nh);this.usages=r.map(s=>s)}else{let r=new Nh(e[0]);super(Cy,e[1],_e.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>ui.toString(r)).join(", "),e}};Sx.NAME="Extended Key Usages";(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(yP||(yP={}));Ex=class extends Ds{constructor(...e){if(Ce.isBufferSource(e[0])){super(e[0]);let r=_e.parse(this.value,Vl);this.usages=r.toNumber()}else{let r=new Vl(e[0]);super(Ty,e[1],_e.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=_e.parse(this.value,Vl);return e[""]=r.toJSON().join(", "),e}};Ex.NAME="Key Usages";Cx=class t extends Ds{static async create(e,r=!1,s=pr.get()){let i=await(await ro.create(e,s)).getKeyIdentifier(s);return new t(Ve.ToHex(i),r)}constructor(...e){if(Ce.isBufferSource(e[0])){super(e[0]);let r=_e.parse(this.value,fs);this.keyId=Ve.ToHex(r)}else{let r=typeof e[0]=="string"?Ve.FromHex(e[0]):e[0],s=new fs(r);super(U_,e[1],_e.serialize(s)),this.keyId=Ve.ToHex(r)}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=_e.parse(this.value,fs);return e[""]=r,e}};Cx.NAME="Subject Key Identifier";Tx=class extends Ds{constructor(...e){Ce.isBufferSource(e[0])?super(e[0]):super(N_,e[1],new no(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=_e.parse(e.extnValue,Ry);this.names=new no(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};Tx.NAME="Subject Alternative Name";ss=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new Ds(e),s=this.items.get(r.type);return s?new s(e):r}};ss.items=new Map;Ax=class extends Ds{constructor(...e){var r;if(Ce.isBufferSource(e[0])){super(e[0]);let s=_e.parse(this.value,Ih);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(r=e[1])!==null&&r!==void 0?r:!1,i=new Ih(s.map(o=>new zc({policyIdentifier:o})));super(_y,n,_e.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new kt("",{},ui.toString(r))),e}};Ax.NAME="Certificate Policies";ss.register(_y,Ax);kx=class extends Ds{constructor(...e){var r;if(Ce.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new ti({distributionPoint:new Yi({fullName:[new Je({uniformResourceIdentifier:o})]})})),i=new da(n);super(Sy,e[1],_e.serialize(i))}else{let s=new da(e[0]);super(Sy,e[1],_e.serialize(s))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let r=_e.parse(e.extnValue,da);this.distributionPoints=r}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var s;let n={};return r.distributionPoint&&(n[""]=(s=r.distributionPoint.fullName)===null||s===void 0?void 0:s.map(i=>new li(i).toString()).join(", ")),r.reasons&&(n.Reasons=r.reasons.toString()),r.cRLIssuer&&(n["CRL Issuer"]=r.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};kx.NAME="CRL Distribution Points";Ix=class extends Ds{constructor(...e){var r,s,n,i;if(Ce.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof $c){let o=new $c(e[0]);super(xy,e[1],_e.serialize(o))}else{let o=e[0],a=new $c;yx(a,o,p_,"ocsp"),yx(a,o,m_,"caIssuers"),yx(a,o,g_,"timeStamping"),yx(a,o,y_,"caRepository"),super(xy,e[1],_e.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(s=this.caIssuers)!==null&&s!==void 0||(this.caIssuers=[]),(n=this.timeStamping)!==null&&n!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],_e.parse(e.extnValue,$c).forEach(s=>{switch(s.accessMethod){case p_:this.ocsp.push(new li(s.accessLocation));break;case m_:this.caIssuers.push(new li(s.accessLocation));break;case g_:this.timeStamping.push(new li(s.accessLocation));break;case y_:this.caRepository.push(new li(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&gx(e,"OCSP",this.ocsp),this.caIssuers.length&&gx(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&gx(e,"Time Stamping",this.timeStamping),this.caRepository.length&&gx(e,"CA Repository",this.caRepository),e}};Ix.NAME="Authority Info Access";Rx=class extends Ds{constructor(...e){Ce.isBufferSource(e[0])?super(e[0]):super(R_,e[1],new no(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=_e.parse(e.extnValue,Gt);this.names=new no(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};Rx.NAME="Issuer Alternative Name";vu=class t extends Ca{constructor(...e){let r;if(Ce.isBufferSource(e[0]))r=Ce.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>Ce.toArrayBuffer(i)):[];r=_e.serialize(new Br({type:s,values:n}))}super(r,Br)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new kt("",{"":r})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[kt.NAME]===t.NAME&&(e[kt.NAME]=ui.toString(this.type)),e}};vu.NAME="Attribute";Px=class extends vu{constructor(...e){var r;if(Ce.isBufferSource(e[0]))super(e[0]);else{let s=new mp({printableString:e[0]});super(w2,[_e.serialize(s)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let r=_e.parse(this.values[0],mp);this.password=r.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[kt.VALUE]=this.password,e}};Px.NAME="Challenge Password";$p=class extends vu{constructor(...e){var r;if(Ce.isBufferSource(e[0]))super(e[0]);else{let s=e[0],n=new Ps;for(let i of s)n.push(_e.parse(i.rawData,Jr));super(yp,[_e.serialize(n)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let r=_e.parse(this.values[0],Ps);this.items=r.map(s=>ss.create(_e.serialize(s)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.items.map(s=>s.toTextObject());for(let s of r)e[s[kt.NAME]]=s;return e}};$p.NAME="Extensions";_u=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new vu(e),s=this.items.get(r.type);return s?new s(e):r}};_u.items=new Map;qp="crypto.signatureFormatter",L2=class{toAsnSignature(e,r){return Ce.toArrayBuffer(r)}toWebSignature(e,r){return Ce.toArrayBuffer(r)}},U2=bx=class{static createPssParams(e,r){let s=bx.getHashAlgorithm(e);return s?new ai({hashAlgorithm:s,maskGenAlgorithm:new be({algorithm:ya,parameters:_e.serialize(s)}),saltLength:r}):null}static getHashAlgorithm(e){let r=zt.resolve(wd);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new be({algorithm:ou,parameters:null});case"sha-256":return new be({algorithm:Gy,parameters:null});case"sha-384":return new be({algorithm:au,parameters:null});case"sha-512":return new be({algorithm:cu,parameters:null})}}else return new be({algorithm:oi,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let r=bx.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new be({algorithm:ga,parameters:_e.serialize(r)})}else return new be({algorithm:ga,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case oi:return{name:"RSASSA-PKCS1-v1_5"};case ou:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Gy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case au:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case cu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case ga:if(e.parameters){let r=_e.parse(e.parameters,ai);return{name:"RSA-PSS",hash:zt.resolve(wd).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};U2=bx=b([wa()],U2);zt.registerSingleton(Vp,U2);M2=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new be({algorithm:dd});case"sha-256":return new be({algorithm:ld});case"sha-384":return new be({algorithm:ud});case"sha-512":return new be({algorithm:fd})}return null}toWebAlgorithm(e){switch(e.algorithm){case dd:return{name:"SHA-1"};case ld:return{name:"SHA-256"};case ud:return{name:"SHA-384"};case fd:return{name:"SHA-512"}}return null}};M2=b([wa()],M2);zt.registerSingleton(Vp,M2);io=class t{addPadding(e,r){let s=Ce.toUint8Array(r),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,r=!1){let s=Ce.toUint8Array(e);for(let n=0;n<s.length;n++)if(s[n]){s=s.slice(n);break}if(r&&s[0]>127){let n=new Uint8Array(s.length+1);return n.set(s,1),n.buffer}return s.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){let s=e.namedCurve,n=t.namedCurveSize.get(s)||t.defaultNamedCurveSize,i=new cd,o=Ce.toUint8Array(r);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),_e.serialize(i)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){let s=_e.parse(r,cd),n=e.namedCurve,i=t.namedCurveSize.get(n)||t.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(s.r)),a=this.addPadding(i,this.removePadding(s.s));return P3(o,a)}return null}};io.namedCurveSize=new Map;io.defaultNamedCurveSize=32;B2="1.3.101.110",xP="1.3.101.111",D2="1.3.101.112",bP="1.3.101.113",j2=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=D2;break;case"x25519":r=B2;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=D2;break;case"ed448":r=bP;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=B2;break;case"x448":r=xP;break}}return r?new be({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case D2:return{name:"Ed25519"};case bP:return{name:"EdDSA",namedCurve:"Ed448"};case B2:return{name:"X25519"};case xP:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};j2=b([wa()],j2);zt.registerSingleton(Vp,j2);F2=class extends Ta{get subjectName(){return ft(this,vp,"f")||Wt(this,vp,new _n(this.asn.certificationRequestInfo.subject),"f"),ft(this,vp,"f")}get subject(){return ft(this,_p,"f")||Wt(this,_p,this.subjectName.toString(),"f"),ft(this,_p,"f")}get signatureAlgorithm(){if(!ft(this,Sp,"f")){let e=zt.resolve(wd);Wt(this,Sp,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ft(this,Sp,"f")}get signature(){return ft(this,Ep,"f")||Wt(this,Ep,this.asn.signature,"f"),ft(this,Ep,"f")}get publicKey(){return ft(this,Cp,"f")||Wt(this,Cp,new ro(this.asn.certificationRequestInfo.subjectPKInfo),"f"),ft(this,Cp,"f")}get attributes(){return ft(this,Tp,"f")||Wt(this,Tp,this.asn.certificationRequestInfo.attributes.map(e=>_u.create(_e.serialize(e))),"f"),ft(this,Tp,"f")}get extensions(){if(!ft(this,xu,"f")){Wt(this,xu,[],"f");let e=this.getAttribute(yp);e instanceof $p&&Wt(this,xu,e.items,"f")}return ft(this,xu,"f")}get tbs(){return ft(this,wp,"f")||Wt(this,wp,this.asn.certificationRequestInfoRaw||_e.serialize(this.asn.certificationRequestInfo),"f"),ft(this,wp,"f")}constructor(e){let r=Ta.isAsnEncoded(e)?[e,Ea]:[e];super(r[0],r[1]),wp.set(this,void 0),vp.set(this,void 0),_p.set(this,void 0),Sp.set(this,void 0),Ep.set(this,void 0),Cp.set(this,void 0),Tp.set(this,void 0),xu.set(this,void 0),this.tag=Ur.CertificateRequestTag}onInit(e){}getAttribute(e){for(let r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(let r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=pr.get()){let r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],e),n=zt.resolveAll(qp).reverse(),i=null;for(let a of n)if(i=a.toWebSignature(r,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,s,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),r=_e.parse(this.rawData,Ea),s=r.certificationRequestInfo,n=new kt("",{Version:`${ri[s.version]} (${s.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new kt("");for(let o of this.attributes){let a=o.toTextObject();i[a[kt.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new kt("",{Algorithm:so.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}};wp=new WeakMap,vp=new WeakMap,_p=new WeakMap,Sp=new WeakMap,Ep=new WeakMap,Cp=new WeakMap,Tp=new WeakMap,xu=new WeakMap;F2.NAME="PKCS#10 Certificate Request";Bx=class extends Ta{get publicKey(){return ft(this,Up,"f")||Wt(this,Up,new ro(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),ft(this,Up,"f")}get serialNumber(){if(!ft(this,kp,"f")){let e=this.asn.tbsCertificate,r=new Uint8Array(e.serialNumber);r.length>1&&r[0]===0&&r[1]>127&&(r=r.slice(1)),Wt(this,kp,Ve.ToHex(r),"f")}return ft(this,kp,"f")}get subjectName(){return ft(this,Ip,"f")||Wt(this,Ip,new _n(this.asn.tbsCertificate.subject),"f"),ft(this,Ip,"f")}get subject(){return ft(this,Rp,"f")||Wt(this,Rp,this.subjectName.toString(),"f"),ft(this,Rp,"f")}get issuerName(){return ft(this,Pp,"f")||Wt(this,Pp,new _n(this.asn.tbsCertificate.issuer),"f"),ft(this,Pp,"f")}get issuer(){return ft(this,Bp,"f")||Wt(this,Bp,this.issuerName.toString(),"f"),ft(this,Bp,"f")}get notBefore(){if(!ft(this,Dp,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Wt(this,Dp,e,"f")}return ft(this,Dp,"f")}get notAfter(){if(!ft(this,Np,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Wt(this,Np,e,"f")}return ft(this,Np,"f")}get signatureAlgorithm(){if(!ft(this,Op,"f")){let e=zt.resolve(wd);Wt(this,Op,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ft(this,Op,"f")}get signature(){return ft(this,Lp,"f")||Wt(this,Lp,this.asn.signatureValue,"f"),ft(this,Lp,"f")}get extensions(){return ft(this,bu,"f")||(Wt(this,bu,[],"f"),this.asn.tbsCertificate.extensions&&Wt(this,bu,this.asn.tbsCertificate.extensions.map(e=>ss.create(_e.serialize(e))),"f")),ft(this,bu,"f")}get tbs(){return ft(this,Ap,"f")||Wt(this,Ap,this.asn.tbsCertificateRaw||_e.serialize(this.asn.tbsCertificate),"f"),ft(this,Ap,"f")}constructor(e){let r=Ta.isAsnEncoded(e)?[e,Js]:[e];super(r[0],r[1]),Ap.set(this,void 0),kp.set(this,void 0),Ip.set(this,void 0),Rp.set(this,void 0),Pp.set(this,void 0),Bp.set(this,void 0),Dp.set(this,void 0),Np.set(this,void 0),Op.set(this,void 0),Lp.set(this,void 0),bu.set(this,void 0),Up.set(this,void 0),this.tag=Ur.CertificateTag}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=pr.get()){let s,n,i=e.publicKey;try{if(!i)s={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(s,["verify"],r);else if("publicKey"in i)s={...i.publicKey.algorithm,...this.signatureAlgorithm},n=await i.publicKey.export(s,["verify"],r);else if(i instanceof ro)s={...i.algorithm,...this.signatureAlgorithm},n=await i.export(s,["verify"],r);else if(Ce.isBufferSource(i)){let d=new ro(i);s={...d.algorithm,...this.signatureAlgorithm},n=await d.export(s,["verify"],r)}else s={...i.algorithm,...this.signatureAlgorithm},n=i}catch{return!1}let o=zt.resolveAll(qp).reverse(),a=null;for(let d of o)if(a=d.toWebSignature(s,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await r.subtle.verify(this.signatureAlgorithm,n,a,this.tbs);if(e.signatureOnly)return c;{let u=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let r,s="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(s=e[0]||s,r=e[1])),r??(r=pr.get()),await r.subtle.digest(s,this.rawData)}async isSelfSigned(e=pr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),r=_e.parse(this.rawData,Js),s=r.tbsCertificate,n=new kt("",{Version:`${ri[s.version]} (${s.version})`,"Serial Number":s.serialNumber,"Signature Algorithm":so.serializeAlgorithm(s.signature),Issuer:this.issuer,Validity:new kt("",{"Not Before":s.validity.notBefore.getTime(),"Not After":s.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(s.issuerUniqueID&&(n["Issuer Unique ID"]=s.issuerUniqueID),s.subjectUniqueID&&(n["Subject Unique ID"]=s.subjectUniqueID),this.extensions.length){let i=new kt("");for(let o of this.extensions){let a=o.toTextObject();i[a[kt.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new kt("",{Algorithm:so.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}};Ap=new WeakMap,kp=new WeakMap,Ip=new WeakMap,Rp=new WeakMap,Pp=new WeakMap,Bp=new WeakMap,Dp=new WeakMap,Np=new WeakMap,Op=new WeakMap,Lp=new WeakMap,bu=new WeakMap,Up=new WeakMap;Bx.NAME="Certificate";Dx=class{static async createSelfSigned(e,r=pr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=pr.get()){var s;let n;e.publicKey instanceof ro?n=e.publicKey.rawData:"publicKey"in e.publicKey?n=e.publicKey.publicKey.rawData:Ce.isBufferSource(e.publicKey)?n=e.publicKey:n=await r.subtle.exportKey("spki",e.publicKey);let i=$K(e.serialNumber,r),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new Js({tbsCertificate:new Nr({version:ri.v3,serialNumber:i,validity:new Ji({notBefore:o,notAfter:a}),extensions:new Ps(((s=e.extensions)===null||s===void 0?void 0:s.map(p=>_e.parse(p.rawData,Jr)))||[]),subjectPublicKeyInfo:_e.parse(n,Dr)})});if(e.subject){let p=e.subject instanceof _n?e.subject:new _n(e.subject);c.tbsCertificate.subject=_e.parse(p.toArrayBuffer(),jt)}if(e.issuer){let p=e.issuer instanceof _n?e.issuer:new _n(e.issuer);c.tbsCertificate.issuer=_e.parse(p.toArrayBuffer(),jt)}let d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},l=zt.resolve(wd);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(u);let f=_e.serialize(c.tbsCertificate),h="signingKey"in e?await r.subtle.sign(u,e.signingKey,f):e.signature,m=zt.resolveAll(qp).reverse(),v=null;for(let p of m)if(v=p.toAsnSignature(u,h),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new Bx(_e.serialize(c))}};(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(wP||(wP={}));VK=new WeakMap,qK=new WeakMap,zK=new WeakMap,KK=new WeakMap,WK=new WeakMap;GK=new WeakMap,XK=new WeakMap,YK=new WeakMap,JK=new WeakMap,QK=new WeakMap,ZK=new WeakMap,eW=new WeakMap;ss.register(wy,_x);ss.register(Cy,Sx);ss.register(Ty,Ex);ss.register(U_,Cx);ss.register(by,vx);ss.register(N_,Tx);ss.register(Sy,kx);ss.register(xy,Ix);ss.register(R_,Rx);_u.register(w2,Px);_u.register(yp,$p);zt.registerSingleton(qp,L2);zt.registerSingleton(qp,io);io.namedCurveSize.set("P-256",32);io.namedCurveSize.set("K-256",32);io.namedCurveSize.set("P-384",48);io.namedCurveSize.set("P-521",66)});var AP=Ne((xEe,TP)=>{"use strict";g();function rW(t){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(t)}TP.exports=rW});var zp=Ne((wEe,LP)=>{"use strict";g();var kP=require("util"),BP=AP(),IP=/[\{\[]/,RP=/[\}\]]/,PP=["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"],DP={};for(Nx=0;Nx<PP.length;Nx++)DP[PP[Nx]]=!0;var Nx,sW=function(t){return BP(t)&&!DP.hasOwnProperty(t)},NP={s:function(t){return""+t},d:function(t){return""+Number(t)},o:function(t){return JSON.stringify(t)}},OP=function(){var t=[],e=0,r={},s=function(o){for(var a="";a.length<e*2;)a+=" ";t.push(a+o)},n=function(o){if(RP.test(o.trim()[0])&&IP.test(o[o.length-1])){e--,s(o),e++;return}if(IP.test(o[o.length-1])){s(o),e++;return}if(RP.test(o.trim()[0])){e--,s(o);return}s(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
34
+ `)>-1)for(var a=o.trim().split(`
35
+ `),c=0;c<a.length;c++)n(a[c].trim());else n(kP.format.apply(kP,arguments));return i};return i.scope={},i.formats=NP,i.sym=function(o){return(!o||!sW(o))&&(o="tmp"),r[o]||(r[o]=0),o+(r[o]++||"")},i.property=function(o,a){return arguments.length===1&&(a=o,o=""),a=a+"",BP(a)?o?o+"."+a:a:o?o+"["+JSON.stringify(a)+"]":JSON.stringify(a)},i.toString=function(){return t.join(`
36
+ `)},i.toFunction=function(o){o||(o={});var a="return ("+i.toString()+")";Object.keys(i.scope).forEach(function(u){o[u]||(o[u]=i.scope[u])});var c=Object.keys(o).map(function(u){return u}),d=c.map(function(u){return o[u]});return Function.apply(null,c.concat(a)).apply(null,d)},arguments.length&&i.apply(null,arguments),i};OP.formats=NP;LP.exports=OP});var MP=Ne((_Ee,UP)=>{"use strict";g();var Lx=class{constructor(){this.next=null,this.buffer=null}};UP.exports=class Ox{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let r=new Lx;r.buffer=e,this.length>0?this.tail.next=r:this.head=r,this.tail=r,this.length+=e.length,this.count+=1}unshift(e){let r=new Lx;r.buffer=e,r.next=this.head,this.isEmpty()&&(this.tail=r),this.head=r,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,r){if(e<0||e>=this.length)return new Ox;if(r<0||r>this.length||r<e)return new Ox;let s=new Ox,n=this.head,i=e,o=r;for(;n;){if(n.buffer.length>i){i===0&&n.buffer.length<=o?s.push(n.buffer):n.buffer.length>=o?s.push(n.buffer.slice(i,o)):s.push(n.buffer.slice(i));break}i-=n.buffer.length,o-=n.buffer.length,n=n.next}if(n.buffer.length<o)for(;n;){if(n.buffer.length===o){s.push(n.buffer);break}else if(n.buffer.length>o){s.push(n.buffer.slice(0,o));break}else i<0&&n.buffer.length<o&&s.push(n.buffer);i-=n.buffer.length,o-=n.buffer.length,n=n.next}return s}}});var $P=Ne((EEe,HP)=>{"use strict";g();var Ux=zp(),nW=MP(),vd=class t{constructor(){this.queue=new nW,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let r=this.queue.shift();this.queue.unshift(r.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let r=0;r<e.length;r+=1)this.append(e[r]);else if(e instanceof t){if(this.offset>0){let s=this.queue.shift();this.queue.unshift(s.slice(this.offset)),this.offset=0}if(e.offset>0){let s=e.queue.shift();e.queue.unshift(s.slice(e.offset)),e.offset=0}let r=e.queue.head;for(;r;)this.queue.push(r.buffer),r=r.next}}get(e){let r=e;for(;r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let s=this.queue.head,{offset:n}=this;for(;s;){if(s.buffer.length-n>r)return s.buffer[r+n];r-=s.buffer.length-n,n=0,s=s.next}}slice(e,r){for(typeof e!="number"&&(e=0),typeof r!="number"&&(r=this.length);e<0;)e+=this.length;for(;r<0;)r+=this.length;if(r=Math.min(r,this.length),e>=this.length||r===0)return Buffer.alloc(0);let s=e;e=Math.min(s,r),r=Math.max(s,r);let n=this.queue.slice(e+this.offset,r+this.offset);if(n.count===1)return n.first;let i=n.head,o=Buffer.allocUnsafe(n.length),a=0;for(let c=0;c<n.count;c+=1)o.set(i.buffer,a),a+=i.buffer.length,i=i.next;return o}toString(e,r,s){return this.slice(r,s).toString(e)}consume(e){let r=e;for(;this.length>0;){let s=this.queue.first.length-this.offset;if(r>=s)this.queue.shift(),r-=s,this.offset=0;else{this.offset+=r;break}}}indexOf(e,r=0){if(!Number.isInteger(e))throw new TypeError("Invalid argument 1");if(e<0||e>255)throw new Error("Invalid argument 1");for(Number.isInteger(r)||(r=0);r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let s=this.queue.head,n=0,i=()=>{n+=s.buffer.length,s=s.next};for(;s;){let o=0;if(s===this.queue.head&&(o+=this.offset),r>=s.buffer.length-o){r-=s.buffer.length-o,i();continue}r<s.buffer.length&&(o+=r);let a=s.buffer.indexOf(e,o);if(a>-1)return a+n-this.offset;i(),o>this.offset&&(r=0)}return-1}},jP={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(jP).forEach(t=>{let e=Ux();e(`
37
+ function bufferlist_${t}(offset = 0) {
38
+ const start = offset + this.offset;
39
+ const head = this.queue.first;
40
+ const size = ${e.formats.d(jP[t])};
41
+ const isFirtsChunkEnough = head.length - start >= size;
42
+
43
+ return isFirtsChunkEnough
44
+ ? head.${t}(start)
45
+ : this.slice(offset, offset + size).${t}(0)
46
+ }
47
+ `),vd.prototype[t]=e.toFunction()});var iW=["readIntBE","readIntLE","readUIntBE","readUIntLE"];iW.forEach(t=>{let e=Ux();e(`
48
+ function bufferlist_${t}(size, offset = 0) {
49
+ const start = offset + this.offset;
50
+ const head = this.queue.first;
51
+ const isFirtsChunkEnough = head.length - start >= size;
52
+
53
+ return isFirtsChunkEnough
54
+ ? head.${t}(start, size)
55
+ : this.slice(offset, offset + size).${t}(0, size)
56
+ }
57
+ `),vd.prototype[t]=e.toFunction()});var FP={writeDoubleBE:8,writeDoubleLE:8,writeFloatBE:4,writeFloatLE:4,writeInt32BE:4,writeInt32LE:4,writeUInt32BE:4,writeUInt32LE:4,writeInt16BE:2,writeInt16LE:2,writeUInt16BE:2,writeUInt16LE:2,writeInt8:1,writeUInt8:1};Object.keys(FP).forEach(t=>{let e=Ux();e(`
58
+ function bufferlist_${t}(value) {
59
+ const size = ${e.formats.d(FP[t])};
60
+ const buf = Buffer.allocUnsafe(size);
61
+ buf.${t}(value, 0);
62
+ this.append(buf);
63
+ }
64
+ `),vd.prototype[t]=e.toFunction()});var oW=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];oW.forEach(t=>{let e=Ux();e(`
65
+ function bufferlist_${t}(value, size) {
66
+ const buf = Buffer.allocUnsafe(size);
67
+ buf.${t}(value, 0, size);
68
+ this.append(buf);
69
+ }
70
+ `),vd.prototype[t]=e.toFunction()});HP.exports=vd});var Su=Ne((AEe,VP)=>{"use strict";g();VP.exports=class extends Error{constructor(e,r){let s=`requested ${e} bytes but only ${r} available`;super(s),this.name="NotEnoughDataError"}}});var Kp=Ne((IEe,KP)=>{"use strict";g();var{Transform:aW}=require("stream"),Mx=zp(),cW=$P(),dW=Su(),qP=Symbol("buffer"),_d=class extends aW{constructor(e={}){super(e),this[qP]=new cW}get buffer(){return this[qP]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,r){return this.buffer.slice(e,r)}consume(e){this.buffer.consume(e)}toString(e,r,s){return this.buffer.toString(e,r,s)}indexOf(e,r=0){return this.buffer.indexOf(e,r)}readBuffer(e){H2(e,this.length);let r=this.slice(0,e);return this.consume(e),r}writeBuffer(e){this.append(e)}},zP={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},lW=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(zP).forEach(t=>{let e=Mx();e(`
71
+ function binary_${t}() {
72
+ const bytes = ${e.formats.d(zP[t])};
73
+ assertSize(bytes, this.length);
74
+
75
+ const res = this.buffer.${t}(0);
76
+ this.consume(bytes);
77
+
78
+ return res;
79
+ }
80
+ `),_d.prototype[t]=e.toFunction({assertSize:H2})});lW.forEach(t=>{let e=Mx();e(`
81
+ function binary_${t}(size) {
82
+ assertSize(size, this.length);
83
+
84
+ const res = this.buffer.${t}(size, 0);
85
+ this.consume(size);
86
+ return res;
87
+ }
88
+ `),_d.prototype[t]=e.toFunction({assertSize:H2})});var uW=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];uW.forEach(t=>{let e=Mx();e(`
89
+ function binary_${t}(value) {
90
+ this.buffer.${t}(value);
91
+ }
92
+ `),_d.prototype[t]=e.toFunction()});var fW=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];fW.forEach(t=>{let e=Mx();e(`
93
+ function binary_${t}(value, size) {
94
+ this.buffer.${t}(value, size);
95
+ }
96
+ `),_d.prototype[t]=e.toFunction()});function H2(t,e){if(t>e)throw new dW(t,e)}KP.exports=_d});var GP=Ne((PEe,WP)=>{"use strict";g();WP.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var JP=Ne((DEe,YP)=>{"use strict";g();var hW=GP();function XP(t){return hW(t)===!0&&Object.prototype.toString.call(t)==="[object Object]"}YP.exports=function(e){var r,s;return!(XP(e)===!1||(r=e.constructor,typeof r!="function")||(s=r.prototype,XP(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var fi=Ne((OEe,QP)=>{"use strict";g();var pW=JP();QP.exports={isType:mW,isUserType:pW,isFunction:Wp,isDecodeType:gW,isEncodeType:yW};function mW(t){return $2(t)&&Wp(t.encode)&&Wp(t.decode)}function Wp(t){return typeof t=="function"}function $2(t){return typeof t=="object"&&t!==null}function gW(t){return $2(t)&&Wp(t.decode)}function yW(t){return $2(t)&&Wp(t.encode)}});var Aa=Ne((UEe,ZP)=>{"use strict";g();var xW=Symbol("skip"),bW=Symbol("bytes");ZP.exports={skip:xW,bytes:bW}});var ka=Ne((jEe,t9)=>{"use strict";g();var e9=Aa();t9.exports=class jx{constructor(){this[e9.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[e9.bytes]}static clone(e){let r=new jx;return e instanceof jx&&(r.node=e.node,r.current=e.current),r}static clean(e){e instanceof jx&&(e.node=void 0,e.current=void 0)}}});var Eu=Ne((HEe,o9)=>{"use strict";g();var{isType:wW,isUserType:vW,isDecodeType:_W}=fi(),SW=Kp(),V2=Aa(),r9=ka();o9.exports={decode:s9,decodeCommon:n9};function s9(t,e){let r=t;Buffer.isBuffer(t)&&(r=new SW,r.append(t));let s=new r9,n=n9(r,e,s);return s9.bytes=s.bytes,r9.clean(s),n}function n9(t,e,r){if(wW(e)){let s=e.decode.call(r,t);return r[V2.bytes]+=e.decode.bytes,s}return i9(t,e,r)}function i9(t,e,r){EW(e);let s=Object.create(null);r.node===void 0&&(r.node=s),r.current=s;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],a=e[o];if(!_W(a)){s[o]=i9(t,a,r),r.current=s;continue}let c=a.decode.call(r,t);r[V2.bytes]+=a.decode.bytes,a[V2.skip]!==!0&&(s[o]=c)}return s}function EW(t){if(!vW(t))throw new TypeError("Argument #2 should be a plain object.")}});var Gp=Ne((VEe,f9)=>{"use strict";g();var{isUserType:CW,isEncodeType:TW,isType:AW}=fi(),c9=Aa(),a9=ka(),q2=Kp();f9.exports={encode:d9,encodeCommon:l9};function d9(t,e,r){let s=new a9;if(e instanceof q2){let n=r;r=e,e=n}return r instanceof q2||(r=new q2),l9(t,r,e,s),d9.bytes=s.bytes,a9.clean(s),r}function l9(t,e,r,s){AW(r)?(r.encode.call(s,t,e),s[c9.bytes]+=r.encode.bytes):u9(t,e,r,s)}function u9(t,e,r,s){kW(r),s.node===void 0&&(s.node=t),s.current=t;let n=Object.keys(r);for(let i=0;i<n.length;i+=1){let o=n[i],a=r[o],c=t[o];if(!TW(a)){u9(c,e,a,s),s.current=t;continue}a.encode.call(s,c,e),s[c9.bytes]+=a.encode.bytes}}function kW(t){if(!CW(t))throw new TypeError("Argument `schema` should be a plain object.")}});var Xp=Ne((zEe,x9)=>{"use strict";g();var{isUserType:IW,isType:p9}=fi(),h9=ka(),m9=Aa();x9.exports={encodingLength:RW,encodingLengthCommon:g9};function RW(t,e){let r=new h9;return g9(t,e,r),h9.clean(r),r.bytes}function g9(t,e,r){p9(e)?r[m9.bytes]+=e.encodingLength.call(r,t):y9(t,e,r)}function y9(t,e,r){if(!IW(e))throw new TypeError("Argument `schema` should be a plain object.");r.node===void 0&&(r.node=t),r.current=t;let s=Object.keys(e);for(let n=0;n<s.length;n+=1){let i=s[n],o=e[i],a=t[i];if(!p9(o)){y9(a,o,r),r.current=t;continue}r[m9.bytes]+=o.encodingLength.call(r,a)}}});var T9=Ne((WEe,C9)=>{"use strict";g();var{decodeCommon:E9}=Eu(),{encodeCommon:PW}=Gp(),{encodingLengthCommon:b9}=Xp(),{isType:w9,isUserType:BW,isFunction:DW}=fi(),Ia=ka();C9.exports=NW;function NW(t,e,r="count"){if(!w9(t)&&!BW(t))throw new TypeError("Argument #1 should be a valid type.");let s=r==="bytes",n=typeof e=="number",i=w9(e),o=DW(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,l){v9(u);let f=Ia.clone(this);a.bytes=0;let h=0;if(i?h=u.length:n?h=e:o&&(h=e(f),_9(h)),s||S9(h,u.length),s){let m=Ia.clone(f);for(let v of u)b9(v,t,m);i&&(h=m.bytes),S9(m.bytes,h),Ia.clean(m)}i&&(e.encode.call(f,h,l),a.bytes+=e.encode.bytes),u.forEach(m=>{PW(m,l,t,f)}),a.bytes+=f.bytes,Ia.clean(f)}function c(u){let l=0;c.bytes=0;let f=Ia.clone(this);n?l=e:i?(l=e.decode.call(f,u),c.bytes+=e.decode.bytes):o&&(l=e(f)),_9(l);let h;return s?h=OW(t,l,u,f):h=LW(t,l,u,f),c.bytes+=f.bytes,Ia.clean(f),h}function d(u){v9(u);let l=Ia.clone(this),f=0;if(n&&s)return e;i&&!s&&(f=e.encodingLength(u.length));for(let h of u)b9(h,t,l);return Ia.clean(l),f+=l.bytes,i&&s&&(f+=e.encodingLength(f)),f}}function v9(t){if(!Array.isArray(t))throw new TypeError("Argument #1 should be an Array.")}function _9(t){if(typeof t!="number")throw new TypeError("Length of an array should be a number.")}function S9(t,e){if(t!==e)throw new Error(`Argument #1 required length ${t} instead of ${e}`)}function OW(t,e,r,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(E9(r,t,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function LW(t,e,r,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=E9(r,t,s);return n}});var R9=Ne((XEe,I9)=>{"use strict";g();var{isType:UW,isFunction:MW}=fi(),jW=Su(),FW=Kp();I9.exports=HW;function HW(t){let e=typeof t=="number",r=UW(t),s=MW(t),n=t===null;if(!e&&!r&&!s&&!n)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,d){A9(c),i.bytes=0;let u=this;if(e&&k9(t,c.length),r&&(t.encode.call(u,c.length,d),i.bytes+=t.encode.bytes),s){let l=t(u);z2(l),k9(l,c.length)}d.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),i.bytes+=c.length,n&&(d.writeUInt8(0),i.bytes+=1)}function o(c){let d=0;o.bytes=0;let u=this;if(e)d=t;else if(r)d=t.decode.call(u,c),o.bytes+=t.decode.bytes,z2(d);else if(s)d=t(u),z2(d);else if(n&&(d=c.indexOf(0),d===-1))throw new jW(c.length+1,c.length);let l=c.readBuffer(d);return o.bytes+=d,n&&(o.bytes+=1,c.consume(1)),l}function a(c){A9(c);let d=0;return e?t:(n?d=1:r&&(d=t.encodingLength(c.length)),d+c.length)}}function A9(t){if(!Buffer.isBuffer(t)&&!(t instanceof FW))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function k9(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}function z2(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}});var B9=Ne((JEe,P9)=>{"use strict";g();var{isType:$W}=fi();P9.exports=VW;function VW(t){if(!$W(t))throw new TypeError("Argument #1 should be valid type.");function e(s){let n=this,i=t.decode.call(n,s);return e.bytes=t.decode.bytes,!!i}function r(s,n){let i=this;t.encode.call(i,s?1:0,n),r.bytes=t.encode.bytes}return{encode:r,decode:e,encodingLength:t.encodingLength}}});var N9=Ne((ZEe,D9)=>{"use strict";g();var{decodeCommon:qW}=Eu(),{encodeCommon:zW}=Gp(),{encodingLengthCommon:KW}=Xp(),{isType:WW,isFunction:Fx}=fi(),GW=Aa(),Ra=ka();D9.exports=XW;function XW(t,e=1){if(!WW(t))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Fx(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[GW.skip]:!0,encodingLength:r,decode:s,encode:n};function r(i){let o=Ra.clone(this),a=Fx(e)?e(o):e;return KW(i,t,o),Ra.clean(o),o.bytes*a}function s(i){let o=Ra.clone(this);s.bytes=0;let a=Fx(e)?e(o):e;if(a===0){Ra.clean(o);return}for(let c=a;c>0;c-=1)qW(i,t,o);s.bytes=o.bytes,Ra.clean(o)}function n(i,o){n.bytes=0;let a=Ra.clone(this),c=Fx(e)?e(a):e;if(c===0){Ra.clean(a);return}for(let d=c;d>0;d-=1)zW(0,o,t,a);n.bytes=a.bytes,Ra.clean(a)}}});var U9=Ne((tCe,L9)=>{"use strict";g();var{isType:YW}=fi(),JW=Su();L9.exports=QW;function QW(t,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof t=="number")return{encode:tG(t,e),decode:rG(t,e),encodingLength:()=>t};if(YW(t))return{encode:sG(t,e),decode:nG(t,e),encodingLength:iG(t,e)};if(t===null)return{encode:ZW(e),decode:eG(e),encodingLength(r){return Buffer.byteLength(r,e)+1}};if(typeof t=="function")return{encode:oG(t,e),decode:aG(t,e),encodingLength(r){return Buffer.byteLength(r,e)}};throw new TypeError("Unknown type of argument #1.")}function ZW(t){return function e(r,s){let n=Buffer.from(r.toString(),t);s.writeBuffer(n),s.writeInt8(0),e.bytes=n.length+1}}function eG(t){return function e(r){let s=r.indexOf(0);if(s===-1)throw new JW(r.length+1,r.length);let n=s+1,i=r.readBuffer(n);return e.bytes=n,i.toString(t,0,s)}}function tG(t,e){return function r(s,n){if(s=s.toString(),Buffer.byteLength(s,e)!==t)throw new Error(`Size of string should be ${t} in bytes.`);let i=Buffer.from(s,e);n.writeBuffer(i),r.bytes=i.length}}function rG(t,e){return function r(s){let n=s.readBuffer(t);return r.bytes=t,n.toString(e)}}function sG(t,e){return function r(s,n){s=s.toString();let i=this;t.encode.call(i,Buffer.byteLength(s,e),n),r.bytes=t.encode.bytes;let o=Buffer.from(s,e);n.writeBuffer(o),r.bytes+=o.length}}function nG(t,e){return function r(s){let n=t.decode.call(this,s);if(typeof n!="number")throw new TypeError("Size of a string should be a number.");let i=s.readBuffer(n);return r.bytes=t.decode.bytes+i.length,i.toString(e)}}function iG(t,e){return function(s){let n=Buffer.byteLength(s,e);return t.encodingLength(n)+n}}function oG(t,e){return function r(s,n){r.bytes=0;let o=t(this),a=Buffer.from(s.toString(),e);O9(o),cG(o,a.length),n.writeBuffer(a),r.bytes+=a.length}}function aG(t,e){return function r(s){let n=t(this);O9(n);let i=s.readBuffer(n);return r.bytes=n,i.toString(e)}}function O9(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}function cG(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}});var j9=Ne((sCe,M9)=>{"use strict";g();var Hx=zp();M9.exports={doublebe:bs(8,"writeDoubleBE","readDoubleBE"),doublele:bs(8,"writeDoubleLE","readDoubleLE"),floatbe:bs(4,"writeFloatBE","readFloatBE"),floatle:bs(4,"writeFloatLE","readFloatLE"),int8:bs(1,"writeInt8","readInt8"),uint8:bs(1,"writeUInt8","readUInt8"),int16be:bs(2,"writeInt16BE","readInt16BE"),uint16be:bs(2,"writeUInt16BE","readUInt16BE"),int16le:bs(2,"writeInt16LE","readInt16LE"),uint16le:bs(2,"writeUInt16LE","readUInt16LE"),int32be:bs(4,"writeInt32BE","readInt32BE"),uint32be:bs(4,"writeUInt32BE","readUInt32BE"),int32le:bs(4,"writeInt32LE","readInt32LE"),uint32le:bs(4,"writeUInt32LE","readUInt32LE"),int24be:rn(3,"writeIntBE","readIntBE"),uint24be:rn(3,"writeUIntBE","readUIntBE"),int24le:rn(3,"writeIntLE","readIntLE"),uint24le:rn(3,"writeUIntLE","readUIntLE"),int40be:rn(5,"writeIntBE","readIntBE"),uint40be:rn(5,"writeUIntBE","readUIntBE"),int40le:rn(5,"writeIntLE","readIntLE"),uint40le:rn(5,"writeUIntLE","readUIntLE"),int48be:rn(6,"writeIntBE","readIntBE"),uint48be:rn(6,"writeUIntBE","readUIntBE"),int48le:rn(6,"writeIntLE","readIntLE"),uint48le:rn(6,"writeUIntLE","readUIntLE")};function bs(t,e,r){let s=Hx(),n=Hx();return s(`
97
+ function decode_${r}(rstream) {
98
+ decode_${r}.bytes = ${s.formats.d(t)};
99
+ return rstream.${r}()
100
+ }
101
+ `),n(`
102
+ function encode_${e}(value, wstream) {
103
+ wstream.${e}(value);
104
+ encode_${e}.bytes = ${s.formats.d(t)};
105
+ }
106
+ `),{encodingLength:()=>t,encode:n.toFunction(),decode:s.toFunction()}}function rn(t,e,r){let s=Hx(),n=Hx();return s(`
107
+ function decode_${r}(rstream) {
108
+ decode_${r}.bytes = ${s.formats.d(t)};
109
+ return rstream.${r}(${s.formats.d(t)})
110
+ }
111
+ `),n(`
112
+ function encode_${e}(value, wstream) {
113
+ wstream.${e}(value, ${s.formats.d(t)});
114
+ encode_${e}.bytes = ${s.formats.d(t)};
115
+ }
116
+ `),{encodingLength:()=>t,encode:n.toFunction(),decode:s.toFunction()}}});var H9=Ne((iCe,F9)=>{"use strict";g();var{isType:dG,isFunction:K2,isUserType:lG}=fi(),W2=Aa(),{decodeCommon:uG}=Eu(),{encodeCommon:fG}=Gp(),{encodingLengthCommon:hG}=Xp(),Pa=ka();F9.exports=pG;function pG(t,e){if(!dG(e)&&!lG(e))throw new TypeError("Argument #2 should be a valid type.");let r={encode:s,decode:n,encodingLength:i,[W2.skip]:!1};return r;function s(o,a){let c=Pa.clone(this);s.bytes=0;let d=K2(t)?!!t(c):!!t;if(r[W2.skip]=!d,!d){Pa.clean(c);return}fG(o,a,e,c),s.bytes=c.bytes,Pa.clean(c)}function n(o){let a=Pa.clone(this);n.bytes=0;let c=K2(t)?!!t(a):!!t;if(r[W2.skip]=!c,!c){Pa.clean(a);return}let d=uG(o,e,a);return n.bytes=a.bytes,Pa.clean(a),d}function i(o){let a=Pa.clone(this);return(K2(t)?t(a):t)&&hG(o,e,a),Pa.clean(a),a.bytes}}});var q9=Ne((aCe,V9)=>{"use strict";g();var $x=Aa(),{decodeCommon:mG}=Eu(),$9=ka();V9.exports=gG;function gG(...t){if(t.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:r,encode:()=>{},[$x.skip]:!0};return e;function r(s){r.bytes=0;let n=$9.clone(this);for(let i of t){let o=mG(s,i,n);if(i[$x.skip]!==!0)return r.bytes=n.bytes,$9.clean(n),e[$x.skip]=!1,o}e[$x.skip]=!0}}});var G9=Ne((dCe,W9)=>{"use strict";g();var K9=zp(),yG=Su(),Yp=class{constructor(e){this.stream=e,this.index=0}append(e){this.stream.append(e)}commit(){this.stream.consume(this.index)}get(e=0){return this.stream.get(this.index+e)}get length(){return this.stream.length}slice(e,r){return this.stream.slice(e,r)}toString(e,r,s){return this.stream.toString(e,r,s)}readBuffer(e){G2(this.index+e,this.length);let r=this.stream.slice(this.index,this.index+e);return this.index+=e,r}indexOf(e,r=0){return this.stream.indexOf(e,this.index+r)-this.index}},z9={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(z9).forEach(t=>{let e=K9(),r=z9[t];e(`
117
+ function transaction_${t}() {
118
+ assertSize(this.index + ${e.formats.d(r)}, this.length);
119
+ const value = this.stream.buffer.${t}(this.index);
120
+ this.index += ${e.formats.d(r)};
121
+ return value;
122
+ }
123
+ `),Yp.prototype[t]=e.toFunction({assertSize:G2})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(t=>{let e=K9();e(`
124
+ function transaction_${t}(bytes) {
125
+ assertSize(this.index + bytes, this.length);
126
+ const value = this.stream.buffer.${t}(bytes, this.index);
127
+ this.index += bytes;
128
+ return value;
129
+ }
130
+ `),Yp.prototype[t]=e.toFunction({assertSize:G2})});W9.exports=Yp;function G2(t,e){if(t>e)throw new yG(t,e)}});var er=Ne((uCe,rB)=>{"use strict";g();var X2=Kp(),xG=T9(),bG=R9(),wG=B9(),vG=N9(),_G=U9(),X9=j9(),SG=H9(),EG=q9(),{encode:Q9}=Gp(),{decode:Z9}=Eu(),{encodingLength:CG}=Xp(),TG=G9(),eB=Su(),tB={array:xG,bool:wG,buffer:bG,reserved:vG,string:_G,when:SG,select:EG};for(let t of Object.keys(X9))tB[t]=X9[t];var Vx=Symbol("schema");function Y9(t){let e=new X2({readableObjectMode:!1,writableObjectMode:!0,transform:AG});return e[Vx]=t,e}function J9(t){let e=null,r=Buffer.isBuffer(t);r||(e=t);let s=new X2({transform:kG,readableObjectMode:!0,writableObjectMode:!1});return s[Vx]=e,r&&s.append(t),s}function AG(t,e,r){try{Q9(t,this[Vx],this);let s=this.slice();this.consume(s.length),r(null,s)}catch(s){r(s)}}function kG(t,e,r){this.append(t);try{for(;this.length>0;){let s=new TG(this),n=Z9(s,this[Vx]);s.commit(),this.push(n)}r()}catch(s){s instanceof eB?r():r(s)}}rB.exports={createEncodeStream:Y9,createDecodeStream:J9,encode:Q9,decode:Z9,encodingLength:CG,createEncode:Y9,createDecode:J9,types:tB,BinaryStream:X2,NotEnoughDataError:eB}});var oo,Sd,sB=z(()=>{"use strict";g();oo=Fe(require("crypto"),1),Sd=oo&&typeof oo=="object"&&"webcrypto"in oo?oo.webcrypto:oo&&typeof oo=="object"&&"randomBytes"in oo?oo:void 0});function Ed(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Jp(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Sn(t,...e){if(!Ed(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function qx(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jp(t.outputLen),Jp(t.blockLen)}function Tu(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function iB(t,e){Sn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function co(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function En(t,e){return t<<32-e|t>>>e}function lo(t){if(Sn(t),oB)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=IG[t[r]];return e}function nB(t){if(t>=ao._0&&t<=ao._9)return t-ao._0;if(t>=ao.A&&t<=ao.F)return t-(ao.A-10);if(t>=ao.a&&t<=ao.f)return t-(ao.a-10)}function Cd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(oB)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let o=nB(t.charCodeAt(i)),a=nB(t.charCodeAt(i+1));if(o===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}s[n]=o*16+a}return s}function aB(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Qp(t){return typeof t=="string"&&(t=aB(t)),Sn(t),t}function Cn(...t){let e=0;for(let s=0;s<t.length;s++){let n=t[s];Sn(n),e+=n.length}let r=new Uint8Array(e);for(let s=0,n=0;s<t.length;s++){let i=t[s];r.set(i,n),n+=i.length}return r}function Kx(t){let e=s=>t().update(Qp(s)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Wx(t=32){if(Sd&&typeof Sd.getRandomValues=="function")return Sd.getRandomValues(new Uint8Array(t));if(Sd&&typeof Sd.randomBytes=="function")return Uint8Array.from(Sd.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}var oB,IG,ao,Cu,Td=z(()=>{"use strict";g();sB();oB=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",IG=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ao={_0:48,_9:57,A:65,F:70,a:97,f:102};Cu=class{}});function Zp(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Ba(t,e,r=""){let s=Ed(t),n=t?.length,i=e!==void 0;if(!s||i&&n!==e){let o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function e0(t){let e=t.toString(16);return e.length&1?"0"+e:e}function cB(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Q2:BigInt("0x"+t)}function Au(t){return cB(lo(t))}function Z2(t){return Sn(t),cB(lo(Uint8Array.from(t).reverse()))}function Gx(t,e){return Cd(t.toString(16).padStart(e*2,"0"))}function eE(t,e){return Gx(t,e).reverse()}function Qr(t,e,r){let s;if(typeof e=="string")try{s=Cd(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Ed(e))s=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let n=s.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return s}function dB(t,e,r){return Y2(t)&&Y2(e)&&Y2(r)&&e<=t&&t<r}function lB(t,e,r,s){if(!dB(e,r,s))throw new Error("expected valid "+t+": "+r+" <= n < "+s+", got "+e)}function Xx(t){let e;for(e=0;t>Q2;t>>=J2,e+=1);return e}function uB(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let s=h=>new Uint8Array(h),n=h=>Uint8Array.of(h),i=s(t),o=s(t),a=0,c=()=>{i.fill(1),o.fill(0),a=0},d=(...h)=>r(o,i,...h),u=(h=s(0))=>{o=d(n(0),h),i=d(),h.length!==0&&(o=d(n(1),h),i=d())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){i=d();let v=i.slice();m.push(v),h+=i.length}return Cn(...m)};return(h,m)=>{c(),u(h);let v;for(;!(v=m(l()));)u();return c(),v}}function t0(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function s(n,i,o){let a=t[n];if(o&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([n,i])=>s(n,i,!1)),Object.entries(r).forEach(([n,i])=>s(n,i,!0))}function tE(t){let e=new WeakMap;return(r,...s)=>{let n=e.get(r);if(n!==void 0)return n;let i=t(r,...s);return e.set(r,i),i}}var Q2,J2,Y2,Da,Yx=z(()=>{"use strict";g();Td();Td();Q2=BigInt(0),J2=BigInt(1);Y2=t=>typeof t=="bigint"&&Q2<=t;Da=t=>(J2<<BigInt(t))-J2});function Tn(t,e){let r=t%e;return r>=ws?r:e+r}function fB(t,e){if(t===ws)throw new Error("invert: expected non-zero number");if(e<=ws)throw new Error("invert: expected positive modulus, got "+e);let r=Tn(t,e),s=e,n=ws,i=Zr,o=Zr,a=ws;for(;r!==ws;){let d=s/r,u=s%r,l=n-o*d,f=i-a*d;s=r,r=u,n=o,i=a,o=l,a=f}if(s!==Zr)throw new Error("invert: does not exist");return Tn(n,e)}function rE(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function bB(t,e){let r=(t.ORDER+Zr)/mB,s=t.pow(e,r);return rE(t,s,e),s}function BG(t,e){let r=(t.ORDER-gB)/yB,s=t.mul(e,Ad),n=t.pow(s,r),i=t.mul(e,n),o=t.mul(t.mul(i,Ad),n),a=t.mul(i,t.sub(o,t.ONE));return rE(t,a,e),a}function DG(t){let e=hi(t),r=wB(t),s=r(e,e.neg(e.ONE)),n=r(e,s),i=r(e,e.neg(s)),o=(t+RG)/xB;return(a,c)=>{let d=a.pow(c,o),u=a.mul(d,s),l=a.mul(d,n),f=a.mul(d,i),h=a.eql(a.sqr(u),c),m=a.eql(a.sqr(l),c);d=a.cmov(d,u,h),u=a.cmov(f,l,m);let v=a.eql(a.sqr(u),c),p=a.cmov(d,u,v);return rE(a,p,c),p}}function wB(t){if(t<pB)throw new Error("sqrt is not defined for small field");let e=t-Zr,r=0;for(;e%Ad===ws;)e/=Ad,r++;let s=Ad,n=hi(t);for(;hB(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bB;let i=n.pow(s,e),o=(e+Zr)/Ad;return function(c,d){if(c.is0(d))return d;if(hB(c,d)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,i),f=c.pow(d,e),h=c.pow(d,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,v=c.sqr(f);for(;!c.eql(v,c.ONE);)if(m++,v=c.sqr(v),m===u)throw new Error("Cannot find square root");let p=Zr<<BigInt(u-m-1),x=c.pow(l,p);u=m,l=c.sqr(x),f=c.mul(f,l),h=c.mul(h,x)}return h}}function NG(t){return t%mB===pB?bB:t%yB===gB?BG:t%xB===PG?DG(t):wB(t)}function sE(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=OG.reduce((s,n)=>(s[n]="function",s),e);return t0(t,r),t}function LG(t,e,r){if(r<ws)throw new Error("invalid exponent, negatives unsupported");if(r===ws)return t.ONE;if(r===Zr)return e;let s=t.ONE,n=e;for(;r>ws;)r&Zr&&(s=t.mul(s,n)),n=t.sqr(n),r>>=Zr;return s}function Jx(t,e,r=!1){let s=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(s[c]=o,t.mul(o,a)),t.ONE),i=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(s[c]=t.mul(o,s[c]),t.mul(o,a)),i),s}function hB(t,e){let r=(t.ORDER-Zr)/Ad,s=t.pow(e,r),n=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),o=t.eql(s,t.neg(t.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Qx(t,e){e!==void 0&&Jp(e);let r=e!==void 0?e:t.toString(2).length,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}function hi(t,e,r=!1,s={}){if(t<=ws)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,i,o=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||r)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(n=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(i=s.sqrt);let{nBitLength:c,nByteLength:d}=Qx(t,n);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:d,MASK:Da(c),ZERO:ws,ONE:Zr,allowedLengths:a,create:f=>Tn(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ws<=f&&f<t},is0:f=>f===ws,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&Zr)===Zr,neg:f=>Tn(-f,t),eql:(f,h)=>f===h,sqr:f=>Tn(f*f,t),add:(f,h)=>Tn(f+h,t),sub:(f,h)=>Tn(f-h,t),mul:(f,h)=>Tn(f*h,t),pow:(f,h)=>LG(l,f,h),div:(f,h)=>Tn(f*fB(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>fB(f,t),sqrt:i||(f=>(u||(u=NG(t)),u(l,f))),toBytes:f=>r?eE(f,d):Gx(f,d),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let v=new Uint8Array(d);v.set(f,r?0:v.length-f.length),f=v}if(f.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+f.length);let m=r?Z2(f):Au(f);if(o&&(m=Tn(m,t)),!h&&!l.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:f=>Jx(l,f),cmov:(f,h,m)=>m?h:f});return Object.freeze(l)}function vB(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function nE(t){let e=vB(t);return e+Math.ceil(e/2)}function _B(t,e,r=!1){let s=t.length,n=vB(e),i=nE(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=r?Z2(t):Au(t),a=Tn(o,e-Zr)+Zr;return r?eE(a,n):Gx(a,n)}var ws,Zr,Ad,pB,mB,gB,RG,yB,PG,xB,OG,Zx=z(()=>{"use strict";g();Yx();ws=BigInt(0),Zr=BigInt(1),Ad=BigInt(2),pB=BigInt(3),mB=BigInt(4),gB=BigInt(5),RG=BigInt(7),yB=BigInt(8),PG=BigInt(9),xB=BigInt(16);OG=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function UG(t,e,r,s){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(r>>n&i),a=Number(r&i),c=s?4:0,d=s?0:4;t.setUint32(e+c,o,s),t.setUint32(e+d,a,s)}function SB(t,e,r){return t&e^~t&r}function EB(t,e,r){return t&e^t&r^e&r}var r0,uo,Mr,jr,CB=z(()=>{"use strict";g();Td();r0=class extends Cu{constructor(e,r,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=zx(this.buffer)}update(e){Tu(this),e=Qp(e),Sn(e);let{view:r,buffer:s,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let c=zx(e);for(;n<=i-o;o+=n)this.process(c,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Tu(this),iB(e,this),this.finished=!0;let{buffer:r,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;r[o++]=128,co(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(s,0),o=0);for(let l=o;l<n;l++)r[l]=0;UG(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=zx(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,u=this.get();if(d>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)a.setUint32(4*l,u[l],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let s=e.slice(0,r);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:s,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(s),e}clone(){return this._cloneInto()}},uo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),jr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function MG(t,e=!1){return e?{h:Number(t&eb),l:Number(t>>TB&eb)}:{h:Number(t>>TB&eb)|0,l:Number(t&eb)|0}}function AB(t,e=!1){let r=t.length,s=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:o,l:a}=MG(t[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function pi(t,e,r,s){let n=(e>>>0)+(s>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}var eb,TB,iE,oE,kd,Id,s0,n0,kB,IB,RB,PB,BB,DB,NB=z(()=>{"use strict";g();eb=BigInt(4294967295),TB=BigInt(32);iE=(t,e,r)=>t>>>r,oE=(t,e,r)=>t<<32-r|e>>>r,kd=(t,e,r)=>t>>>r|e<<32-r,Id=(t,e,r)=>t<<32-r|e>>>r,s0=(t,e,r)=>t<<64-r|e>>>r-32,n0=(t,e,r)=>t>>>r-32|e<<64-r;kB=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),IB=(t,e,r,s)=>e+r+s+(t/2**32|0)|0,RB=(t,e,r,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0),PB=(t,e,r,s,n)=>e+r+s+n+(t/2**32|0)|0,BB=(t,e,r,s,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0)+(n>>>0),DB=(t,e,r,s,n,i)=>e+r+s+n+i+(t/2**32|0)|0});var FG,Na,aE,OB,HG,$G,Oa,La,tb,cE,LB,UB,MB,jB=z(()=>{"use strict";g();CB();NB();Td();FG=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]),Na=new Uint32Array(64),aE=class extends r0{constructor(e=32){super(64,e,8,!1),this.A=uo[0]|0,this.B=uo[1]|0,this.C=uo[2]|0,this.D=uo[3]|0,this.E=uo[4]|0,this.F=uo[5]|0,this.G=uo[6]|0,this.H=uo[7]|0}get(){let{A:e,B:r,C:s,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,s,n,i,o,a,c]}set(e,r,s,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=s|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)Na[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let f=Na[l-15],h=Na[l-2],m=En(f,7)^En(f,18)^f>>>3,v=En(h,17)^En(h,19)^h>>>10;Na[l]=v+Na[l-7]+m+Na[l-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:c,G:d,H:u}=this;for(let l=0;l<64;l++){let f=En(a,6)^En(a,11)^En(a,25),h=u+f+SB(a,c,d)+FG[l]+Na[l]|0,v=(En(s,2)^En(s,13)^En(s,22))+EB(s,n,i)|0;u=d,d=c,c=a,a=o+h|0,o=i,i=n,n=s,s=h+v|0}s=s+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(s,n,i,o,a,c,d,u)}roundClean(){co(Na)}destroy(){this.set(0,0,0,0,0,0,0,0),co(this.buffer)}},OB=AB(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),HG=OB[0],$G=OB[1],Oa=new Uint32Array(80),La=new Uint32Array(80),tb=class extends r0{constructor(e=64){super(128,e,16,!1),this.Ah=jr[0]|0,this.Al=jr[1]|0,this.Bh=jr[2]|0,this.Bl=jr[3]|0,this.Ch=jr[4]|0,this.Cl=jr[5]|0,this.Dh=jr[6]|0,this.Dl=jr[7]|0,this.Eh=jr[8]|0,this.El=jr[9]|0,this.Fh=jr[10]|0,this.Fl=jr[11]|0,this.Gh=jr[12]|0,this.Gl=jr[13]|0,this.Hh=jr[14]|0,this.Hl=jr[15]|0}get(){let{Ah:e,Al:r,Bh:s,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:d,El:u,Fh:l,Fl:f,Gh:h,Gl:m,Hh:v,Hl:p}=this;return[e,r,s,n,i,o,a,c,d,u,l,f,h,m,v,p]}set(e,r,s,n,i,o,a,c,d,u,l,f,h,m,v,p){this.Ah=e|0,this.Al=r|0,this.Bh=s|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=u|0,this.Fh=l|0,this.Fl=f|0,this.Gh=h|0,this.Gl=m|0,this.Hh=v|0,this.Hl=p|0}process(e,r){for(let E=0;E<16;E++,r+=4)Oa[E]=e.getUint32(r),La[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){let P=Oa[E-15]|0,j=La[E-15]|0,T=kd(P,j,1)^kd(P,j,8)^iE(P,j,7),k=Id(P,j,1)^Id(P,j,8)^oE(P,j,7),_=Oa[E-2]|0,A=La[E-2]|0,M=kd(_,A,19)^s0(_,A,61)^iE(_,A,6),V=Id(_,A,19)^n0(_,A,61)^oE(_,A,6),Y=RB(k,V,La[E-7],La[E-16]),H=PB(Y,T,M,Oa[E-7],Oa[E-16]);Oa[E]=H|0,La[E]=Y|0}let{Ah:s,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:d,Dl:u,Eh:l,El:f,Fh:h,Fl:m,Gh:v,Gl:p,Hh:x,Hl:w}=this;for(let E=0;E<80;E++){let P=kd(l,f,14)^kd(l,f,18)^s0(l,f,41),j=Id(l,f,14)^Id(l,f,18)^n0(l,f,41),T=l&h^~l&v,k=f&m^~f&p,_=BB(w,j,k,$G[E],La[E]),A=DB(_,x,P,T,HG[E],Oa[E]),M=_|0,V=kd(s,n,28)^s0(s,n,34)^s0(s,n,39),Y=Id(s,n,28)^n0(s,n,34)^n0(s,n,39),H=s&i^s&a^i&a,F=n&o^n&c^o&c;x=v|0,w=p|0,v=h|0,p=m|0,h=l|0,m=f|0,{h:l,l:f}=pi(d|0,u|0,A|0,M|0),d=a|0,u=c|0,a=i|0,c=o|0,i=s|0,o=n|0;let K=kB(M,Y,F);s=IB(K,A,V,H),n=K|0}({h:s,l:n}=pi(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=pi(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=pi(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=pi(this.Dh|0,this.Dl|0,d|0,u|0),{h:l,l:f}=pi(this.Eh|0,this.El|0,l|0,f|0),{h,l:m}=pi(this.Fh|0,this.Fl|0,h|0,m|0),{h:v,l:p}=pi(this.Gh|0,this.Gl|0,v|0,p|0),{h:x,l:w}=pi(this.Hh|0,this.Hl|0,x|0,w|0),this.set(s,n,i,o,a,c,d,u,l,f,h,m,v,p,x,w)}roundClean(){co(Oa,La)}destroy(){co(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},cE=class extends tb{constructor(){super(48),this.Ah=Mr[0]|0,this.Al=Mr[1]|0,this.Bh=Mr[2]|0,this.Bl=Mr[3]|0,this.Ch=Mr[4]|0,this.Cl=Mr[5]|0,this.Dh=Mr[6]|0,this.Dl=Mr[7]|0,this.Eh=Mr[8]|0,this.El=Mr[9]|0,this.Fh=Mr[10]|0,this.Fl=Mr[11]|0,this.Gh=Mr[12]|0,this.Gl=Mr[13]|0,this.Hh=Mr[14]|0,this.Hl=Mr[15]|0}},LB=Kx(()=>new aE),UB=Kx(()=>new tb),MB=Kx(()=>new cE)});var rb,dE,FB=z(()=>{"use strict";g();Td();rb=class extends Cu{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,qx(e);let s=Qp(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(s.length>n?e.create().update(s).digest():s);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),co(i)}update(e){return Tu(this),this.iHash.update(e),this}digestInto(e){Tu(this),Sn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:s,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},dE=(t,e,r)=>new rb(t,e).update(r).digest();dE.create=(t,e)=>new rb(t,e)});function i0(t,e){let r=e.negate();return t?r:e}function nb(t,e){let r=Jx(t.Fp,e.map(s=>s.Z));return e.map((s,n)=>t.fromAffine(s.toAffine(r[n])))}function qB(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function lE(t,e){qB(t,e);let r=Math.ceil(e/t)+1,s=2**(t-1),n=2**t,i=Da(t),o=BigInt(t);return{windows:r,windowSize:s,mask:i,maxNumber:n,shiftBy:o}}function HB(t,e,r){let{windowSize:s,mask:n,maxNumber:i,shiftBy:o}=r,a=Number(t&n),c=t>>o;a>s&&(a-=i,c+=Rd);let d=e*s,u=d+Math.abs(a)-1,l=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}}function VG(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,s)=>{if(!(r instanceof e))throw new Error("invalid point at index "+s)})}function qG(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,s)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+s)})}function fE(t){return zB.get(t)||1}function $B(t){if(t!==ku)throw new Error("invalid wNAF")}function KB(t,e,r,s){let n=e,i=t.ZERO,o=t.ZERO;for(;r>ku||s>ku;)r&Rd&&(i=i.add(n)),s&Rd&&(o=o.add(n)),n=n.double(),r>>=Rd,s>>=Rd;return{p1:i,p2:o}}function WB(t,e,r,s){VG(r,t),qG(s,e);let n=r.length,i=s.length;if(n!==i)throw new Error("arrays of points and scalars must have equal length");let o=t.ZERO,a=Xx(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=Da(c),u=new Array(Number(d)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c,f=o;for(let h=l;h>=0;h-=c){u.fill(o);for(let v=0;v<i;v++){let p=s[v],x=Number(p>>BigInt(h)&d);u[x]=u[x].add(r[v])}let m=o;for(let v=u.length-1,p=o;v>0;v--)p=p.add(u[v]),m=m.add(p);if(f=f.add(m),h!==0)for(let v=0;v<c;v++)f=f.double()}return f}function VB(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sE(e),e}else return hi(t,{isLE:r})}function GB(t,e,r={},s){if(s===void 0&&(s=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>ku))throw new Error(`CURVE.${c} must be positive bigint`)}let n=VB(e.p,r.Fp,s),i=VB(e.n,r.Fn,s),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}var ku,Rd,uE,zB,sb,XB=z(()=>{"use strict";g();Yx();Zx();ku=BigInt(0),Rd=BigInt(1);uE=new WeakMap,zB=new WeakMap;sb=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,s=this.ZERO){let n=e;for(;r>ku;)r&Rd&&(s=s.add(n)),n=n.double(),r>>=Rd;return s}precomputeWindow(e,r){let{windows:s,windowSize:n}=lE(r,this.bits),i=[],o=e,a=o;for(let c=0;c<s;c++){a=o,i.push(a);for(let d=1;d<n;d++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=lE(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:l,isNegF:f,offsetF:h}=HB(s,a,o);s=c,u?i=i.add(i0(f,r[h])):n=n.add(i0(l,r[d]))}return $B(s),{p:n,f:i}}wNAFUnsafe(e,r,s,n=this.ZERO){let i=lE(e,this.bits);for(let o=0;o<i.windows&&s!==ku;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=HB(s,o,i);if(s=a,!d){let l=r[c];n=n.add(u?l.negate():l)}}return $B(s),n}getPrecomputes(e,r,s){let n=uE.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof s=="function"&&(n=s(n)),uE.set(r,n))),n}cached(e,r,s){let n=fE(e);return this.wNAF(n,this.getPrecomputes(n,e,s),r)}unsafe(e,r,s,n){let i=fE(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),r,n)}createCache(e,r){qB(r,this.bits),zB.set(e,r),uE.delete(e)}hasCache(e){return fE(e)!==1}}});function zG(t,e,r){let[[s,n],[i,o]]=e,a=YB(o*t,r),c=YB(-n*t,r),d=t-a*s-c*i,u=-a*n-c*o,l=d<ho,f=u<ho;l&&(d=-d),f&&(u=-u);let h=Da(Math.ceil(Xx(r)/2))+Ru;if(d<ho||d>=h||u<ho||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:d,k2neg:f,k2:u}}function pE(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function hE(t,e){let r={};for(let s of Object.keys(e))r[s]=t[s]===void 0?e[s]:t[s];return Zp(r.lowS,"lowS"),Zp(r.prehash,"prehash"),r.format!==void 0&&pE(r.format),r}function Iu(t,e){let{BYTES:r}=t,s;if(typeof e=="bigint")s=e;else{let n=Qr("private key",e);try{s=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function WG(t,e={}){let r=GB("weierstrass",t,e),{Fp:s,Fn:n}=r,i=r.CURVE,{h:o,n:a}=i;t0(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!s.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=ZB(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(Y,H,F){let{x:K,y:I}=H.toAffine(),G=s.toBytes(K);if(Zp(F,"isCompressed"),F){u();let se=!s.isOdd(I);return Cn(QB(se),G)}else return Cn(Uint8Array.of(4),G,s.toBytes(I))}function f(Y){Ba(Y,void 0,"Point");let{publicKey:H,publicKeyUncompressed:F}=d,K=Y.length,I=Y[0],G=Y.subarray(1);if(K===H&&(I===2||I===3)){let se=s.fromBytes(G);if(!s.isValid(se))throw new Error("bad point: is not on curve, wrong x");let D=v(se),O;try{O=s.sqrt(D)}catch(Q){let pe=Q instanceof Error?": "+Q.message:"";throw new Error("bad point: is not on curve, sqrt error"+pe)}u();let W=s.isOdd(O);return(I&1)===1!==W&&(O=s.neg(O)),{x:se,y:O}}else if(K===F&&I===4){let se=s.BYTES,D=s.fromBytes(G.subarray(0,se)),O=s.fromBytes(G.subarray(se,se*2));if(!p(D,O))throw new Error("bad point: is not on curve");return{x:D,y:O}}else throw new Error(`bad point: got length ${K}, expected compressed=${H} or uncompressed=${F}`)}let h=e.toBytes||l,m=e.fromBytes||f;function v(Y){let H=s.sqr(Y),F=s.mul(H,Y);return s.add(s.add(F,s.mul(Y,i.a)),i.b)}function p(Y,H){let F=s.sqr(H),K=v(Y);return s.eql(F,K)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let x=s.mul(s.pow(i.a,ib),KG),w=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(x,w)))throw new Error("bad curve params: a or b");function E(Y,H,F=!1){if(!s.isValid(H)||F&&s.is0(H))throw new Error(`bad point coordinate ${Y}`);return H}function P(Y){if(!(Y instanceof A))throw new Error("ProjectivePoint expected")}function j(Y){if(!c||!c.basises)throw new Error("no endo");return zG(Y,c.basises,n.ORDER)}let T=tE((Y,H)=>{let{X:F,Y:K,Z:I}=Y;if(s.eql(I,s.ONE))return{x:F,y:K};let G=Y.is0();H==null&&(H=G?s.ONE:s.inv(I));let se=s.mul(F,H),D=s.mul(K,H),O=s.mul(I,H);if(G)return{x:s.ZERO,y:s.ZERO};if(!s.eql(O,s.ONE))throw new Error("invZ was invalid");return{x:se,y:D}}),k=tE(Y=>{if(Y.is0()){if(e.allowInfinityPoint&&!s.is0(Y.Y))return;throw new Error("bad point: ZERO")}let{x:H,y:F}=Y.toAffine();if(!s.isValid(H)||!s.isValid(F))throw new Error("bad point: x or y not field elements");if(!p(H,F))throw new Error("bad point: equation left != right");if(!Y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(Y,H,F,K,I){return F=new A(s.mul(F.X,Y),F.Y,F.Z),H=i0(K,H),F=i0(I,F),H.add(F)}class A{constructor(H,F,K){this.X=E("x",H),this.Y=E("y",F,!0),this.Z=E("z",K),Object.freeze(this)}static CURVE(){return i}static fromAffine(H){let{x:F,y:K}=H||{};if(!H||!s.isValid(F)||!s.isValid(K))throw new Error("invalid affine point");if(H instanceof A)throw new Error("projective point not allowed");return s.is0(F)&&s.is0(K)?A.ZERO:new A(F,K,s.ONE)}static fromBytes(H){let F=A.fromAffine(m(Ba(H,void 0,"point")));return F.assertValidity(),F}static fromHex(H){return A.fromBytes(Qr("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,F=!0){return V.createCache(this,H),F||this.multiply(ib),this}assertValidity(){k(this)}hasEvenY(){let{y:H}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(H)}equals(H){P(H);let{X:F,Y:K,Z:I}=this,{X:G,Y:se,Z:D}=H,O=s.eql(s.mul(F,D),s.mul(G,I)),W=s.eql(s.mul(K,D),s.mul(se,I));return O&&W}negate(){return new A(this.X,s.neg(this.Y),this.Z)}double(){let{a:H,b:F}=i,K=s.mul(F,ib),{X:I,Y:G,Z:se}=this,D=s.ZERO,O=s.ZERO,W=s.ZERO,q=s.mul(I,I),Q=s.mul(G,G),pe=s.mul(se,se),ve=s.mul(I,G);return ve=s.add(ve,ve),W=s.mul(I,se),W=s.add(W,W),D=s.mul(H,W),O=s.mul(K,pe),O=s.add(D,O),D=s.sub(Q,O),O=s.add(Q,O),O=s.mul(D,O),D=s.mul(ve,D),W=s.mul(K,W),pe=s.mul(H,pe),ve=s.sub(q,pe),ve=s.mul(H,ve),ve=s.add(ve,W),W=s.add(q,q),q=s.add(W,q),q=s.add(q,pe),q=s.mul(q,ve),O=s.add(O,q),pe=s.mul(G,se),pe=s.add(pe,pe),q=s.mul(pe,ve),D=s.sub(D,q),W=s.mul(pe,Q),W=s.add(W,W),W=s.add(W,W),new A(D,O,W)}add(H){P(H);let{X:F,Y:K,Z:I}=this,{X:G,Y:se,Z:D}=H,O=s.ZERO,W=s.ZERO,q=s.ZERO,Q=i.a,pe=s.mul(i.b,ib),ve=s.mul(F,G),at=s.mul(K,se),yt=s.mul(I,D),Dt=s.add(F,K),vt=s.add(G,se);Dt=s.mul(Dt,vt),vt=s.add(ve,at),Dt=s.sub(Dt,vt),vt=s.add(F,I);let Ot=s.add(G,D);return vt=s.mul(vt,Ot),Ot=s.add(ve,yt),vt=s.sub(vt,Ot),Ot=s.add(K,I),O=s.add(se,D),Ot=s.mul(Ot,O),O=s.add(at,yt),Ot=s.sub(Ot,O),q=s.mul(Q,vt),O=s.mul(pe,yt),q=s.add(O,q),O=s.sub(at,q),q=s.add(at,q),W=s.mul(O,q),at=s.add(ve,ve),at=s.add(at,ve),yt=s.mul(Q,yt),vt=s.mul(pe,vt),at=s.add(at,yt),yt=s.sub(ve,yt),yt=s.mul(Q,yt),vt=s.add(vt,yt),ve=s.mul(at,vt),W=s.add(W,ve),ve=s.mul(Ot,vt),O=s.mul(Dt,O),O=s.sub(O,ve),ve=s.mul(Dt,at),q=s.mul(Ot,q),q=s.add(q,ve),new A(O,W,q)}subtract(H){return this.add(H.negate())}is0(){return this.equals(A.ZERO)}multiply(H){let{endo:F}=e;if(!n.isValidNot0(H))throw new Error("invalid scalar: out of range");let K,I,G=se=>V.cached(this,se,D=>nb(A,D));if(F){let{k1neg:se,k1:D,k2neg:O,k2:W}=j(H),{p:q,f:Q}=G(D),{p:pe,f:ve}=G(W);I=Q.add(ve),K=_(F.beta,q,pe,se,O)}else{let{p:se,f:D}=G(H);K=se,I=D}return nb(A,[K,I])[0]}multiplyUnsafe(H){let{endo:F}=e,K=this;if(!n.isValid(H))throw new Error("invalid scalar: out of range");if(H===ho||K.is0())return A.ZERO;if(H===Ru)return K;if(V.hasCache(this))return this.multiply(H);if(F){let{k1neg:I,k1:G,k2neg:se,k2:D}=j(H),{p1:O,p2:W}=KB(A,K,G,D);return _(F.beta,O,W,I,se)}else return V.unsafe(K,H)}multiplyAndAddUnsafe(H,F,K){let I=this.multiplyUnsafe(F).add(H.multiplyUnsafe(K));return I.is0()?void 0:I}toAffine(H){return T(this,H)}isTorsionFree(){let{isTorsionFree:H}=e;return o===Ru?!0:H?H(A,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:H}=e;return o===Ru?this:H?H(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(H=!0){return Zp(H,"isCompressed"),this.assertValidity(),h(A,this,H)}toHex(H=!0){return lo(this.toBytes(H))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(H=!0){return this.toBytes(H)}_setWindowSize(H){this.precompute(H)}static normalizeZ(H){return nb(A,H)}static msm(H,F){return WB(A,n,H,F)}static fromPrivateKey(H){return A.BASE.multiply(Iu(n,H))}}A.BASE=new A(i.Gx,i.Gy,s.ONE),A.ZERO=new A(s.ZERO,s.ONE,s.ZERO),A.Fp=s,A.Fn=n;let M=n.BITS,V=new sb(A,e.endo?Math.ceil(M/2):M);return A.BASE.precompute(8),A}function QB(t){return Uint8Array.of(t?2:3)}function ZB(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function GG(t,e={}){let{Fn:r}=t,s=e.randomBytes||Wx,n=Object.assign(ZB(t.Fp,r),{seed:nE(r.ORDER)});function i(h){try{return!!Iu(r,h)}catch{return!1}}function o(h,m){let{publicKey:v,publicKeyUncompressed:p}=n;try{let x=h.length;return m===!0&&x!==v||m===!1&&x!==p?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=s(n.seed)){return _B(Ba(h,n.seed,"seed"),r.ORDER)}function c(h,m=!0){return t.BASE.multiply(Iu(r,h)).toBytes(m)}function d(h){let m=a(h);return{secretKey:m,publicKey:c(m)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;let{secretKey:m,publicKey:v,publicKeyUncompressed:p}=n;if(r.allowedLengths||m===v)return;let x=Qr("key",h).length;return x===v||x===p}function l(h,m,v=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");let p=Iu(r,h);return t.fromHex(m).multiply(p).toBytes(v)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Iu(r,h),precompute(h=8,m=t.BASE){return m.precompute(h,!1)}},lengths:n})}function XG(t,e,r={}){qx(e),t0(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=r.randomBytes||Wx,n=r.hmac||((F,...K)=>dE(e,F,Cn(...K))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:l,utils:f,lengths:h}=GG(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},v="compact";function p(F){let K=a>>Ru;return F>K}function x(F,K){if(!o.isValidNot0(K))throw new Error(`invalid signature ${F}: out of range 1..Point.Fn.ORDER`);return K}function w(F,K){pE(K);let I=h.signature,G=K==="compact"?I:K==="recovered"?I+1:void 0;return Ba(F,G,`${K} signature`)}class E{constructor(K,I,G){this.r=x("r",K),this.s=x("s",I),G!=null&&(this.recovery=G),Object.freeze(this)}static fromBytes(K,I=v){w(K,I);let G;if(I==="der"){let{r:W,s:q}=fo.toSig(Ba(K));return new E(W,q)}I==="recovered"&&(G=K[0],I="compact",K=K.subarray(1));let se=o.BYTES,D=K.subarray(0,se),O=K.subarray(se,se*2);return new E(o.fromBytes(D),o.fromBytes(O),G)}static fromHex(K,I){return this.fromBytes(Cd(K),I)}addRecoveryBit(K){return new E(this.r,this.s,K)}recoverPublicKey(K){let I=i.ORDER,{r:G,s:se,recovery:D}=this;if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");if(a*JB<I&&D>1)throw new Error("recovery id is ambiguous for h>1 curve");let W=D===2||D===3?G+a:G;if(!i.isValid(W))throw new Error("recovery id 2 or 3 invalid");let q=i.toBytes(W),Q=t.fromBytes(Cn(QB((D&1)===0),q)),pe=o.inv(W),ve=j(Qr("msgHash",K)),at=o.create(-ve*pe),yt=o.create(se*pe),Dt=t.BASE.multiplyUnsafe(at).add(Q.multiplyUnsafe(yt));if(Dt.is0())throw new Error("point at infinify");return Dt.assertValidity(),Dt}hasHighS(){return p(this.s)}toBytes(K=v){if(pE(K),K==="der")return Cd(fo.hexFromSig(this));let I=o.toBytes(this.r),G=o.toBytes(this.s);if(K==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Cn(Uint8Array.of(this.recovery),I,G)}return Cn(I,G)}toHex(K){return lo(this.toBytes(K))}assertValidity(){}static fromCompact(K){return E.fromBytes(Qr("sig",K),"compact")}static fromDER(K){return E.fromBytes(Qr("sig",K),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return lo(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return lo(this.toBytes("compact"))}}let P=r.bits2int||function(K){if(K.length>8192)throw new Error("input is too large");let I=Au(K),G=K.length*8-c;return G>0?I>>BigInt(G):I},j=r.bits2int_modN||function(K){return o.create(P(K))},T=Da(c);function k(F){return lB("num < 2^"+c,F,ho,T),o.toBytes(F)}function _(F,K){return Ba(F,void 0,"message"),K?Ba(e(F),void 0,"prehashed message"):F}function A(F,K,I){if(["recovered","canonical"].some(at=>at in I))throw new Error("sign() legacy options not supported");let{lowS:G,prehash:se,extraEntropy:D}=hE(I,m);F=_(F,se);let O=j(F),W=Iu(o,K),q=[k(W),k(O)];if(D!=null&&D!==!1){let at=D===!0?s(h.secretKey):D;q.push(Qr("extraEntropy",at))}let Q=Cn(...q),pe=O;function ve(at){let yt=P(at);if(!o.isValidNot0(yt))return;let Dt=o.inv(yt),vt=t.BASE.multiply(yt).toAffine(),Ot=o.create(vt.x);if(Ot===ho)return;let Ms=o.create(Dt*o.create(pe+Ot*W));if(Ms===ho)return;let js=(vt.x===Ot?0:2)|Number(vt.y&Ru),tc=Ms;return G&&p(Ms)&&(tc=o.neg(Ms),js^=1),new E(Ot,tc,js)}return{seed:Q,k2sig:ve}}function M(F,K,I={}){F=Qr("message",F);let{seed:G,k2sig:se}=A(F,K,I);return uB(e.outputLen,o.BYTES,n)(G,se)}function V(F){let K,I=typeof F=="string"||Ed(F),G=!I&&F!==null&&typeof F=="object"&&typeof F.r=="bigint"&&typeof F.s=="bigint";if(!I&&!G)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(G)K=new E(F.r,F.s);else if(I){try{K=E.fromBytes(Qr("sig",F),"der")}catch(se){if(!(se instanceof fo.Err))throw se}if(!K)try{K=E.fromBytes(Qr("sig",F),"compact")}catch{return!1}}return K||!1}function Y(F,K,I,G={}){let{lowS:se,prehash:D,format:O}=hE(G,m);if(I=Qr("publicKey",I),K=_(Qr("message",K),D),"strict"in G)throw new Error("options.strict was renamed to lowS");let W=O===void 0?V(F):E.fromBytes(Qr("sig",F),O);if(W===!1)return!1;try{let q=t.fromBytes(I);if(se&&W.hasHighS())return!1;let{r:Q,s:pe}=W,ve=j(K),at=o.inv(pe),yt=o.create(ve*at),Dt=o.create(Q*at),vt=t.BASE.multiplyUnsafe(yt).add(q.multiplyUnsafe(Dt));return vt.is0()?!1:o.create(vt.x)===Q}catch{return!1}}function H(F,K,I={}){let{prehash:G}=hE(I,m);return K=_(K,G),E.fromBytes(F,"recovered").recoverPublicKey(K).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:l,utils:f,lengths:h,Point:t,sign:M,verify:Y,recoverPublicKey:H,Signature:E,hash:e})}function YG(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,s=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,n=hi(e.n,{BITS:t.nBitLength,allowedLengths:s,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:n,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function JG(t){let{CURVE:e,curveOpts:r}=YG(t),s={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:s}}function QG(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Qx(r.Fn.ORDER,r.Fn.BITS))})}function eD(t){let{CURVE:e,curveOpts:r,hash:s,ecdsaOpts:n}=JG(t),i=WG(e,r),o=XG(i,s,n);return QG(t,o)}var YB,mE,fo,ho,Ru,JB,ib,KG,tD=z(()=>{"use strict";g();FB();Td();Yx();XB();Zx();YB=(t,e)=>(t+(t>=0?e:-e)/JB)/e;mE=class extends Error{constructor(e=""){super(e)}},fo={Err:mE,_tlv:{encode:(t,e)=>{let{Err:r}=fo;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let s=e.length/2,n=e0(s);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=s>127?e0(n.length/2|128):"";return e0(t)+i+n+e},decode(t,e){let{Err:r}=fo,s=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[s++]!==t)throw new r("tlv.decode: wrong tlv");let n=e[s++],i=!!(n&128),o=0;if(!i)o=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=e.subarray(s,s+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of d)o=o<<8|u;if(s+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(t){let{Err:e}=fo;if(t<ho)throw new e("integer: negative integers are not allowed");let r=e0(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=fo;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Au(t)}},toSig(t){let{Err:e,_int:r,_tlv:s}=fo,n=Qr("signature",t),{v:i,l:o}=s.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,i),{v:d,l:u}=s.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(t){let{_tlv:e,_int:r}=fo,s=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),i=s+n;return e.encode(48,i)}},ho=BigInt(0),Ru=BigInt(1),JB=BigInt(2),ib=BigInt(3),KG=BigInt(4)});function ob(t,e){let r=s=>eD({...t,hash:s});return{...r(e),create:r}}var rD=z(()=>{"use strict";g();tD();});var sD,nD,iD,ZG,eX,tX,oD,rTe,sTe,aD=z(()=>{"use strict";g();jB();rD();Zx();sD={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},nD={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},iD={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},ZG=hi(sD.p),eX=hi(nD.p),tX=hi(iD.p),oD=ob({...sD,Fp:ZG,lowS:!1},LB),rTe=ob({...nD,Fp:eX,lowS:!1},MB),sTe=ob({...iD,Fp:tX,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},UB)});var ab,cD=z(()=>{"use strict";g();aD();ab=oD});var lD=Ne(Ua=>{"use strict";g();Object.defineProperty(Ua,"__esModule",{value:!0});Ua.LEB128=Ua.SignedLEB128=Ua.UnsignedLEB128=void 0;var Pu;(function(t){t[t.LOWER_7=127]="LOWER_7",t[t.UPPER_1=128]="UPPER_1"})(Pu||(Pu={}));var dD=t=>Number.isSafeInteger(t),Pd=class{static decode(e,r=0){let s=this.$scanForNullBytes(e,r),n=0,i=0;for(let o=0;o<=s-r;o++){let a=e[r+o]&Pu.LOWER_7;n|=a<<i,i+=7}return n}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let r=[],s=e;do{let n=s&Pu.LOWER_7;s>>=7,s&&(n=n|Pu.UPPER_1),r.push(n)}while(s);return Uint8Array.from(r)}static check(e){if(!dD(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,r=0){let s=r,n=0;do{if(s>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");n=e.slice(s,s+1)[0],s++}while(n&Pu.UPPER_1);return s-1}static getLength(e,r=0){return this.$scanForNullBytes(e,r)-r}};Ua.UnsignedLEB128=Pd;var o0=class{static $ceil7mul(e){let r=e;for(;r%7;)r++;return r}static check(e){if(!dD(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let r=Math.ceil(Math.log2(-e));return Pd.encode((1<<this.$ceil7mul(r))+e)}static decode(e,r=0){let s=Pd.decode(e,r);return-((1<<Math.ceil(Math.log2(s)))-s)}};Ua.SignedLEB128=o0;var a0=class{};Ua.LEB128=a0;a0.encode=t=>(t>=0?Pd:o0).encode(t);a0.decode=(t,e=0,r=!1)=>(r?o0:Pd).decode(t,e)});var fD=Ne((gE,uD)=>{"use strict";g();(function(t){"use strict";function e(D){return parseInt(D)===D}function r(D){if(!e(D.length))return!1;for(var O=0;O<D.length;O++)if(!e(D[O])||D[O]<0||D[O]>255)return!1;return!0}function s(D,O){if(D.buffer&&D.name==="Uint8Array")return O&&(D.slice?D=D.slice():D=Array.prototype.slice.call(D)),D;if(Array.isArray(D)){if(!r(D))throw new Error("Array contains invalid value: "+D);return new Uint8Array(D)}if(e(D.length)&&r(D))return new Uint8Array(D);throw new Error("unsupported array-like object")}function n(D){return new Uint8Array(D)}function i(D,O,W,q,Q){(q!=null||Q!=null)&&(D.slice?D=D.slice(q,Q):D=Array.prototype.slice.call(D,q,Q)),O.set(D,W)}var o=(function(){function D(W){var q=[],Q=0;for(W=encodeURI(W);Q<W.length;){var pe=W.charCodeAt(Q++);pe===37?(q.push(parseInt(W.substr(Q,2),16)),Q+=2):q.push(pe)}return s(q)}function O(W){for(var q=[],Q=0;Q<W.length;){var pe=W[Q];pe<128?(q.push(String.fromCharCode(pe)),Q++):pe>191&&pe<224?(q.push(String.fromCharCode((pe&31)<<6|W[Q+1]&63)),Q+=2):(q.push(String.fromCharCode((pe&15)<<12|(W[Q+1]&63)<<6|W[Q+2]&63)),Q+=3)}return q.join("")}return{toBytes:D,fromBytes:O}})(),a=(function(){function D(q){for(var Q=[],pe=0;pe<q.length;pe+=2)Q.push(parseInt(q.substr(pe,2),16));return Q}var O="0123456789abcdef";function W(q){for(var Q=[],pe=0;pe<q.length;pe++){var ve=q[pe];Q.push(O[(ve&240)>>4]+O[ve&15])}return Q.join("")}return{toBytes:D,fromBytes:W}})(),c={16:10,24:12,32:14},d=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],u=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],l=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],f=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],h=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],m=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],v=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],p=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],x=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],w=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],E=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],P=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],j=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],T=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],k=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function _(D){for(var O=[],W=0;W<D.length;W+=4)O.push(D[W]<<24|D[W+1]<<16|D[W+2]<<8|D[W+3]);return O}var A=function(D){if(!(this instanceof A))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(D,!0)}),this._prepare()};A.prototype._prepare=function(){var D=c[this.key.length];if(D==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var O=0;O<=D;O++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var W=(D+1)*4,q=this.key.length/4,Q=_(this.key),pe,O=0;O<q;O++)pe=O>>2,this._Ke[pe][O%4]=Q[O],this._Kd[D-pe][O%4]=Q[O];for(var ve=0,at=q,yt;at<W;){if(yt=Q[q-1],Q[0]^=u[yt>>16&255]<<24^u[yt>>8&255]<<16^u[yt&255]<<8^u[yt>>24&255]^d[ve]<<24,ve+=1,q!=8)for(var O=1;O<q;O++)Q[O]^=Q[O-1];else{for(var O=1;O<q/2;O++)Q[O]^=Q[O-1];yt=Q[q/2-1],Q[q/2]^=u[yt&255]^u[yt>>8&255]<<8^u[yt>>16&255]<<16^u[yt>>24&255]<<24;for(var O=q/2+1;O<q;O++)Q[O]^=Q[O-1]}for(var O=0,Dt,vt;O<q&&at<W;)Dt=at>>2,vt=at%4,this._Ke[Dt][vt]=Q[O],this._Kd[D-Dt][vt]=Q[O++],at++}for(var Dt=1;Dt<D;Dt++)for(var vt=0;vt<4;vt++)yt=this._Kd[Dt][vt],this._Kd[Dt][vt]=P[yt>>24&255]^j[yt>>16&255]^T[yt>>8&255]^k[yt&255]},A.prototype.encrypt=function(D){if(D.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var O=this._Ke.length-1,W=[0,0,0,0],q=_(D),Q=0;Q<4;Q++)q[Q]^=this._Ke[0][Q];for(var pe=1;pe<O;pe++){for(var Q=0;Q<4;Q++)W[Q]=f[q[Q]>>24&255]^h[q[(Q+1)%4]>>16&255]^m[q[(Q+2)%4]>>8&255]^v[q[(Q+3)%4]&255]^this._Ke[pe][Q];q=W.slice()}for(var ve=n(16),at,Q=0;Q<4;Q++)at=this._Ke[O][Q],ve[4*Q]=(u[q[Q]>>24&255]^at>>24)&255,ve[4*Q+1]=(u[q[(Q+1)%4]>>16&255]^at>>16)&255,ve[4*Q+2]=(u[q[(Q+2)%4]>>8&255]^at>>8)&255,ve[4*Q+3]=(u[q[(Q+3)%4]&255]^at)&255;return ve},A.prototype.decrypt=function(D){if(D.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var O=this._Kd.length-1,W=[0,0,0,0],q=_(D),Q=0;Q<4;Q++)q[Q]^=this._Kd[0][Q];for(var pe=1;pe<O;pe++){for(var Q=0;Q<4;Q++)W[Q]=p[q[Q]>>24&255]^x[q[(Q+3)%4]>>16&255]^w[q[(Q+2)%4]>>8&255]^E[q[(Q+1)%4]&255]^this._Kd[pe][Q];q=W.slice()}for(var ve=n(16),at,Q=0;Q<4;Q++)at=this._Kd[O][Q],ve[4*Q]=(l[q[Q]>>24&255]^at>>24)&255,ve[4*Q+1]=(l[q[(Q+3)%4]>>16&255]^at>>16)&255,ve[4*Q+2]=(l[q[(Q+2)%4]>>8&255]^at>>8)&255,ve[4*Q+3]=(l[q[(Q+1)%4]&255]^at)&255;return ve};var M=function(D){if(!(this instanceof M))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new A(D)};M.prototype.encrypt=function(D){if(D=s(D),D.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var O=n(D.length),W=n(16),q=0;q<D.length;q+=16)i(D,W,0,q,q+16),W=this._aes.encrypt(W),i(W,O,q);return O},M.prototype.decrypt=function(D){if(D=s(D),D.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var O=n(D.length),W=n(16),q=0;q<D.length;q+=16)i(D,W,0,q,q+16),W=this._aes.decrypt(W),i(W,O,q);return O};var V=function(D,O){if(!(this instanceof V))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!O)O=n(16);else if(O.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=s(O,!0),this._aes=new A(D)};V.prototype.encrypt=function(D){if(D=s(D),D.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var O=n(D.length),W=n(16),q=0;q<D.length;q+=16){i(D,W,0,q,q+16);for(var Q=0;Q<16;Q++)W[Q]^=this._lastCipherblock[Q];this._lastCipherblock=this._aes.encrypt(W),i(this._lastCipherblock,O,q)}return O},V.prototype.decrypt=function(D){if(D=s(D),D.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var O=n(D.length),W=n(16),q=0;q<D.length;q+=16){i(D,W,0,q,q+16),W=this._aes.decrypt(W);for(var Q=0;Q<16;Q++)O[q+Q]=W[Q]^this._lastCipherblock[Q];i(D,this._lastCipherblock,0,q,q+16)}return O};var Y=function(D,O,W){if(!(this instanceof Y))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!O)O=n(16);else if(O.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");W||(W=1),this.segmentSize=W,this._shiftRegister=s(O,!0),this._aes=new A(D)};Y.prototype.encrypt=function(D){if(D.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var O=s(D,!0),W,q=0;q<O.length;q+=this.segmentSize){W=this._aes.encrypt(this._shiftRegister);for(var Q=0;Q<this.segmentSize;Q++)O[q+Q]^=W[Q];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(O,this._shiftRegister,16-this.segmentSize,q,q+this.segmentSize)}return O},Y.prototype.decrypt=function(D){if(D.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var O=s(D,!0),W,q=0;q<O.length;q+=this.segmentSize){W=this._aes.encrypt(this._shiftRegister);for(var Q=0;Q<this.segmentSize;Q++)O[q+Q]^=W[Q];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(D,this._shiftRegister,16-this.segmentSize,q,q+this.segmentSize)}return O};var H=function(D,O){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!O)O=n(16);else if(O.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=s(O,!0),this._lastPrecipherIndex=16,this._aes=new A(D)};H.prototype.encrypt=function(D){for(var O=s(D,!0),W=0;W<O.length;W++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),O[W]^=this._lastPrecipher[this._lastPrecipherIndex++];return O},H.prototype.decrypt=H.prototype.encrypt;var F=function(D){if(!(this instanceof F))throw Error("Counter must be instanitated with `new`");D!==0&&!D&&(D=1),typeof D=="number"?(this._counter=n(16),this.setValue(D)):this.setBytes(D)};F.prototype.setValue=function(D){if(typeof D!="number"||parseInt(D)!=D)throw new Error("invalid counter value (must be an integer)");if(D>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var O=15;O>=0;--O)this._counter[O]=D%256,D=parseInt(D/256)},F.prototype.setBytes=function(D){if(D=s(D,!0),D.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=D},F.prototype.increment=function(){for(var D=15;D>=0;D--)if(this._counter[D]===255)this._counter[D]=0;else{this._counter[D]++;break}};var K=function(D,O){if(!(this instanceof K))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",O instanceof F||(O=new F(O)),this._counter=O,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new A(D)};K.prototype.encrypt=function(D){for(var O=s(D,!0),W=0;W<O.length;W++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),O[W]^=this._remainingCounter[this._remainingCounterIndex++];return O},K.prototype.decrypt=K.prototype.encrypt;function I(D){D=s(D,!0);var O=16-D.length%16,W=n(D.length+O);i(D,W);for(var q=D.length;q<W.length;q++)W[q]=O;return W}function G(D){if(D=s(D,!0),D.length<16)throw new Error("PKCS#7 invalid length");var O=D[D.length-1];if(O>16)throw new Error("PKCS#7 padding byte out of range");for(var W=D.length-O,q=0;q<O;q++)if(D[W+q]!==O)throw new Error("PKCS#7 invalid padding byte");var Q=n(W);return i(D,Q,0,0,W),Q}var se={AES:A,Counter:F,ModeOfOperation:{ecb:M,cbc:V,cfb:Y,ofb:H,ctr:K},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:I,strip:G}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof gE<"u"?uD.exports=se:typeof define=="function"&&define.amd?define([],function(){return se}):(t.aesjs&&(se._aesjs=t.aesjs),t.aesjs=se)})(gE)});function mD(t,e,r){var s=e?0:4,n=e?4:0,i=e?0:3,o=e?1:2,a=e?2:1,c=e?3:0,d=e?oX:cX,u=e?aX:dX,l=m.prototype,f="is"+t,h="_"+f;return l.buffer=void 0,l.offset=0,l[h]=!0,l.toNumber=w,l.toString=E,l.toJSON=w,l.toArray=nX,Nu&&(l.toBuffer=iX),Du&&(l.toArrayBuffer=gD),m[f]=v,m;function m(T,k,_,A){return this instanceof m?p(this,T,k,_,A):new m(T,k,_,A)}function v(T){return!!(T&&T[h])}function p(T,k,_,A,M){if(Du&&cb&&(k instanceof cb&&(k=new Du(k)),A instanceof cb&&(A=new Du(A))),!k&&!_&&!A&&!Ou){T.buffer=yD(hD,0);return}if(!pD(k,_)){var V=Ou||Array;M=_,A=k,_=0,k=Ou===Nu?Nu.alloc(8):new V(8)}T.buffer=k,T.offset=_|=0,db!==typeof A&&(typeof A=="string"?x(k,_,A,M||10):pD(A,M)?yE(k,_,A,M):typeof M=="number"?(P(k,_+s,A),P(k,_+n,M)):A>0?d(k,_,A):A<0?u(k,_,A):yE(k,_,hD,0))}function x(T,k,_,A){var M=0,V=_.length,Y=0,H=0;_[0]==="-"&&M++;for(var F=M;M<V;){var K=parseInt(_[M++],A);if(!(K>=0))break;H=H*A+K,Y=Y*A+Math.floor(H/Bu),H%=Bu}F&&(Y=~Y,H?H=Bu-H:Y++),P(T,k+s,Y),P(T,k+n,H)}function w(){var T=this.buffer,k=this.offset,_=j(T,k+s),A=j(T,k+n);return r||(_|=0),_?_*Bu+A:A}function E(T){var k=this.buffer,_=this.offset,A=j(k,_+s),M=j(k,_+n),V="",Y=!r&&A&2147483648;for(Y&&(A=~A,M=Bu-M),T=T||10;;){var H=A%T*Bu+M;if(A=Math.floor(A/T),M=Math.floor(H/T),V=(H%T).toString(T)+V,!A&&!M)break}return Y&&(V="-"+V),V}function P(T,k,_){T[k+c]=_&255,_=_>>8,T[k+a]=_&255,_=_>>8,T[k+o]=_&255,_=_>>8,T[k+i]=_&255}function j(T,k){return T[k+i]*sX+(T[k+o]<<16)+(T[k+a]<<8)+T[k+c]}}function nX(t){var e=this.buffer,r=this.offset;return Ou=null,t!==!1&&rX(e)?e.length===8?e:e.slice(r,r+8):yD(e,r)}function iX(t){var e=this.buffer,r=this.offset;return Ou=Nu,t!==!1&&Nu.isBuffer(e)?e.length===8?e:e.slice(r,r+8):Nu.from(gD.call(this,t))}function gD(t){var e=this.buffer,r=this.offset,s=e.buffer;if(Ou=Du,t!==!1&&!e.offset&&s instanceof cb)return s.byteLength===8?s:s.slice(r,r+8);var n=new Du(8);return yE(n,0,e,r),n.buffer}function pD(t,e){var r=t&&t.length;return e|=0,r&&e+8<=r&&typeof t[e]!="string"}function yE(t,e,r,s){e|=0,s|=0;for(var n=0;n<8;n++)t[e++]=r[s++]&255}function yD(t,e){return Array.prototype.slice.call(t,e,e+8)}function oX(t,e,r){for(var s=e+8;s>e;)t[--s]=r&255,r/=256}function aX(t,e,r){var s=e+8;for(r++;s>e;)t[--s]=-r&255^255,r/=256}function cX(t,e,r){for(var s=e+8;e<s;)t[e++]=r&255,r/=256}function dX(t,e,r){var s=e+8;for(r++;e<s;)t[e++]=-r&255^255,r/=256}function lX(t){return!!t&&Object.prototype.toString.call(t)=="[object Array]"}var db,Nu,Du,cb,hD,rX,Bu,sX,Ou,lb,xE,ub=z(()=>{"use strict";g();db="undefined",Nu=db!==typeof Buffer&&Buffer,Du=db!==typeof Uint8Array&&Uint8Array,cb=db!==typeof ArrayBuffer&&ArrayBuffer,hD=[0,0,0,0,0,0,0,0],rX=Array.isArray||lX,Bu=4294967296,sX=16777216,lb=mD("Uint64BE",!0,!0),xE=mD("Int64BE",!0,!1)});var wE=Ne(xD=>{"use strict";g();var Ge=xD,{Buffer:fb}=require("buffer"),uX=require("os");Ge.toBuffer=function(t,e,r){r=~~r;let s;if(this.isV4Format(t))s=e||fb.alloc(r+4),t.split(/\./g).map(n=>{s[r++]=parseInt(n,10)&255});else if(this.isV6Format(t)){let n=t.split(":",8),i;for(i=0;i<n.length;i++){let o=this.isV4Format(n[i]),a;o&&(a=this.toBuffer(n[i]),n[i]=a.slice(0,2).toString("hex")),a&&++i<8&&n.splice(i,0,a.slice(2,4).toString("hex"))}if(n[0]==="")for(;n.length<8;)n.unshift("0");else if(n[n.length-1]==="")for(;n.length<8;)n.push("0");else if(n.length<8){for(i=0;i<n.length&&n[i]!=="";i++);let o=[i,1];for(i=9-n.length;i>0;i--)o.push("0");n.splice(...o)}for(s=e||fb.alloc(r+16),i=0;i<n.length;i++){let o=parseInt(n[i],16);s[r++]=o>>8&255,s[r++]=o&255}}if(!s)throw Error(`Invalid ip address: ${t}`);return s};Ge.toString=function(t,e,r){e=~~e,r=r||t.length-e;let s=[];if(r===4){for(let n=0;n<r;n++)s.push(t[e+n]);s=s.join(".")}else if(r===16){for(let n=0;n<r;n+=2)s.push(t.readUInt16BE(e+n).toString(16));s=s.join(":"),s=s.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),s=s.replace(/:{3,4}/,"::")}return s};var fX=/^(\d{1,3}\.){3,3}\d{1,3}$/,hX=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;Ge.isV4Format=function(t){return fX.test(t)};Ge.isV6Format=function(t){return hX.test(t)};function c0(t){return t===4?"ipv4":t===6?"ipv6":t?t.toLowerCase():"ipv4"}Ge.fromPrefixLen=function(t,e){t>32?e="ipv6":e=c0(e);let r=4;e==="ipv6"&&(r=16);let s=fb.alloc(r);for(let n=0,i=s.length;n<i;++n){let o=8;t<8&&(o=t),t-=o,s[n]=~(255>>o)&255}return Ge.toString(s)};Ge.mask=function(t,e){t=Ge.toBuffer(t),e=Ge.toBuffer(e);let r=fb.alloc(Math.max(t.length,e.length)),s;if(t.length===e.length)for(s=0;s<t.length;s++)r[s]=t[s]&e[s];else if(e.length===4)for(s=0;s<e.length;s++)r[s]=t[t.length-4+s]&e[s];else{for(s=0;s<r.length-6;s++)r[s]=0;for(r[10]=255,r[11]=255,s=0;s<t.length;s++)r[s+12]=t[s]&e[s+12];s+=12}for(;s<r.length;s++)r[s]=0;return Ge.toString(r)};Ge.cidr=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ge.fromPrefixLen(parseInt(e[1],10));return Ge.mask(r,s)};Ge.subnet=function(t,e){let r=Ge.toLong(Ge.mask(t,e)),s=Ge.toBuffer(e),n=0;for(let o=0;o<s.length;o++)if(s[o]===255)n+=8;else{let a=s[o]&255;for(;a;)a=a<<1&255,n++}let i=2**(32-n);return{networkAddress:Ge.fromLong(r),firstAddress:i<=2?Ge.fromLong(r):Ge.fromLong(r+1),lastAddress:i<=2?Ge.fromLong(r+i-1):Ge.fromLong(r+i-2),broadcastAddress:Ge.fromLong(r+i-1),subnetMask:e,subnetMaskLength:n,numHosts:i<=2?i:i-2,length:i,contains(o){return r===Ge.toLong(Ge.mask(o,e))}}};Ge.cidrSubnet=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ge.fromPrefixLen(parseInt(e[1],10));return Ge.subnet(r,s)};Ge.not=function(t){let e=Ge.toBuffer(t);for(let r=0;r<e.length;r++)e[r]=255^e[r];return Ge.toString(e)};Ge.or=function(t,e){if(t=Ge.toBuffer(t),e=Ge.toBuffer(e),t.length===e.length){for(let i=0;i<t.length;++i)t[i]|=e[i];return Ge.toString(t)}let r=t,s=e;e.length>t.length&&(r=e,s=t);let n=r.length-s.length;for(let i=n;i<r.length;++i)r[i]|=s[i-n];return Ge.toString(r)};Ge.isEqual=function(t,e){if(t=Ge.toBuffer(t),e=Ge.toBuffer(e),t.length===e.length){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}if(e.length===4){let s=e;e=t,t=s}for(let s=0;s<10;s++)if(e[s]!==0)return!1;let r=e.readUInt16BE(10);if(r!==0&&r!==65535)return!1;for(let s=0;s<4;s++)if(t[s]!==e[s+12])return!1;return!0};Ge.isPrivate=function(t){if(Ge.isLoopback(t))return!0;if(!Ge.isV6Format(t)){let e=Ge.normalizeToLong(t);if(e<0)throw new Error("invalid ipv4 address");t=Ge.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^f[cd][0-9a-f]{2}:/i.test(t)||/^fe80:/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ge.isPublic=function(t){return!Ge.isPrivate(t)};Ge.isLoopback=function(t){return!/\./.test(t)&&!/:/.test(t)&&(t=Ge.fromLong(Number(t))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(t)||/^0177\./.test(t)||/^0x7f\./i.test(t)||/^fe80::1$/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ge.loopback=function(t){if(t=c0(t),t!=="ipv4"&&t!=="ipv6")throw new Error("family must be ipv4 or ipv6");return t==="ipv4"?"127.0.0.1":"fe80::1"};Ge.address=function(t,e){let r=uX.networkInterfaces();if(e=c0(e),t&&t!=="private"&&t!=="public"){let n=r[t].filter(i=>c0(i.family)===e);return n.length===0?void 0:n[0].address}let s=Object.keys(r).map(n=>{let i=r[n].filter(o=>(o.family=c0(o.family),o.family!==e||Ge.isLoopback(o.address)?!1:t?t==="public"?Ge.isPrivate(o.address):Ge.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return s.length?s[0]:Ge.loopback(e)};Ge.toLong=function(t){let e=0;return t.split(".").forEach(r=>{e<<=8,e+=parseInt(r)}),e>>>0};Ge.fromLong=function(t){return`${t>>>24}.${t>>16&255}.${t>>8&255}.${t&255}`};Ge.normalizeToLong=function(t){let e=t.split(".").map(n=>n.startsWith("0x")||n.startsWith("0X")?parseInt(n,16):n.startsWith("0")&&n!=="0"&&/^[0-7]+$/.test(n)?parseInt(n,8):/^[1-9]\d*$/.test(n)||n==="0"?parseInt(n,10):NaN);if(e.some(isNaN))return-1;let r=0;switch(e.length){case 1:r=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;r=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;r=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(n=>n>255))return-1;r=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return r>>>0}});var wD=Ne((gTe,bD)=>{"use strict";g();bD.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var s,n,i;if(Array.isArray(e)){if(s=e.length,s!=r.length)return!1;for(n=s;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),s=i.length,s!==Object.keys(r).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=s;n--!==0;){var o=i[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var vD=Ne(vE=>{"use strict";g();vE.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};vE.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var _D=Ne(_E=>{"use strict";g();_E.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};_E.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var SD=Ne(SE=>{"use strict";g();SE.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};SE.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var ED=Ne(EE=>{"use strict";g();EE.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};EE.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var CD=Ne(CE=>{"use strict";g();CE.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};CE.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var kD=Ne((AD,TE)=>{"use strict";g();var TD=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=l,t.encode=u,t.familyOf=d,t.name=void 0,t.sizeOf=c,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,s=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,n=16,i={name:"v4",size:r,isFormat:f=>e.test(f),encode(f,h,m){m=~~m,h=h||new Uint8Array(m+r);let v=f.length,p=0;for(let x=0;x<v;){let w=f.charCodeAt(x++);w===46?(h[m++]=p,p=0):p=p*10+(w-48)}return h[m]=p,h},decode(f,h){return h=~~h,`${f[h++]}.${f[h++]}.${f[h++]}.${f[h]}`}};t.v4=i;let o={name:"v6",size:n,isFormat:f=>f.length>0&&s.test(f),encode(f,h,m){m=~~m;let v=m+n,p=-1,x=0,w=0,E=!0,P=!1;h=h||new Uint8Array(m+n);for(let j=0;j<f.length;j++){let T=f.charCodeAt(j);T===58?(E?p!==-1?(m<v&&(h[m]=0),m<v-1&&(h[m+1]=0),m+=2):m<v&&(p=m):(P===!0?(m<v&&(h[m]=w),m++):(m<v&&(h[m]=x>>8),m<v-1&&(h[m+1]=x&255),m+=2),x=0,w=0),E=!0,P=!1):T===46?(m<v&&(h[m]=w),m++,w=0,x=0,E=!1,P=!0):(E=!1,T>=97?T-=87:T>=65?T-=55:(T-=48,w=w*10+T),x=(x<<4)+T)}if(E===!1)P===!0?(m<v&&(h[m]=w),m++):(m<v&&(h[m]=x>>8),m<v-1&&(h[m+1]=x&255),m+=2);else if(p===0)m<v&&(h[m]=0),m<v-1&&(h[m+1]=0),m+=2;else if(p!==-1){m+=2;for(let j=Math.min(m-1,v-1);j>=p+2;j--)h[j]=h[j-2];h[p]=0,h[p+1]=0,p=m}if(p!==m&&p!==-1)for(m>v-2&&(m=v-2);v>p;)h[--v]=m<v&&m>p?h[--m]:0;else for(;m<v;)h[m++]=0;return h},decode(f,h){h=~~h;let m="";for(let v=0;v<n;v+=2)v!==0&&(m+=":"),m+=(f[h+v]<<8|f[h+v+1]).toString(16);return m.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=o;let a="ip";t.name=a;function c(f){if(i.isFormat(f))return i.size;if(o.isFormat(f))return o.size;throw Error(`Invalid ip address: ${f}`)}function d(f){return c(f)===i.size?1:2}function u(f,h,m){m=~~m;let v=c(f);return typeof h=="function"&&(h=h(m+v)),v===i.size?i.encode(f,h,m):o.encode(f,h,m)}function l(f,h,m){if(h=~~h,m=m||f.length-h,m===i.size)return i.decode(f,h,m);if(m===o.size)return o.decode(f,h,m);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return TD}):typeof TE=="object"&&typeof AD=="object"&&(TE.exports=TD)});var PD=Ne(Xe=>{"use strict";g();var Ye=require("buffer").Buffer,So=vD(),pX=_D(),mX=SD(),pb=ED(),AE=CD(),Bd=kD(),gX=0,ID=32768,kE=32768,yX=~kE,RD=32768,xX=~RD,Ae=Xe.name={};Ae.encode=function(t,e,r,{mail:s=!1}={}){e||(e=Ye.alloc(Ae.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=[];if(s){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):o.length===0&&a.length?o.push(a+"."+c):o.push(c)})}else o=i.split(".");for(let a=0;a<o.length;a++){let c=e.write(o[a],r+1);e[r]=c,r+=c+1}}return e[r++]=0,Ae.encode.bytes=r-n,e};Ae.encode.bytes=0;Ae.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let s=[],n=e,i=0,o=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let d=t.toString("utf-8",e,e+c);r&&(d=d.replace(/\./g,"\\.")),s.push(d),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=t.readUInt16BE(e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,o+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return Ae.decode.bytes=o,s.length===0?".":s.join(".")};Ae.decode.bytes=0;Ae.encodingLength=function(t){return t==="."||t===".."?1:Ye.byteLength(t.replace(/^\.|\.$/gm,""))+2};var wt={};wt.encode=function(t,e,r){e||(e=Ye.alloc(wt.encodingLength(t))),r||(r=0);let s=e.write(t,r+1);return e[r]=s,wt.encode.bytes=s+1,e};wt.encode.bytes=0;wt.decode=function(t,e){e||(e=0);let r=t[e],s=t.toString("utf-8",e+1,e+1+r);return wt.decode.bytes=r+1,s};wt.decode.bytes=0;wt.encodingLength=function(t){return Ye.byteLength(t)+1};var In={};In.encode=function(t,e,r){e||(e=In.encodingLength(t)),r||(r=0);let s=(t.flags||0)&32767,n=t.type==="response"?ID:gX;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(s|n,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};In.encode.bytes=12;In.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&ID?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:mX.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:pX.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};In.decode.bytes=12;In.encodingLength=function(){return 12};var po=Xe.unknown={};po.encode=function(t,e,r){return e||(e=Ye.alloc(po.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),po.encode.bytes=t.length+2,e};po.encode.bytes=0;po.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=t.slice(e+2,e+2+r);return po.decode.bytes=r+2,s};po.decode.bytes=0;po.encodingLength=function(t){return t.length+2};var mo=Xe.ns={};mo.encode=function(t,e,r){return e||(e=Ye.alloc(mo.encodingLength(t))),r||(r=0),Ae.encode(t,e,r+2),e.writeUInt16BE(Ae.encode.bytes,r),mo.encode.bytes=Ae.encode.bytes+2,e};mo.encode.bytes=0;mo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=Ae.decode(t,e+2);return mo.decode.bytes=r+2,s};mo.decode.bytes=0;mo.encodingLength=function(t){return Ae.encodingLength(t)+2};var go=Xe.soa={};go.encode=function(t,e,r){e||(e=Ye.alloc(go.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ae.encode(t.mname,e,r),r+=Ae.encode.bytes,Ae.encode(t.rname,e,r,{mail:!0}),r+=Ae.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-s-2,s),go.encode.bytes=r-s,e};go.encode.bytes=0;go.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mname=Ae.decode(t,e),e+=Ae.decode.bytes,s.rname=Ae.decode(t,e,{mail:!0}),e+=Ae.decode.bytes,s.serial=t.readUInt32BE(e),e+=4,s.refresh=t.readUInt32BE(e),e+=4,s.retry=t.readUInt32BE(e),e+=4,s.expire=t.readUInt32BE(e),e+=4,s.minimum=t.readUInt32BE(e),e+=4,go.decode.bytes=e-r,s};go.decode.bytes=0;go.encodingLength=function(t){return 22+Ae.encodingLength(t.mname)+Ae.encodingLength(t.rname)};var yo=Xe.txt={};yo.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let n=0;n<t.length;n++)if(typeof t[n]=="string"&&(t[n]=Ye.from(t[n])),!Ye.isBuffer(t[n]))throw new Error("Must be a Buffer");e||(e=Ye.alloc(yo.encodingLength(t))),r||(r=0);let s=r;return r+=2,t.forEach(function(n){e[r++]=n.length,n.copy(e,r,0,n.length),r+=n.length}),e.writeUInt16BE(r-s-2,s),yo.encode.bytes=r-s,e};yo.encode.bytes=0;yo.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=[];for(;s>0;){let i=t[e++];if(--s,s<i)throw new Error("Buffer overflow");n.push(t.slice(e,e+i)),e+=i,s-=i}return yo.decode.bytes=e-r,n};yo.decode.bytes=0;yo.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Ye.byteLength(r)+1:e+=r.length+1}),e};var xo=Xe.null={};xo.encode=function(t,e,r){e||(e=Ye.alloc(xo.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=Ye.from(t)),t||(t=Ye.alloc(0));let s=r;r+=2;let n=t.length;return t.copy(e,r,0,n),r+=n,e.writeUInt16BE(r-s-2,s),xo.encode.bytes=r-s,e};xo.encode.bytes=0;xo.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=t.slice(e,e+s);return e+=s,xo.decode.bytes=e-r,n};xo.decode.bytes=0;xo.encodingLength=function(t){return t?(Ye.isBuffer(t)?t.length:Ye.byteLength(t))+2:2};var bo=Xe.hinfo={};bo.encode=function(t,e,r){e||(e=Ye.alloc(bo.encodingLength(t))),r||(r=0);let s=r;return r+=2,wt.encode(t.cpu,e,r),r+=wt.encode.bytes,wt.encode(t.os,e,r),r+=wt.encode.bytes,e.writeUInt16BE(r-s-2,s),bo.encode.bytes=r-s,e};bo.encode.bytes=0;bo.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.cpu=wt.decode(t,e),e+=wt.decode.bytes,s.os=wt.decode(t,e),e+=wt.decode.bytes,bo.decode.bytes=e-r,s};bo.decode.bytes=0;bo.encodingLength=function(t){return wt.encodingLength(t.cpu)+wt.encodingLength(t.os)+2};var An=Xe.ptr={},bX=Xe.cname=An,wX=Xe.dname=An;An.encode=function(t,e,r){return e||(e=Ye.alloc(An.encodingLength(t))),r||(r=0),Ae.encode(t,e,r+2),e.writeUInt16BE(Ae.encode.bytes,r),An.encode.bytes=Ae.encode.bytes+2,e};An.encode.bytes=0;An.decode=function(t,e){e||(e=0);let r=Ae.decode(t,e+2);return An.decode.bytes=Ae.decode.bytes+2,r};An.decode.bytes=0;An.encodingLength=function(t){return Ae.encodingLength(t)+2};var wo=Xe.srv={};wo.encode=function(t,e,r){e||(e=Ye.alloc(wo.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),Ae.encode(t.target,e,r+8);let s=Ae.encode.bytes+6;return e.writeUInt16BE(s,r),wo.encode.bytes=s+2,e};wo.encode.bytes=0;wo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s={};return s.priority=t.readUInt16BE(e+2),s.weight=t.readUInt16BE(e+4),s.port=t.readUInt16BE(e+6),s.target=Ae.decode(t,e+8),wo.decode.bytes=r+2,s};wo.decode.bytes=0;wo.encodingLength=function(t){return 8+Ae.encodingLength(t.target)};var Ns=Xe.caa={};Ns.ISSUER_CRITICAL=128;Ns.encode=function(t,e,r){let s=Ns.encodingLength(t);return e||(e=Ye.alloc(Ns.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=Ns.ISSUER_CRITICAL),e.writeUInt16BE(s-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,wt.encode(t.tag,e,r),r+=wt.encode.bytes,e.write(t.value,r),r+=Ye.byteLength(t.value),Ns.encode.bytes=s,e};Ns.encode.bytes=0;Ns.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let s=e,n={};return n.flags=t.readUInt8(e),e+=1,n.tag=wt.decode(t,e),e+=wt.decode.bytes,n.value=t.toString("utf-8",e,s+r),n.issuerCritical=!!(n.flags&Ns.ISSUER_CRITICAL),Ns.decode.bytes=r+2,n};Ns.decode.bytes=0;Ns.encodingLength=function(t){return wt.encodingLength(t.tag)+wt.encodingLength(t.value)+2};var Ma=Xe.mx={};Ma.encode=function(t,e,r){e||(e=Ye.alloc(Ma.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Ae.encode(t.exchange,e,r),r+=Ae.encode.bytes,e.writeUInt16BE(r-s-2,s),Ma.encode.bytes=r-s,e};Ma.encode.bytes=0;Ma.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.preference=t.readUInt16BE(e),e+=2,s.exchange=Ae.decode(t,e),e+=Ae.decode.bytes,Ma.decode.bytes=e-r,s};Ma.encodingLength=function(t){return 4+Ae.encodingLength(t.exchange)};var vo=Xe.a={};vo.encode=function(t,e,r){return e||(e=Ye.alloc(vo.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Bd.v4.encode(t,e,r),vo.encode.bytes=6,e};vo.encode.bytes=0;vo.decode=function(t,e){e||(e=0),e+=2;let r=Bd.v4.decode(t,e);return vo.decode.bytes=6,r};vo.decode.bytes=0;vo.encodingLength=function(){return 6};var _o=Xe.aaaa={};_o.encode=function(t,e,r){return e||(e=Ye.alloc(_o.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Bd.v6.encode(t,e,r),_o.encode.bytes=18,e};_o.encode.bytes=0;_o.decode=function(t,e){e||(e=0),e+=2;let r=Bd.v6.decode(t,e);return _o.decode.bytes=18,r};_o.decode.bytes=0;_o.encodingLength=function(){return 18};var vs=Xe.option={};vs.encode=function(t,e,r){e||(e=Ye.alloc(vs.encodingLength(t))),r||(r=0);let s=r,n=AE.toCode(t.code);if(e.writeUInt16BE(n,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(n){case 8:let i=t.sourcePrefixLength||0,o=t.family||Bd.familyOf(t.ip),a=Bd.encode(t.ip,Ye.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,r),r+=2,e.writeUInt16BE(o,r),r+=2,e.writeUInt8(i,r++),e.writeUInt8(t.scopePrefixLength||0,r++),a.copy(e,r,0,c),r+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let d=t.length||0;e.writeUInt16BE(d,r),r+=2,e.fill(0,r,r+d),r+=d;break;case 14:let u=t.tags.length*2;e.writeUInt16BE(u,r),r+=2;for(let l of t.tags)e.writeUInt16BE(l,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return vs.encode.bytes=r-s,e};vs.encode.bytes=0;vs.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=AE.toString(r.code),e+=2;let s=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+s),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let n=Ye.alloc(r.family===1?4:16);t.copy(n,0,e,e+s-4),r.ip=Bd.decode(n);break;case 11:s>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let i=0;i<s;i+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return vs.decode.bytes=s+4,r};vs.decode.bytes=0;vs.encodingLength=function(t){if(t.data)return t.data.length+4;switch(AE.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var Ls=Xe.opt={};Ls.encode=function(t,e,r){e||(e=Ye.alloc(Ls.encodingLength(t))),r||(r=0);let s=r,n=Lu(t,vs);return e.writeUInt16BE(n,r),r=d0(t,vs,e,r+2),Ls.encode.bytes=r-s,e};Ls.encode.bytes=0;Ls.decode=function(t,e){e||(e=0);let r=e,s=[],n=t.readUInt16BE(e);e+=2;let i=0;for(;n>0;)s[i++]=vs.decode(t,e),e+=vs.decode.bytes,n-=vs.decode.bytes;return Ls.decode.bytes=e-r,s};Ls.decode.bytes=0;Ls.encodingLength=function(t){return 2+Lu(t||[],vs)};var ns=Xe.dnskey={};ns.PROTOCOL_DNSSEC=3;ns.ZONE_KEY=128;ns.SECURE_ENTRYPOINT=32768;ns.encode=function(t,e,r){e||(e=Ye.alloc(ns.encodingLength(t))),r||(r=0);let s=r,n=t.key;if(!Ye.isBuffer(n))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(ns.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,ns.encode.bytes=r-s,e.writeUInt16BE(ns.encode.bytes-2,s),e};ns.encode.bytes=0;ns.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);if(e+=2,s.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==ns.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,s.algorithm=t.readUInt8(e),e+=1,s.key=t.slice(e,r+n+2),e+=s.key.length,ns.decode.bytes=e-r,s};ns.decode.bytes=0;ns.encodingLength=function(t){return 6+Ye.byteLength(t.key)};var mi=Xe.rrsig={};mi.encode=function(t,e,r){e||(e=Ye.alloc(mi.encodingLength(t))),r||(r=0);let s=r,n=t.signature;if(!Ye.isBuffer(n))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(So.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,Ae.encode(t.signersName,e,r),r+=Ae.encode.bytes,n.copy(e,r,0,n.length),r+=n.length,mi.encode.bytes=r-s,e.writeUInt16BE(mi.encode.bytes-2,s),e};mi.encode.bytes=0;mi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.typeCovered=So.toString(t.readUInt16BE(e)),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.labels=t.readUInt8(e),e+=1,s.originalTTL=t.readUInt32BE(e),e+=4,s.expiration=t.readUInt32BE(e),e+=4,s.inception=t.readUInt32BE(e),e+=4,s.keyTag=t.readUInt16BE(e),e+=2,s.signersName=Ae.decode(t,e),e+=Ae.decode.bytes,s.signature=t.slice(e,r+n+2),e+=s.signature.length,mi.decode.bytes=e-r,s};mi.decode.bytes=0;mi.encodingLength=function(t){return 20+Ae.encodingLength(t.signersName)+Ye.byteLength(t.signature)};var gi=Xe.rp={};gi.encode=function(t,e,r){e||(e=Ye.alloc(gi.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ae.encode(t.mbox||".",e,r,{mail:!0}),r+=Ae.encode.bytes,Ae.encode(t.txt||".",e,r),r+=Ae.encode.bytes,gi.encode.bytes=r-s,e.writeUInt16BE(gi.encode.bytes-2,s),e};gi.encode.bytes=0;gi.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mbox=Ae.decode(t,e,{mail:!0})||".",e+=Ae.decode.bytes,s.txt=Ae.decode(t,e)||".",e+=Ae.decode.bytes,gi.decode.bytes=e-r,s};gi.decode.bytes=0;gi.encodingLength=function(t){return 2+Ae.encodingLength(t.mbox||".")+Ae.encodingLength(t.txt||".")};var Pr={};Pr.encode=function(t,e,r){e||(e=Ye.alloc(Pr.encodingLength(t))),r||(r=0);let s=r;for(var n=[],i=0;i<t.length;i++){var o=So.toType(t[i]);n[o>>8]===void 0&&(n[o>>8]=[]),n[o>>8][o>>3&31]|=1<<7-(o&7)}for(i=0;i<n.length;i++)if(n[i]!==void 0){var a=Ye.from(n[i]);e.writeUInt8(i,r),r+=1,e.writeUInt8(a.length,r),r+=1,a.copy(e,r),r+=a.length}return Pr.encode.bytes=r-s,e};Pr.encode.bytes=0;Pr.decode=function(t,e,r){e||(e=0);let s=e;for(var n=[];e-s<r;){var i=t.readUInt8(e);e+=1;var o=t.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=t.readUInt8(e+a),d=0;d<8;d++)if(c&1<<7-d){var u=So.toString(i<<8|a<<3|d);n.push(u)}e+=o}return Pr.decode.bytes=e-s,n};Pr.decode.bytes=0;Pr.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var s=So.toType(t[r]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}var n=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(n+=2+Math.ceil((e[r]+1)/8));return n};var yi=Xe.nsec={};yi.encode=function(t,e,r){e||(e=Ye.alloc(yi.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ae.encode(t.nextDomain,e,r),r+=Ae.encode.bytes,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,yi.encode.bytes=r-s,e.writeUInt16BE(yi.encode.bytes-2,s),e};yi.encode.bytes=0;yi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.nextDomain=Ae.decode(t,e),e+=Ae.decode.bytes,s.rrtypes=Pr.decode(t,e,n-(e-r)),e+=Pr.decode.bytes,yi.decode.bytes=e-r,s};yi.decode.bytes=0;yi.encodingLength=function(t){return 2+Ae.encodingLength(t.nextDomain)+Pr.encodingLength(t.rrtypes)};var xi=Xe.nsec3={};xi.encode=function(t,e,r){e||(e=Ye.alloc(xi.encodingLength(t))),r||(r=0);let s=r,n=t.salt;if(!Ye.isBuffer(n))throw new Error("salt must be a Buffer");let i=t.nextDomain;if(!Ye.isBuffer(i))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(n.length,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,xi.encode.bytes=r-s,e.writeUInt16BE(xi.encode.bytes-2,s),e};xi.encode.bytes=0;xi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);e+=2,s.algorithm=t.readUInt8(e),e+=1,s.flags=t.readUInt8(e),e+=1,s.iterations=t.readUInt16BE(e),e+=2;let i=t.readUInt8(e);e+=1,s.salt=t.slice(e,e+i),e+=i;let o=t.readUInt8(e);return e+=1,s.nextDomain=t.slice(e,e+o),e+=o,s.rrtypes=Pr.decode(t,e,n-(e-r)),e+=Pr.decode.bytes,xi.decode.bytes=e-r,s};xi.decode.bytes=0;xi.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+Pr.encodingLength(t.rrtypes)};var bi=Xe.ds={};bi.encode=function(t,e,r){e||(e=Ye.alloc(bi.encodingLength(t))),r||(r=0);let s=r,n=t.digest;if(!Ye.isBuffer(n))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,bi.encode.bytes=r-s,e.writeUInt16BE(bi.encode.bytes-2,s),e};bi.encode.bytes=0;bi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.keyTag=t.readUInt16BE(e),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.digestType=t.readUInt8(e),e+=1,s.digest=t.slice(e,r+n+2),e+=s.digest.length,bi.decode.bytes=e-r,s};bi.decode.bytes=0;bi.encodingLength=function(t){return 6+Ye.byteLength(t.digest)};var Os=Xe.sshfp={};Os.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};Os.encode=function(e,r,s){r||(r=Ye.alloc(Os.encodingLength(e))),s||(s=0);let n=s;s+=2,r[s]=e.algorithm,s+=1,r[s]=e.hash,s+=1;let i=Ye.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==Os.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(r,s),s+=i.byteLength,Os.encode.bytes=s-n,r.writeUInt16BE(Os.encode.bytes-2,n),r};Os.encode.bytes=0;Os.decode=function(e,r){r||(r=0);let s=r,n={};r+=2,n.algorithm=e[r],r+=1,n.hash=e[r],r+=1;let i=Os.getFingerprintLengthForHashType(n.hash);return n.fingerprint=e.slice(r,r+i).toString("hex").toUpperCase(),r+=i,Os.decode.bytes=r-s,n};Os.decode.bytes=0;Os.encodingLength=function(t){return 4+Ye.from(t.fingerprint,"hex").byteLength};var wi=Xe.naptr={};wi.encode=function(t,e,r){e||(e=Ye.alloc(wi.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,wt.encode(t.flags,e,r),r+=wt.encode.bytes,wt.encode(t.services,e,r),r+=wt.encode.bytes,wt.encode(t.regexp,e,r),r+=wt.encode.bytes,Ae.encode(t.replacement,e,r),r+=Ae.encode.bytes,wi.encode.bytes=r-s,e.writeUInt16BE(wi.encode.bytes-2,s),e};wi.encode.bytes=0;wi.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.order=t.readUInt16BE(e),e+=2,s.preference=t.readUInt16BE(e),e+=2,s.flags=wt.decode(t,e),e+=wt.decode.bytes,s.services=wt.decode(t,e),e+=wt.decode.bytes,s.regexp=wt.decode(t,e),e+=wt.decode.bytes,s.replacement=Ae.decode(t,e),e+=Ae.decode.bytes,wi.decode.bytes=e-r,s};wi.decode.bytes=0;wi.encodingLength=function(t){return wt.encodingLength(t.flags)+wt.encodingLength(t.services)+wt.encodingLength(t.regexp)+Ae.encodingLength(t.replacement)+6};var vi=Xe.tlsa={};vi.encode=function(t,e,r){e||(e=Ye.alloc(vi.encodingLength(t))),r||(r=0);let s=r,n=t.certificate;if(!Ye.isBuffer(n))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,vi.encode.bytes=r-s,e.writeUInt16BE(vi.encode.bytes-2,s),e};vi.encode.bytes=0;vi.decode=function(t,e){e||(e=0);let r=e,s={},n=t.readUInt16BE(e);return e+=2,s.usage=t.readUInt8(e),e+=1,s.selector=t.readUInt8(e),e+=1,s.matchingType=t.readUInt8(e),e+=1,s.certificate=t.slice(e,r+n+2),e+=s.certificate.length,vi.decode.bytes=e-r,s};vi.decode.bytes=0;vi.encodingLength=function(t){return 5+Ye.byteLength(t.certificate)};var IE=Xe.record=function(t){switch(t.toUpperCase()){case"A":return vo;case"PTR":return An;case"CNAME":return bX;case"DNAME":return wX;case"TXT":return yo;case"NULL":return xo;case"AAAA":return _o;case"SRV":return wo;case"HINFO":return bo;case"CAA":return Ns;case"NS":return mo;case"SOA":return go;case"MX":return Ma;case"OPT":return Ls;case"DNSKEY":return ns;case"RRSIG":return mi;case"RP":return gi;case"NSEC":return yi;case"NSEC3":return xi;case"SSHFP":return Os;case"DS":return bi;case"NAPTR":return wi;case"TLSA":return vi}return po},Fr=Xe.answer={};Fr.encode=function(t,e,r){e||(e=Ye.alloc(Fr.encodingLength(t))),r||(r=0);let s=r;if(Ae.encode(t.name,e,r),r+=Ae.encode.bytes,e.writeUInt16BE(So.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,Ls.encode(t.options||[],e,r),r+=Ls.encode.bytes}else{let n=pb.toClass(t.class===void 0?"IN":t.class);t.flush&&(n|=kE),e.writeUInt16BE(n,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let i=IE(t.type);i.encode(t.data,e,r),r+=i.encode.bytes}return Fr.encode.bytes=r-s,e};Fr.encode.bytes=0;Fr.decode=function(t,e){e||(e=0);let r={},s=e;if(r.name=Ae.decode(t,e),e+=Ae.decode.bytes,r.type=So.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=Ls.decode(t,e+8),e+=8+Ls.decode.bytes;else{let n=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=pb.toString(n&yX),r.flush=!!(n&kE);let i=IE(r.type);r.data=i.decode(t,e+8),e+=8+i.decode.bytes}return Fr.decode.bytes=e-s,r};Fr.decode.bytes=0;Fr.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ae.encodingLength(t.name)+8+IE(t.type).encodingLength(e)};var kn=Xe.question={};kn.encode=function(t,e,r){e||(e=Ye.alloc(kn.encodingLength(t))),r||(r=0);let s=r;return Ae.encode(t.name,e,r),r+=Ae.encode.bytes,e.writeUInt16BE(So.toType(t.type),r),r+=2,e.writeUInt16BE(pb.toClass(t.class===void 0?"IN":t.class),r),r+=2,kn.encode.bytes=r-s,t};kn.encode.bytes=0;kn.decode=function(t,e){e||(e=0);let r=e,s={};return s.name=Ae.decode(t,e),e+=Ae.decode.bytes,s.type=So.toString(t.readUInt16BE(e)),e+=2,s.class=pb.toString(t.readUInt16BE(e)),e+=2,s.class&RD&&(s.class&=xX),kn.decode.bytes=e-r,s};kn.decode.bytes=0;kn.encodingLength=function(t){return Ae.encodingLength(t.name)+4};Xe.AUTHORITATIVE_ANSWER=1024;Xe.TRUNCATED_RESPONSE=512;Xe.RECURSION_DESIRED=256;Xe.RECURSION_AVAILABLE=128;Xe.AUTHENTIC_DATA=32;Xe.CHECKING_DISABLED=16;Xe.DNSSEC_OK=32768;Xe.encode=function(t,e,r){let s=!e;s&&(e=Ye.alloc(Xe.encodingLength(t))),r||(r=0);let n=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),In.encode(t,e,r),r+=In.encode.bytes,r=d0(t.questions,kn,e,r),r=d0(t.answers,Fr,e,r),r=d0(t.authorities,Fr,e,r),r=d0(t.additionals,Fr,e,r),Xe.encode.bytes=r-n,s&&Xe.encode.bytes!==e.length?e.slice(0,Xe.encode.bytes):e};Xe.encode.bytes=0;Xe.decode=function(t,e){e||(e=0);let r=e,s=In.decode(t,e);return e+=In.decode.bytes,e=hb(s.questions,kn,t,e),e=hb(s.answers,Fr,t,e),e=hb(s.authorities,Fr,t,e),e=hb(s.additionals,Fr,t,e),Xe.decode.bytes=e-r,s};Xe.decode.bytes=0;Xe.encodingLength=function(t){return In.encodingLength(t)+Lu(t.questions||[],kn)+Lu(t.answers||[],Fr)+Lu(t.authorities||[],Fr)+Lu(t.additionals||[],Fr)};Xe.streamEncode=function(t){let e=Xe.encode(t),r=Ye.alloc(2);r.writeUInt16BE(e.byteLength);let s=Ye.concat([r,e]);return Xe.streamEncode.bytes=s.byteLength,s};Xe.streamEncode.bytes=0;Xe.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=Xe.decode(t.slice(2));return Xe.streamDecode.bytes=Xe.decode.bytes,r};Xe.streamDecode.bytes=0;function Lu(t,e){let r=0;for(let s=0;s<t.length;s++)r+=e.encodingLength(t[s]);return r}function d0(t,e,r,s){for(let n=0;n<t.length;n++)e.encode(t[n],r,s),s+=e.encode.bytes;return s}function hb(t,e,r,s){for(let n=0;n<t.length;n++)t[n]=e.decode(r,s),s+=e.decode.bytes;return s}});var ND=Ne((PTe,DD)=>{"use strict";g();var BD=TX;process.nextTick(CX,42);DD.exports=vX;function vX(t){var e=s;return r;function r(n){e(n||SX)}function s(n){var i=[n];e=o,t(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=_X(c)?s:u;i.length;)u(i.shift());function u(l){BD(EX,l,d)}}}}function _X(t){return Object.prototype.toString.call(t)==="[object Error]"}function SX(){}function EX(t,e){t.apply(null,e)}function CX(t){t===42&&(BD=process.nextTick)}function TX(t,e,r){process.nextTick(function(){t(e,r)})}});var UD=Ne((DTe,LD)=>{"use strict";g();var RE=PD(),AX=require("dgram"),kX=ND(),IX=require("events"),BE=require("os"),PE=function(){};LD.exports=function(t){t||(t={});var e=new IX.EventEmitter,r=typeof t.port=="number"?t.port:5353,s=t.type||"udp4",n=t.ip||t.host||(s==="udp4"?"224.0.0.251":null),i={address:n,port:r},o={},a=!1,c=null;if(s==="udp6"&&(!n||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=t.socket||AX.createSocket({type:s,reuseAddr:t.reuseAddr!==!1,toString:function(){return s}});d.on("error",function(l){l.code==="EACCES"||l.code==="EADDRINUSE"?e.emit("error",l):e.emit("warning",l)}),d.on("message",function(l,f){try{l=RE.decode(l)}catch(h){e.emit("warning",h);return}e.emit("packet",l,f),l.type==="query"&&e.emit("query",l,f),l.type==="response"&&e.emit("response",l,f)}),d.on("listening",function(){r||(r=i.port=d.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),d.setMulticastTTL(t.ttl||255),d.setMulticastLoopback(t.loopback!==!1))});var u=kX(function(l){if(!r||t.bind===!1)return l(null);d.once("error",l),d.bind(r,t.bind||t.interface,function(){d.removeListener("error",l),l(null)})});return u(function(l){if(l)return e.emit("error",l);e.emit("ready")}),e.send=function(l,f,h){if(typeof f=="function")return e.send(l,null,f);h||(h=PE),f?!f.host&&!f.address&&(f.address=i.address):f=i,u(m);function m(v){if(a)return h();if(v)return h(v);var p=RE.encode(l);d.send(p,0,p.length,f.port,f.address||f.host,h)}},e.response=e.respond=function(l,f,h){Array.isArray(l)&&(l={answers:l}),l.type="response",l.flags=(l.flags||0)|RE.AUTHORITATIVE_ANSWER,e.send(l,f,h)},e.query=function(l,f,h,m){if(typeof f=="function")return e.query(l,null,null,f);if(typeof f=="object"&&f&&f.port)return e.query(l,null,f,h);if(typeof h=="function")return e.query(l,f,null,h);m||(m=PE),typeof l=="string"&&(l=[{name:l,type:f||"ANY"}]),Array.isArray(l)&&(l={type:"query",questions:l}),l.type="query",e.send(l,h,m)},e.destroy=function(l){if(l||(l=PE),a)return process.nextTick(l);a=!0,clearInterval(c);for(var f in o)try{d.dropMembership(n,f)}catch{}o={},d.close(l)},e.update=function(){for(var l=t.interface?[].concat(t.interface):PX(),f=!1,h=0;h<l.length;h++){var m=l[h];if(!o[m])try{d.addMembership(n,m),o[m]=!0,f=!0}catch(v){e.emit("warning",v)}}if(f){if(d.setMulticastInterface)try{d.setMulticastInterface(t.interface||RX())}catch(v){e.emit("warning",v)}e.emit("networkInterface")}},e};function RX(){for(var t=BE.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var s=t[e[r]],n=0;n<s.length;n++){var i=s[n];if(OD(i.family)&&!i.internal)return BE.platform()==="darwin"&&e[r]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function PX(){for(var t=BE.networkInterfaces(),e=Object.keys(t),r=[],s=0;s<e.length;s++)for(var n=t[e[s]],i=0;i<n.length;i++){var o=n[i];if(OD(o.family)){r.push(o.address);break}}return r}function OD(t){return t===4||t==="IPv4"}});var LU={};ic(LU,{AV1Obu:()=>LO,AV1RtpPayload:()=>tC,AttributeKeys:()=>ZY,BitStream:()=>za,BitWriter:()=>O0,BitWriter2:()=>Qb,BufferChain:()=>OX,CONSENT_FAILURES:()=>AC,CONSENT_INTERVAL:()=>l7,COOKIE:()=>d1,Candidate:()=>Ga,CandidatePair:()=>CC,CandidatePairState:()=>u7,CipherContext:()=>j0,CipherSuite:()=>jb,CipherSuiteList:()=>nO,Connection:()=>b7,ConnectionStates:()=>DQ,CurveType:()=>cT,DEFAULT_MAX_MESSAGE_SIZE:()=>zu,DePacketizerBase:()=>TY,Directions:()=>kb,DtlsClient:()=>yC,DtlsServer:()=>ML,DtlsSocket:()=>xT,DtlsStates:()=>GJ,Event:()=>Be,EventDisposer:()=>JN,ExtensionProfiles:()=>Va,FINGERPRINT_LENGTH:()=>jL,FINGERPRINT_XOR:()=>FL,GenericNack:()=>z0,GroupDescription:()=>Xu,H264RtpPayload:()=>FO,HEADER_LENGTH:()=>To,HashAlgorithm:()=>M0,ICE_COMPLETED:()=>TC,ICE_FAILED:()=>I0,INTEGRITY_LENGTH:()=>bT,IPV4_PROTOCOL:()=>wT,IPV6_PROTOCOL:()=>vT,IceCandidate:()=>WT,IceGathererStates:()=>eQ,IceTransportStates:()=>ZJ,Inactive:()=>L7,Int:()=>$0,MediaDescription:()=>Yb,MediaStream:()=>U7,MediaStreamTrack:()=>Y0,MediaStreamTrackFactory:()=>$J,Message:()=>sn,NalUnitType:()=>$a,NamedCurveAlgorithm:()=>Ro,NamedCurveAlgorithmList:()=>aT,OpusRtpPayload:()=>$O,PacketChunk:()=>eL,PacketResult:()=>rL,PacketStatus:()=>tL,PictureLossIndication:()=>V0,Profiles:()=>wY,PromiseQueue:()=>VX,ProtectionProfileAeadAes128Gcm:()=>Kd,ProtectionProfileAes128CmHmacSha1_80:()=>nf,RETRY_MAX:()=>HL,RETRY_RTO:()=>$L,RTCCertificate:()=>KT,RTCDataChannel:()=>RT,RTCDataChannelParameters:()=>PT,RTCDtlsFingerprint:()=>Wb,RTCDtlsParameters:()=>Gb,RTCDtlsTransport:()=>DC,RTCIceCandidate:()=>eU,RTCIceGatherer:()=>Q7,RTCIceParameters:()=>GT,RTCIceTransport:()=>J7,RTCP_HEADER_SIZE:()=>$b,RTCPeerConnection:()=>IQ,RTCRtcpFeedback:()=>S7,RTCRtcpParameters:()=>wJ,RTCRtpCodecParameters:()=>Xa,RTCRtpCodingParameters:()=>C7,RTCRtpHeaderExtensionParameters:()=>ki,RTCRtpReceiver:()=>ZT,RTCRtpRtxParameters:()=>E7,RTCRtpSender:()=>PU,RTCRtpSimulcastParameters:()=>BT,RTCRtpTransceiver:()=>O7,RTCSctpCapabilities:()=>YT,RTCSctpTransport:()=>TU,RTCSessionDescription:()=>IU,RTCStatsReport:()=>N7,RTP_EXTENSION_URI:()=>Xt,ReceiverEstimatedMaxBitrate:()=>q0,RecvDelta:()=>B0,Recvonly:()=>MT,Red:()=>mT,RedEncoder:()=>_L,RedHandler:()=>SL,RedHeader:()=>hC,RtcpHeader:()=>Do,RtcpPacketConverter:()=>aL,RtcpPayloadSpecificFeedback:()=>Ju,RtcpReceiverInfo:()=>c1,RtcpRrPacket:()=>Qu,RtcpSenderInfo:()=>pT,RtcpSourceDescriptionPacket:()=>W0,RtcpSrPacket:()=>$d,RtcpTransportLayerFeedback:()=>Hd,RtpBuilder:()=>qY,RtpHeader:()=>Po,RtpPacket:()=>Bo,RtpRouter:()=>RU,RunLengthChunk:()=>Gu,SDPManager:()=>DU,Sendonly:()=>UT,Sendrecv:()=>jT,SessionDescription:()=>N0,SignalingStates:()=>BQ,SignatureAlgorithm:()=>Ai,SignatureScheme:()=>WE,SourceDescriptionChunk:()=>fT,SourceDescriptionItem:()=>hT,SrtcpSession:()=>DL,SrtpAuthenticationError:()=>Vd,SrtpContext:()=>F0,SrtpSession:()=>NL,SsrcDescription:()=>Jb,StatusVectorChunk:()=>QO,StunOverTurnProtocol:()=>ZL,StunProtocol:()=>Vb,TcpTransport:()=>rO,TransceiverManager:()=>OU,TransportWideCC:()=>K0,TurnProtocol:()=>t7,UdpTransport:()=>Mb,Vp8RtpPayload:()=>qO,Vp9RtpPayload:()=>KO,WeriftError:()=>zX,addSDPHeader:()=>XC,andDirection:()=>VT,buffer2ArrayBuffer:()=>UX,bufferArrayXor:()=>DX,bufferReader:()=>os,bufferWriter:()=>tr,bufferWriterLE:()=>FN,bufferXor:()=>BX,candidateFoundation:()=>qb,candidateFromIce:()=>tf,candidateFromSdp:()=>QT,candidatePairPriority:()=>zb,candidatePriority:()=>D0,candidateToIce:()=>Z7,candidateToSdp:()=>JT,certificateTypes:()=>iO,classes:()=>_T,codecParametersFromString:()=>em,codecParametersToString:()=>vQ,compactNtp:()=>zT,crc32:()=>KN,crc32c:()=>nT,createBufferWriter:()=>P0,createSelfSignedCertificate:()=>HJ,createStunOverTurnClient:()=>vC,createTurnClient:()=>s7,dePacketizeRtpPackets:()=>AY,debug:()=>dt,deepMerge:()=>V7,defaultOptions:()=>f7,defaultPeerConfig:()=>RQ,depacketizerCodecs:()=>kY,deserializeAbsSendTime:()=>yL,deserializeAudioLevelIndication:()=>xL,deserializeString:()=>mL,deserializeUint16BE:()=>gL,deserializeVideoOrientation:()=>bL,dumpBuffer:()=>LX,enumerate:()=>IY,findCodecByMimeType:()=>eT,findPort:()=>XN,fingerprint:()=>HT,generateStatsId:()=>Ft,getBit:()=>Ee,getDataChannelMessageSize:()=>v7,getGlobalIp:()=>mJ,getHostAddresses:()=>x7,getStatsTimestamp:()=>Ya,growBufferSize:()=>rC,int:()=>Ku,interfaceAddress:()=>e1,isDtls:()=>M7,isLinkLocalAddress:()=>y7,isMedia:()=>GO,isRtcp:()=>cL,keyLength:()=>BO,leb128decode:()=>MO,makeIntegrityKey:()=>n7,methods:()=>ST,microTime:()=>F7,milliTime:()=>qT,nodeIpAddress:()=>RC,normalizeFamilyNodeV18:()=>U0,normalizeFingerprintAlgorithm:()=>$T,normalizeFingerprintValue:()=>Kb,ntpTime:()=>H7,ntpTime2Sec:()=>oL,paddingBits:()=>NX,paddingByte:()=>L0,paddingLength:()=>bC,parseGroup:()=>Lb,parseIceServers:()=>$7,parseMessage:()=>l1,random16:()=>sT,random32:()=>Ub,randomPort:()=>oT,randomPorts:()=>qX,reverseDirection:()=>j7,reverseSimulcastDirection:()=>jJ,rtpHeaderExtensionsParser:()=>dL,saltLength:()=>DO,serializeAbsSendTime:()=>pL,serializeAudioLevelIndication:()=>OY,serializeRepairedRtpStreamId:()=>fL,serializeSdesMid:()=>lL,serializeSdesRTPStreamID:()=>uL,serializeTransportWideCC:()=>hL,serverReflexiveCandidate:()=>p7,signatures:()=>dT,sortCandidatePairs:()=>h7,supportedAudioCodecs:()=>_J,supportedCodecs:()=>LT,supportedVideoCodecs:()=>vJ,timer:()=>RY,timestampSeconds:()=>J0,uint16Add:()=>$r,uint16Gt:()=>Zb,uint16Gte:()=>$X,uint24:()=>GN,uint32Add:()=>Od,uint32Gt:()=>Ei,uint32Gte:()=>qu,uint8Add:()=>WN,unwrapRtx:()=>CL,url2Address:()=>gJ,useAV1X:()=>k7,useAbsSendTime:()=>AJ,useAudioLevelIndication:()=>IJ,useDependencyDescriptor:()=>kJ,useFIR:()=>bJ,useH264:()=>T7,useNACK:()=>cm,useOPUS:()=>NT,usePCMU:()=>OT,usePLI:()=>af,useREMB:()=>dm,useRepairedRtpStreamId:()=>CJ,useSdesMid:()=>SJ,useSdesRTPStreamId:()=>EJ,useTWCC:()=>_7,useTransportWideCC:()=>TJ,useVP8:()=>DT,useVP9:()=>A7,useVideoOrientation:()=>RJ,validateAddress:()=>IC,validateRemoteCandidate:()=>kC,wrapRtx:()=>TL});function sT(){return rT.jspack.Unpack("!H",(0,tT.randomBytes)(2))[0]}function Ub(){return rT.jspack.Unpack("!L",(0,tT.randomBytes)(4))[0]}function BX(t,e){if(t.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let r=t.length,s=Buffer.allocUnsafe(r);for(let n=0;n<r;n++)s[n]=t[n]^e[n];return s}function DX(t){let e=[...t].sort((s,n)=>s.length-n.length).reverse()[0].length,r=Buffer.allocUnsafe(e);for(let s=0;s<e;s++)r[s]=0,t.forEach(n=>{r[s]^=n[s]??0});return r}function Ee(t,e,r=1){let s=t.toString(2).split("");s=[...Array(8-s.length).fill("0"),...s];let n=s.slice(e,e+r).join("");return Number.parseInt(n,2)}function L0(t){let e=t.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function NX(t,e){let r=t.toString(2);return[...[...Array(e-r.length)].map(()=>"0"),...r].join("")}function tr(t,e){return P0(t)(e)}function P0(t,e){let r=t.reduce((n,i)=>n+i,0),s=e?Buffer.alloc(r):void 0;return n=>{let i=s||Buffer.alloc(r),o=0;return n.forEach((a,c)=>{let d=t[c];d===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,d),o+=d}),i}}function FN(t,e){let r=t.reduce((i,o)=>i+o,0),s=Buffer.alloc(r),n=0;return e.forEach((i,o)=>{let a=t[o];a===8?s.writeBigUInt64LE(i,n):s.writeUIntLE(i,n,a),n+=a}),s}function os(t,e){let r=0;return e.map(s=>{let n;return s===8?n=t.readBigUInt64BE(r):n=t.readUIntBE(r,s),r+=s,n})}function UX(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function HN(t){return typeof t!="string"}function $N(t){let e=new Array(256),r=0;for(let s=0;s<256;++s)r=s,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,e[s]=r;return new Int32Array(e)}function VN(t){let e=new Int32Array(4096),r=0,s=0,n=0;for(n=0;n<256;++n)e[n]=t[n];for(n=0;n<256;++n)for(s=t[n],r=256+n;r<4096;r+=256)s=e[r]=s>>>8^t[s&255];let i=[];for(n=1;n<16;++n)i[n-1]=e.subarray(n*256,n*256+256);return i}function qN(t,e,r){let s=e^-1,n=0,i=t.length,o=0,a=0;for(;n<i;)o=t.charCodeAt(n++),o<128?s=s>>>8^r[(s^o)&255]:o<2048?(s=s>>>8^r[(s^(192|o>>6&31))&255],s=s>>>8^r[(s^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=t.charCodeAt(n++)&1023,s=s>>>8^r[(s^(240|o>>8&7))&255],s=s>>>8^r[(s^(128|o>>2&63))&255],s=s>>>8^r[(s^(128|a>>6&15|(o&3)<<4))&255],s=s>>>8^r[(s^(128|a&63))&255]):(s=s>>>8^r[(s^(224|o>>12&15))&255],s=s>>>8^r[(s^(128|o>>6&63))&255],s=s>>>8^r[(s^(128|o&63))&255]);return~s>>>0}function zN(t,e,r,s){let[n,i,o,a,c,d,u,l,f,h,m,v,p,x,w]=s,E=e^-1,P=0,j=t.length-15;for(;P<j;)E=w[t[P++]^E&255]^x[t[P++]^E>>>8&255]^p[t[P++]^E>>>16&255]^v[t[P++]^E>>>24]^m[t[P++]]^h[t[P++]]^f[t[P++]]^l[t[P++]]^u[t[P++]]^d[t[P++]]^c[t[P++]]^a[t[P++]]^o[t[P++]]^i[t[P++]]^n[t[P++]]^r[t[P++]];for(j+=15;P<j;)E=E>>>8^r[(E^t[P++])&255];return~E>>>0}function KN(t,e=0){return HN(t)?zN(t,e,zE,FX):qN(t,e,zE)}function nT(t,e=0){return HN(t)?zN(t,e,KE,HX):qN(t,e,KE)}function WN(t,e){return t+e&255}function $r(t,e){return t+e&65535}function Od(t,e){return Number(BigInt(t)+BigInt(e)&0xffffffffn)}function GN(t){return t&16777215}function Zb(t,e){return t<e&&e-t>32768||t>e&&t-e<32768}function $X(t,e){return t===e||Zb(t,e)}function Ei(t,e){return t<e&&e-t>2147483648||t>e&&t-e<2147483648}function qu(t,e){return t===e||Ei(t,e)}async function oT(t="udp4",e){let r=(0,iT.createSocket)(t);setImmediate(()=>r.bind({port:0,address:e1(t,e)})),await new Promise(n=>{r.once("error",n),r.once("listening",n)});let s=r.address()?.port;return await new Promise(n=>r.close(()=>n())),s}async function qX(t,e="udp4",r){return Promise.all([...Array(t)].map(()=>oT(e,r)))}async function XN(t,e,r="udp4",s){let n;for(let i=t;i<=e;i++){let o=(0,iT.createSocket)(r);if(setImmediate(()=>o.bind({port:i,address:e1(r,s)})),await new Promise(c=>{o.once("error",d=>c(d)),o.once("listening",()=>c())})){await new Promise(c=>o.close(()=>c()));continue}if(n=o.address()?.port,await new Promise(c=>o.close(()=>c())),t<=n&&n<=e)break}if(!n)throw new Error("port not found");return n}function U0(t){return t==="IPv4"?4:t==="IPv6"?6:t}function cO(t,e,r){switch(r){case Ro.secp256r1_23:return WX({publicKey:t,privateKey:e});case Ro.x25519_29:return Buffer.from(aO.default.scalarMult(e,t));default:throw new Error}}function jD(t,e,r){let s=(0,r1.createHmac)(t,e);return s.update(r),s.digest()}function tm(t,e,r,s="sha256"){let n=r,i=[],o=e;do{o=jD(s,t,o);let a=jD(s,t,Buffer.concat([o,e]));i.push(a),r-=a.length}while(r>0);return Buffer.concat(i,n)}function dO(t,e,r){let s=Buffer.concat([Buffer.from("master secret"),e,r]);return tm(t,s,48)}function lO(t,e){let r=uO("sha256",e);return tm(t,Buffer.concat([Buffer.from("extended master secret"),r]),48)}function GX(t,e,r,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(t),o,a]);return tm(r,c,e)}function uO(t,e){return(0,r1.createHash)(t).update(e).digest()}function fO(t,e,r,s=12){let n=uO("sha256",e);return tm(t,Buffer.concat([Buffer.from(r),n]),s)}function XX(t,e){return fO(t,e,"client finished")}function YX(t,e){return fO(t,e,"server finished")}function JX(t,e,r,s,n,i,o="sha256"){let a=s*2+n*2,c=t,d=Buffer.concat([r,e]),u=tm(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),l=(0,oO.createDecode)(u),f=l.readBuffer(s),h=l.readBuffer(s),m=l.readBuffer(n),v=l.readBuffer(n),p=Buffer.alloc(i,0),x=Buffer.alloc(i,0);return m.copy(p,0),v.copy(x,0),{clientWriteKey:f,serverWriteKey:h,clientNonce:p,serverNonce:x}}function fY(){let t=new om;return t.id=im.RSA,t.name="RSA",t.keyType=nm.RSA,t}function hY(){let t=new om;return t.id=im.ECDHE_RSA,t.name="ECDHE_RSA",t.signType=s1.ECDHE,t.keyType=nm.RSA,t}function pY(){let t=new om;return t.id=im.ECDHE_ECDSA,t.name="ECDHE_ECDSA",t.signType=s1.ECDHE,t.keyType=nm.ECDSA,t}function mY(){let t=new om;return t.id=im.PSK,t.name="PSK",t.signType=s1.NULL,t.keyType=nm.PSK,t}function gY(){let t=new om;return t.id=im.ECDHE_PSK,t.name="ECDHE_PSK",t.signType=s1.ECDHE,t.keyType=nm.PSK,t}function vO(t){switch(t){case mr.TLS_RSA_WITH_AES_128_GCM_SHA256:return _i(mr.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",FD,l0);case mr.TLS_RSA_WITH_AES_256_GCM_SHA384:return _i(mr.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",FD,u0,"sha384");case mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return _i(mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",HD,l0);case mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return _i(mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",HD,u0,"sha384");case mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return _i(mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",$D,l0);case mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return _i(mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",$D,u0,"sha384");case mr.TLS_PSK_WITH_AES_128_GCM_SHA256:return _i(mr.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",VD,l0,"sha256");case mr.TLS_PSK_WITH_AES_256_GCM_SHA384:return _i(mr.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",VD,u0,"sha384");case mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return _i(mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",qD,l0,"sha256");case mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return _i(mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",qD,u0,"sha384");default:break}return null}function _i(t,e,r,s,n,i="sha256"){let o=new xY;return o.id=t,o.name=e,o.blockAlgorithm=r,o.kx=s,o.hashAlgorithm=i,o.keyLength=n.K_LEN,o.nonceLength=n.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function SO(t){switch(t){case Ro.secp256r1_23:{let{privateKey:e,publicKey:r}=KX();return{curve:t,privateKey:e,publicKey:r}}case Ro.x25519_29:{let e=_O.default.box.keyPair();return{curve:t,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function bY(t,e){return Buffer.from((0,RO.encode)(t,e).slice())}function MO(t){let e=0,r=0;for(let s=0;s<8;s++){let n=t.readUInt8(s);if(e|=(n&127)<<s*7,r++,!(n&128))break}return[e,r]}function AY(t,e,r){let s=n=>{let i=[];for(let c of e){let d=n.deSerialize(c.payload,r);d.fragment?(r??=Buffer.alloc(0),r=d.fragment):d.payload&&(r=void 0),i.push(d)}let o=!!i.find(c=>c.isKeyframe),a=Buffer.concat(i.map(c=>c.payload).filter(c=>c));return{isKeyframe:o,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:r}};switch(t.toUpperCase()){case"AV1":{let n=e.map(a=>tC.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=tC.getFrame(n);return{isKeyframe:i,data:o,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return s(FO);case"VP8":return s(qO);case"VP9":return s(KO);case"OPUS":return s($O);default:throw new Error}}function IY(t){return t.map((e,r)=>[r,e])}function rC(t,e){let r=Buffer.alloc(e);return t.copy(r),r}function $0(t){return Number.parseInt(t.toString(),10)}function GO(t){let e=t[0];return e>127&&e<192}function KD(t){return t%4==0?0:4-t%4}function cL(t){return t.length>=2&&t[1]>=192&&t[1]<=208}function dL(t,e){return t.map(r=>{let s=e[r.id];if(!s)return{uri:"unknown",value:r.payload};switch(s){case Xt.sdesMid:case Xt.sdesRTPStreamID:case Xt.repairedRtpStreamId:return{uri:s,value:mL(r.payload)};case Xt.transportWideCC:return{uri:s,value:gL(r.payload)};case Xt.absSendTime:return{uri:s,value:yL(r.payload)};case Xt.audioLevelIndication:return{uri:s,value:xL(r.payload)};case Xt.videoOrientation:return{uri:s,value:bL(r.payload)};default:return{uri:s,value:r.payload}}}).reduce((r,s)=>(s&&(r[s.uri]=s.value),r),{})}function lL(t){return Buffer.from(t)}function uL(t){return Buffer.from(t)}function fL(t){return Buffer.from(t)}function hL(t){return tr([2],[t])}function pL(t){let e=Buffer.alloc(3),r=t>>14n&0x00ffffffn;return e.writeUIntBE(Number(r),0,3),e}function OY(t){let e=new za(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,t),e.uint8Array}function mL(t){return t.toString()}function gL(t){return t.readUInt16BE()}function yL(t){return os(t,[3])[0]}function xL(t){let e=new za(t);return{v:e.readBits(1)===1,level:e.readBits(7)}}function bL(t){let e=new za(t);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function CL(t,e,r){return new Bo(new Po({payloadType:e,marker:t.header.marker,sequenceNumber:gT.jspack.Unpack("!H",t.payload.subarray(0,2))[0],timestamp:t.header.timestamp,ssrc:r}),t.payload.subarray(2))}function TL(t,e,r,s){return new Bo(new Po({payloadType:e,marker:t.header.marker,sequenceNumber:r,timestamp:t.header.timestamp,ssrc:s,csrc:t.header.csrc,extensions:t.header.extensions}),Buffer.concat([Buffer.from(gT.jspack.Pack("!H",[t.header.sequenceNumber])),t.payload]))}function yT(t,e,r="Failed to authenticate SRTP packet"){let s=t.length-e;G0(t.length>=QD+e,r);let n=IL(()=>Po.deSerialize(t.subarray(0,s)),r);return n.paddingSize=0,G0(n.payloadOffset>=QD&&n.payloadOffset<=s,r),n}function kL(t,e,r,s="Failed to authenticate SRTCP packet"){return G0(t.length>=MY+e+r,s),IL(()=>Do.deSerialize(t.subarray(0,$b)),s)}function G0(t,e){if(!t)throw new Vd(e)}function IL(t,e){try{return t()}catch{throw new Vd(e)}}function RL(t,e,r="Failed to authenticate SRTP packet"){if(!t.padding)return t.paddingSize=0,t;G0(e.length>t.payloadOffset,r);let s=e[e.length-1];return G0(s>0&&s<=e.length-t.payloadOffset,r),t.paddingSize=s,t}function eN(t,e,r){if(t.length!==e.length||!(0,Un.timingSafeEqual)(t,e))throw new Vd(r)}function rN(t,e){try{t.final()}catch{throw new Vd(`Failed to authenticate ${e} packet`)}}function h0(t){return(0,CT.randomBytes)(t).toString("hex").substring(0,t)}function VL(){return(0,CT.randomBytes)(12)}function Hu(t){let[e]=t,r=X0.default.isV4Format(e)?wT:vT,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(r,1),s.writeUInt16BE(t[1],2),Buffer.concat([s,X0.default.toBuffer(e)])}function eJ(t){if(t.length<4)throw new Error("STUN error code is less than 4 bytes");let e=t.readUInt8(2),r=t.readUInt8(3),s=t.slice(4).toString("utf8");return[e*100+r,s]}function $u(t){if(t.length<4)throw new Error("STUN address length is less than 4 bytes");let e=t.readUInt8(1),r=t.readUInt16BE(2),s=t.slice(4);switch(e){case wT:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[X0.default.toString(s),r];case vT:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[X0.default.toString(s),r];default:throw new Error("STUN address has unknown protocol")}}function qL(t,e){let r=[...TT,...e],s=t.slice(0,2);for(let n=2;n<t.length;n++){let i=t[n]^r[n-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),s=Buffer.concat([s,o])}return s}function Sb(t,e){return $u(qL(t,e))}function tJ(t){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(t[0]/100),2),e.writeUInt8(t[0]%100,3);let r=Buffer.from(t[1],"utf8");return Buffer.concat([e,r])}function Eb(t,e){return qL(Hu(t),e)}function l1(t,e){if(t.length<To)return;let r=t.readUint16BE(2);if(t.length!==To+r)return;let s=t.readUint16BE(0),n=Buffer.from(t.slice(To-12,To)),i=new KL;for(let a=To;a<=t.length-4;){let c=t.readUInt16BE(a),d=t.readUInt16BE(a+2),u=t.slice(a+4,a+4+d),l=4*Math.floor((d+3)/4)-d;if(Object.keys(hN).includes(c.toString())){let[,h,,m]=hN[c];if(m.name===Sb.name?i.setAttribute(h,m(u,n)):i.setAttribute(h,m(u)),h==="FINGERPRINT"){let v=WL(t.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==v)return}else if(h==="MESSAGE-INTEGRITY"&&e){let v=aJ(t.slice(0,a),e),p=i.getAttributeValue("MESSAGE-INTEGRITY");if(!v.equals(p))return}}a+=4+d+l}let o=i.getAttributes();return i.clear(),new sn(s&16111,s&272,n,o)}function WL(t){let e=AT(t,t.length-To+jL);return(KN(e)^FL)>>>0}function aJ(t,e){let r=AT(t,t.length-To+bT);return Buffer.from((0,ET.createHmac)("sha1",e).update(r).digest("hex"),"hex")}function bC(t){let e=t%4;return e===0?0:4-e}async function s7({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=lJ,o??="udp";let a=o==="udp"?await Mb.init("udp4",{portRange:n,interfaceAddresses:i}):await rO.init(t),c=new t7(t,e,r,s,a);return await c.connectionMade(),c}async function vC({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await s7({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new ZL(a)}function n7(t,e,r){return(0,JL.createHash)("md5").update(Buffer.from([t,e,r].join(":"))).digest()}function mN(t){return(t[0]&192)==64}function qb(t,e,r){let s=`${t}|${e}|${r}`;return(0,i7.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function D0(t,e=65535){let s=0;return t==="host"?s=126:t==="prflx"?s=110:t==="srflx"?s=100:s=0,(1<<24)*s+256*e+255}function kC(t){if(!["host","relay","srflx"].includes(t.type))throw new Error(`Unexpected candidate type "${t.type}"`);return t}function h7(t,e){return t.sort((r,s)=>zb(r.localCandidate,r.remoteCandidate,e)-zb(s.localCandidate,s.remoteCandidate,e)).reverse()}function zb(t,e,r){let s=r&&t.priority||e.priority,n=r&&e.priority||t.priority;return 1*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}async function p7(t,e){let r=new sn(1,0);try{let[s]=await t.request(r,e),n=t.localCandidate;if(!n)throw new Error("not exist");return new Ga(qb("srflx","udp",n.host),n.component,n.transport,D0("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){hJ("error serverReflexiveCandidate",s)}}function IC(t){return t&&Number.isNaN(t[1])?[t[0],443]:t}async function mJ(t,e){let r=new Vb;await r.connectionMade(!0,void 0,e);let s=new sn(1,0),[n]=await r.request(s,t??["stun.l.google.com",19302]);return await r.close(),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function y7(t){return U0(t.family)===4&&t.address?.startsWith("169.254.")||U0(t.family)===6&&t.address?.startsWith("fe80::")}function RC(t,{useLinkLocalAddress:e}={}){let r=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=m7.networkInterfaces();pJ(n);let i=Object.keys(n).map(o=>{for(let c of[...r,...s])if(o.startsWith(c))return{nic:o,addresses:[]};let a=n[o].filter(c=>U0(c.family)===t&&!g7.default.isLoopback(c.address)&&(e?!0:!y7(c)));return{nic:o,addresses:a.map(c=>c.address)}}).filter(o=>!!o);return i.sort((o,a)=>o.nic.localeCompare(a.nic)),Object.values(i).flatMap(o=>o.addresses)}function x7(t,e,r={}){let s=[];return t&&s.push(...RC(4,r)),e&&s.push(...RC(6,r)),s}function yN(t){return t.map((e,r)=>[r,e])}function Co(t,e){let r=t.split(e);return[r[0],r.slice(1).join(e)]}function v7(t){return Buffer.isBuffer(t)?t.length:Buffer.byteLength(t)}function SJ(){return new ki({uri:Xt.sdesMid})}function EJ(){return new ki({uri:Xt.sdesRTPStreamID})}function CJ(){return new ki({uri:Xt.repairedRtpStreamId})}function TJ(){return new ki({uri:Xt.transportWideCC})}function AJ(){return new ki({uri:Xt.absSendTime})}function kJ(){return new ki({uri:Xt.dependencyDescriptor})}function IJ(){return new ki({uri:Xt.audioLevelIndication})}function RJ(){return new ki({uri:Xt.videoOrientation})}function Ft(t,...e){let r=e.filter(s=>s!==void 0);return`${t}_${r.join("_")}`}function Ya(){return performance.now()}function HT(t,e){let r=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,R7.createHash)(e).update(t).digest("hex");return s(r(n))}function $T(t){return MJ[t.trim().toLowerCase()]}function Kb(t){return t.replace(/[^0-9a-f]/gi,"").toLowerCase()}function M7(t){let e=t[0];return e>19&&e<64}function jJ(t){return t==="recv"?"send":"recv"}function j7(t){return t==="sendonly"?"recvonly":t==="recvonly"?"sendonly":t}function $7(t){let e=a=>{if(!a)return;let[c,d]=a.split(":");return[c,Number.parseInt(d)]},r=e(t.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),s=e(t.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:n,username:i}=t.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:r,turnServer:s,turnUsername:i,turnPassword:n};return UJ("iceOptions",o),o}function tf(t){let e=new WT(t.component,t.foundation,t.host,t.port,t.priority,t.transport,t.type,t.generation,t.ufrag);return e.relatedAddress=t.relatedAddress,e.relatedPort=t.relatedPort,e.tcpType=t.tcptype,e}function Z7(t){return new Ga(t.foundation,t.component,t.protocol,t.priority,t.ip,t.port,t.type,t.relatedAddress,t.relatedPort,t.tcpType,t.generation,t.ufrag)}function um(t){let e=t%4;return e?4-e:0}function _U(t){let e=Buffer.from(""),r=Buffer.from("");return t.forEach(([s,n])=>{let i=n.length+4,o=Buffer.alloc(4);o.writeUInt16BE(s,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,r,o,n]),r=Buffer.concat([...Array(um(i))].map(()=>Buffer.from("\0")))}),e}function SU(t){let e=[],r=0;for(;r<=t.length-4;){let s=t.readUInt16BE(r),n=t.readUInt16BE(r+2);e.push([s,t.slice(r+4,r+n)]),r+=n+um(n)}return e}function nQ(t){if(t.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=t.readUInt16BE(0),r=t.readUInt16BE(2),s=t.readUInt32BE(4),n=t.readUInt32LE(8),i=nT(Buffer.concat([t.slice(0,8),Buffer.from("\0\0\0\0"),t.slice(12)]));if(n!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=t.length;){let c=t.readUInt8(a),d=t.readUInt8(a+1),u=t.readUInt16BE(a+2),l=t.slice(a+4,a+u),f=sQ[c.toString()];if(f)o.push(new f(d,l));else throw new Error("unknown");a+=u+um(u)}return[e,r,s,o]}function iQ(t,e,r,s){let n=Buffer.alloc(8);n.writeUInt16BE(t,0),n.writeUInt16BE(e,2),n.writeUInt32BE(r,4);let i=s.bytes,o=nT(Buffer.concat([n,Buffer.from("\0\0\0\0"),i])),a=Buffer.alloc(4);return a.writeUInt32LE(o,0),Buffer.concat([n,a,i])}function oQ(t){return t.map((e,r)=>[r,e])}function aQ(t){return t.reduce((e,r)=>(e[r]=new Be,e),{})}function Dd(t){return(t-1)%Xb}function Vu(t){return(t+1)%Xb}function $E(t){let e=t.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function GC(t){return`IN IP${(0,K7.isIPv4)(t)?4:6} ${t}`}function JT(t){let e=`${t.foundation} ${t.component} ${t.protocol} ${t.priority} ${t.ip} ${t.port} typ ${t.type}`;return t.relatedAddress!=null&&(e+=` raddr ${t.relatedAddress}`),t.relatedPort!=null&&(e+=` rport ${t.relatedPort}`),t.tcpType!=null&&(e+=` tcptype ${t.tcpType}`),t.generation!=null&&(e+=` generation ${t.generation}`),t.ufrag!=null&&(e+=` ufrag ${t.ufrag}`),e}function wQ(t){let e=[],r=[],s=t.split(`\r
131
+ `);return s.length===1&&(s=t.split(`
132
+ `)),s.forEach(n=>{n.startsWith("m=")?r.push([n]):r.length>0?r[r.length-1].push(n):e.push(n)}),[e,r]}function VE(t){if(t.includes(":")){let e=Co(t.slice(2),":");return[e[0],e[1]]}else return[t.slice(2),void 0]}function Lb(t,e,r=s=>s.toString()){let s=e.split(" ");s.length>0&&t.push(new Xu(s[0],s.slice(1).map(r)))}function QT(t){let e=Ga.fromSdp(t);return tf(e)}function XC(t,e){let s=new lb((0,z7.randomBytes)(64)).toString().slice(0,8),n=0;e.origin=`- ${s} ${n} IN IP4 0.0.0.0`,e.msidSemantic.push(new Xu("WMS",["*"])),e.type=t}function em(t){let e={};return t.split(";").forEach(r=>{if(r.includes("=")){let[s,n]=Co(r,"=");OJ.includes(s)?e[s]=Number(n):e[s]=n}else if(r.includes(":")){let[s,n]=r.split(":");e[s]=Number.isNaN(Number(n))?n:Number(n)}else e[r]=void 0}),e}function vQ(t,e="="){let r=Object.entries(t).map(([s,n])=>n?`${s}${e}${n}`:s);if(r.length>0)return r.join(";")}function NU(){return{codecs:{audio:[NT(),OT()],video:[DT()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:zu}}var tT,rT,iT,YN,QN,ZN,eO,rf,t1,Wu,r1,oO,aO,Hr,Nn,pO,gO,Ld,xO,Ao,n1,_O,Md,Ka,jd,sf,Wa,Fd,On,Ln,a1,Dn,RO,NO,gT,wb,vb,Un,Zu,qd,Nd,LL,Ti,Ci,zd,UL,ET,CT,X0,JL,wC,QL,i7,_C,a7,SC,EC,Cb,c7,d7,m7,g7,w7,I7,Tb,R7,P7,PC,B7,FT,q7,z7,K7,Q0,W7,G7,Y7,tU,Ib,Z0,Rb,ko,YC,JC,QC,ZC,BU,O0,Qb,OX,LX,za,MX,jX,zE,FX,KE,HX,Ku,VX,e1,zX,dt,Be,JN,MD,Mb,rO,Ai,M0,jb,nO,Ro,aT,cT,WE,iO,dT,KX,WX,Io,QX,GE,j0,F0,lT,hO,nn,Fb,ZX,mO,eY,H0,tY,rY,XE,sY,nY,iY,oY,uT,Ud,yO,aY,bO,wO,rm,JE,cY,DE,sm,dY,lY,uY,s1,nm,im,om,yY,xY,mr,l0,u0,FD,HD,$D,VD,qD,i1,o1,Yu,Hb,EO,CO,TO,ZE,AO,kO,IO,PO,nf,Kd,wY,BO,DO,vY,tC,LO,jO,_Y,FO,$a,SY,EY,CY,$O,qO,KO,TY,kY,RY,$b,Do,zD,V0,q0,PY,Ju,Qu,c1,YO,z0,BY,K0,Gu,QO,B0,eL,tL,rL,DY,Hd,W0,fT,hT,$d,pT,oL,NY,aL,Xt,LY,mT,hC,_L,UY,SL,Va,WD,GD,XD,YD,JD,Po,Bo,AL,Vd,QD,MY,jY,ZD,FY,NE,tN,PL,f0,sN,HY,$Y,BL,DL,VY,NL,qY,is,zY,of,OL,KY,nN,WY,mC,gC,iN,oN,OE,GY,XY,aN,cN,xT,LE,yC,Si,YY,dN,JY,ef,QY,am,Uu,ML,d1,jL,FL,To,bT,wT,vT,HL,$L,ZY,_T,ST,lN,xC,TT,p0,m0,rJ,sJ,uN,fN,UE,ME,jE,FE,nJ,iJ,zL,KL,hN,oJ,sn,AT,GL,XL,cJ,HE,kT,pN,Vb,_s,dJ,lJ,uJ,ZL,t7,Ga,fJ,hJ,CC,TC,I0,l7,AC,u7,f7,pJ,gJ,Ut,b7,yJ,gN,IT,xJ,RT,PT,bJ,cm,af,dm,_7,Xa,ki,wJ,S7,E7,C7,BT,T7,DT,A7,k7,NT,OT,LT,vJ,_J,xN,bN,PJ,mb,wN,vN,BJ,DJ,NJ,_N,BC,SN,OJ,D7,EN,Ab,LJ,N7,O7,L7,UT,MT,jT,kb,Y0,U7,UJ,MJ,VT,qT,FJ,F7,J0,H7,zT,HJ,$J,V7,VJ,CN,qJ,zJ,KJ,WJ,Rn,DC,GJ,KT,Wb,Gb,XJ,YJ,JJ,QJ,TN,AN,J7,ZJ,eQ,Q7,eU,WT,GT,Ii,XT,Pb,NC,tQ,Bb,Db,OC,LC,lm,UC,Nb,jC,fU,FC,HC,gU,xU,wU,rQ,sQ,$C,EU,gb,Ob,kN,Nt,cQ,dQ,IN,Pn,R0,CU,KC,RN,lQ,PN,BN,DN,uQ,fQ,Xb,hQ,pQ,NN,ON,LN,UN,mQ,gQ,yQ,xQ,Mu,zu,TU,YT,bQ,N0,Yb,Xu,IU,Jb,yb,ZT,g0,RU,_Q,ju,SQ,EQ,qE,MN,jN,PU,CQ,TQ,DU,y0,AQ,kQ,Bn,IQ,eT,RQ,PQ,OU,BQ,DQ,UU=z(()=>{"use strict";g();tT=require("crypto"),rT=Fe(Wo(),1),iT=require("dgram"),YN=Fe(m3(),1),QN=require("dgram"),ZN=Fe(require("net"),1),eO=require("net"),rf=require("crypto"),t1=Fe(Fv(),1);CP();Wu=Fe(er(),1),r1=require("crypto"),oO=Fe(er(),1),aO=Fe(Hg(),1);cD();Hr=Fe(er(),1),Nn=Fe(er(),1),pO=Fe(er(),1),gO=require("crypto"),Ld=Fe(er(),1),xO=require("timers/promises"),Ao=Fe(er(),1),n1=require("crypto"),_O=Fe(Hg(),1),Md=Fe(er(),1),Ka=Fe(er(),1),jd=Fe(er(),1),sf=Fe(er(),1),Wa=Fe(er(),1),Fd=Fe(er(),1),On=Fe(er(),1),Ln=Fe(er(),1),a1=Fe(er(),1),Dn=Fe(er(),1),RO=Fe(er(),1),NO=Fe(lD(),1),gT=Fe(Wo(),1),wb=require("crypto"),vb=Fe(fD(),1),Un=require("crypto"),Zu=require("crypto"),qd=Fe(er(),1),Nd=Fe(er(),1),LL=require("timers/promises"),Ti=Fe(er(),1),Ci=Fe(er(),1),zd=Fe(er(),1),UL=require("crypto"),ET=require("crypto"),CT=require("crypto");ub();X0=Fe(wE(),1),JL=require("crypto"),wC=Fe(Wo(),1),QL=require("timers/promises"),i7=require("crypto"),_C=require("net"),a7=require("crypto"),SC=require("net");ub();EC=Fe(require("timers/promises"),1),Cb=Fe(wD(),1),c7=Fe(UD(),1),d7=require("crypto"),m7=Fe(require("os"),1),g7=Fe(wE(),1),w7=require("events"),I7=require("crypto"),Tb=require("timers/promises"),R7=require("crypto"),P7=require("dgram"),PC=require("perf_hooks"),B7=require("crypto"),FT=require("crypto"),q7=require("timers/promises"),z7=require("crypto"),K7=require("net");ub();Q0=Fe(Fv(),1),W7=require("crypto"),G7=require("timers/promises"),Y7=require("crypto"),tU=require("crypto"),Ib=Fe(Wo(),1),Z0=require("crypto"),Rb=Fe(Wo(),1),ko=Fe(Wo(),1),YC=require("crypto"),JC=Fe(Wo(),1),QC=require("crypto"),ZC=require("timers/promises"),BU=require("crypto");O0=class{constructor(t){this.bitLength=t}value=0;set(t,e,r){return r&=(1<<t)-1,this.value|=r<<this.bitLength-t-e,this}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}},Qb=class{constructor(t){if(this.bitLength=t,t>32)throw new Error}_value=0n;offset=0n;set(t,e=1){let r=BigInt(t),s=BigInt(e);return r&=(1n<<s)-1n,this._value|=r<<BigInt(this.bitLength)-s-this.offset,this.offset+=s,this}get value(){return Number(this._value)}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}};OX=class{buffer;constructor(t){this.buffer=Buffer.alloc(t)}writeInt16BE(t,e){return this.buffer.writeInt16BE(t,e),this}writeUInt8(t,e){return this.buffer.writeUInt8(t,e),this}},LX=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");za=class{constructor(t){this.uint8Array=t}position=0;bitsPending=0;writeBits(t,e){if(t==0)return this;e&=4294967295>>>32-t;let r;return this.bitsPending>0?this.bitsPending>t?(this.uint8Array[this.position-1]|=e<<this.bitsPending-t,r=t,this.bitsPending-=t):this.bitsPending==t?(this.uint8Array[this.position-1]|=e,r=t,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>t-this.bitsPending,r=this.bitsPending,this.bitsPending=0):(r=Math.min(8,t),this.bitsPending=8-r,this.uint8Array[this.position++]=e>>t-r<<this.bitsPending),t-=r,t>0&&this.writeBits(t,e),this}readBits(t){return this._readBits(t)}_readBits(t,e){if(typeof e>"u"&&(e=0),t==0)return e;let r,s;if(this.bitsPending>0){let n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;s=Math.min(this.bitsPending,t),this.bitsPending-=s,r=n>>this.bitsPending}else s=Math.min(8,t),this.bitsPending=8-s,r=this.uint8Array[this.position++]>>this.bitsPending;return t-=s,e=e<<s|r,t>0?this._readBits(t,e):e}seekTo(t){this.position=t/8|0,this.bitsPending=t%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},MX=3988292384,jX=2197175160;zE=$N(MX),FX=VN(zE),KE=$N(jX),HX=VN(KE);Ku=t=>Number.parseInt(t,10),VX=class{queue=[];running=!1;push=t=>new Promise((e,r)=>{this.queue.push({promise:t,done:e,failed:r}),this.running||this.run()});async run(){let t=this.queue.shift();if(t){this.running=!0;try{let e=await t.promise();t.done(e)}catch(e){t.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},e1=(t,e)=>e?e[t]:void 0;zX=class extends Error{message;payload;path;constructor(t){super(t.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},dt=YN.default.debug,Be=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=t=>{};execute=(...t)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...t);(async()=>{for(let e of this.event.promiseStack)await e.execute(...t)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let t of this.event.stack)t.complete&&t.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=t=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(t);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(t,e,r)=>{let s=this.event.eventId;this.event.stack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};pipe(t){this.subscribe((...e)=>{t.execute(...e)})}queuingSubscribe=(t,e,r)=>{if(this.ended)throw new Error("event completed");let s=this.event.eventId;this.event.promiseStack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};once=(t,e,r)=>{let s=this.subscribe((...n)=>{s.unSubscribe(),t(...n)},e,r)};watch=(t,e)=>new Promise((r,s)=>{let n=e&&setTimeout(()=>{s("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{t(...o)&&(n&&clearTimeout(n),i(),r(o))})});asPromise=t=>new Promise((e,r)=>{let s=t&&setTimeout(()=>{r("Event asPromise timeout")},t);this.once((...n)=>{s&&clearTimeout(s),e(n)},()=>{s&&clearTimeout(s),e([])},n=>{s&&clearTimeout(s),r(n)})});get returnTrigger(){let{execute:t,error:e,complete:r}=this;return{execute:t,error:e,complete:r}}get returnListener(){let{subscribe:t,once:e,asPromise:r}=this;return{subscribe:t,once:e,asPromise:r}}get length(){return this.event.stack.length}},JN=class{_disposer=[];push(t){this._disposer.push(t)}dispose(){this._disposer.forEach(t=>t()),this._disposer=[]}},MD=dt("werift-ice:packages/ice/src/transport.ts"),Mb=class tO{constructor(e,r={}){this.socketType=e,this.options=r,this.socket=(0,QN.createSocket)(e),this.socket.on("message",(s,n)=>{U0(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){MD("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,r={}){let s=new tO(e,r);return await s.init(),s}async init(){let e=e1(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let r=await XN(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:r,address:e})}else this.socket.bind({address:e});await new Promise(r=>this.socket.once("listening",r))}send=async(e,r)=>{if(r&&!ZN.isIP(r[0]))return new Promise((s,n)=>{this.socket.send(e,r[1],r[0],i=>{i?(MD("send error",r,e),n(i)):s()})});r=r??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,r[1],r[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},rO=class sO{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,r)=>{try{this.client=(0,eO.connect)({port:this.addr[1],host:this.addr[0]},e)}catch(s){r(s)}}),this.client.on("data",e=>{let r=[this.client.remoteAddress,this.client.remotePort];this.onData(e,r)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{console.log("error",e)}))}async init(){await this.connecting}static async init(e){let r=new sO(e);return await r.init(),r}get address(){return{}}send=async(e,r)=>{await this.connecting,this.client.write(e,s=>{s&&console.log("err",s)})};close=async()=>{this.closed=!0,this.client.destroy()}},Ai={rsa_1:1,ecdsa_3:3},M0={sha256_4:4},jb={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},nO=Object.values(jb),Ro={x25519_29:29,secp256r1_23:23},aT=Object.values(Ro),cT={named_curve_3:3},WE={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},iO=[1,64],dT=[{hash:M0.sha256_4,signature:Ai.rsa_1},{hash:M0.sha256_4,signature:Ai.ecdsa_3}],KX=()=>{let t=ab.utils.randomPrivateKey(),e=ab.getPublicKey(t,!1),r=Buffer.from(t),s=Buffer.from(e);return{privateKey:r,publicKey:s}},WX=({publicKey:t,privateKey:e})=>{let r=ab.getSharedSecret(e,t);return Buffer.from(r).subarray(1)};Io={CLIENT:1,SERVER:2},QX=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...t){throw new Error("not implemented")}encrypt(...t){throw new Error("not implemented")}decrypt(...t){throw new Error("not implemented")}toString(){return this.name}},GE=rf.webcrypto;pr.set(GE);j0=class{constructor(t,e,r,s){this.sessionType=t,this.certPem=e,this.keyPem=r,e&&r&&s&&this.parseX509(e,r,s)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(t,e)=>{let r=(()=>{switch(t.signature){case Ai.rsa_1:return"RSASSA-PKCS1-v1_5";case Ai.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(t.hash===M0.sha256_4)return"SHA-256"})(),n=(()=>{switch(e){case Ro.secp256r1_23:return"P-256";case Ro.x25519_29:return r==="ECDSA"?"P-256":"X25519";default:{if(r==="ECDSA")return"P-256";if(r==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(r){case"ECDSA":return{name:r,hash:s,namedCurve:n};case"RSASSA-PKCS1-v1_5":return{name:r,hash:s,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await GE.subtle.generateKey(i,!0,["sign","verify"]),c=(await Dx.createSelfSigned({serialNumber:(0,rf.randomBytes)(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:i,keys:o})).toString("pem"),d=Ur.encode(await GE.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:d,signatureHash:t}};encryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor,s=this.cipher.encrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return t.fragment=s,t.recordLayerHeader.contentLen=s.length,t}decryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(t){return this.sessionType===Io.CLIENT?XX(this.masterSecret,t):YX(this.masterSecret,t)}signatureData(t,e){let r=(0,rf.createSign)(e).update(t),s=this.localPrivateKey.toPEM().toString();return r.sign(s)}generateKeySignature(t){let e=this.sessionType===Io.CLIENT?this.localRandom:this.remoteRandom,r=this.sessionType===Io.SERVER?this.localRandom:this.remoteRandom,s=this.valueKeySignature(e.serialize(),r.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(s,t)}parseX509(t,e,r){let s=t1.Certificate.fromPEM(Buffer.from(t)),n=t1.PrivateKey.fromPEM(Buffer.from(e));this.localCert=s.raw,this.localPrivateKey=n,this.signatureHashAlgorithm=r}valueKeySignature(t,e,r,s){let n=Buffer.from((0,Wu.encode)({type:cT.named_curve_3,curve:s,len:r.length},{type:Wu.types.uint8,curve:Wu.types.uint16be,len:Wu.types.uint8}).slice());return Buffer.concat([t,e,n,r])}},F0=class{srtpProfile;static findMatchingSRTPProfile(t,e){for(let r of e)if(t.includes(r))return r}},lT=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),hO=t=>Object.entries({...t}).reduce((e,[r,s])=>((typeof s=="number"||typeof s=="string")&&(e[r]=s),Buffer.isBuffer(s)&&(e[r]=lT(s)),e),{}),nn=class ja{constructor(e,r,s,n,i,o){this.msg_type=e,this.length=r,this.message_seq=s,this.fragment_offset=n,this.fragment_length=i,this.fragment=o}static spec={msg_type:Nn.types.uint8,length:Nn.types.uint24be,message_seq:Nn.types.uint16be,fragment_offset:Nn.types.uint24be,fragment_length:Nn.types.uint24be,fragment:Nn.types.buffer(e=>e.current.fragment_length)};get summary(){return hO(this)}static createEmpty(){return new ja(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ja(...Object.values((0,Nn.decode)(e,ja.spec)))}serialize(){let e=(0,Nn.encode)(this,ja.spec).slice();return Buffer.from(e)}chunk(e){let r=0,s=this.fragment.length;if(s===0)return[new ja(this.msg_type,s,this.message_seq,r,0,this.fragment)];let n=[];for(e||(e=1240);r<s;){let i=Math.min(e,s-r),o=Buffer.from(this.fragment.slice(r,r+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");n.push(new ja(this.msg_type,s,this.message_seq,r,o.length,o)),r+=o.length}return n}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);let r=Buffer.alloc(e[0].length);for(let s of e)s.fragment.copy(r,s.fragment_offset);return new ja(e[0].msg_type,e[0].length,e[0].message_seq,0,r.length,r)}static findAllFragments(e,r){let s=e.find(n=>n.msg_type===r);return s?e?.length?e.filter(n=>n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length):[]:[]}},{uint16be:Fb,uint24be:ZX,buffer:mO,array:eY,uint8:H0,string:tY}=pO.types,rY={type:Fb,data:mO(Fb)},XE=eY(rY,Fb,"bytes"),sY=mO(ZX),nY=H0,iY=tY(Fb),oY={hash:H0,signature:H0},uT={major:H0,minor:H0},Ud=class x0{constructor(e=Math.floor(Date.now()/1e3),r=(0,gO.randomBytes)(28)){this.gmt_unix_time=e,this.random_bytes=r}static spec={gmt_unix_time:Ld.types.uint32be,random_bytes:Ld.types.buffer(28)};static deSerialize(e){return new x0(...Object.values((0,Ld.decode)(e,x0.spec)))}static from(e){return new x0(...Object.values(e))}serialize(){let e=(0,Ld.encode)(this,x0.spec).slice();return Buffer.from(e)}},yO=class b0{constructor(e,r,s,n,i,o,a){this.clientVersion=e,this.random=r,this.sessionId=s,this.cookie=n,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Hr.types.uint8,minor:Hr.types.uint8},random:Ud.spec,sessionId:Hr.types.buffer(Hr.types.uint8),cookie:Hr.types.buffer(Hr.types.uint8),cipherSuites:Hr.types.array(Hr.types.uint16be,Hr.types.uint16be,"bytes"),compressionMethods:Hr.types.array(Hr.types.uint8,Hr.types.uint8,"bytes"),extensions:XE};static createEmpty(){return new b0(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new b0(...Object.values((0,Hr.decode)(e,b0.spec)))}serialize(){let e=(0,Hr.encode)(this,b0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},aY=class w0{constructor(e,r,s,n,i){this.epoch=e,this.sequenceNumber=r,this.contentType=s,this.protocolVersion=n,this.contentLen=i}static spec={epoch:Ao.types.uint16be,sequenceNumber:Ao.types.uint48be,contentType:Ao.types.uint8,protocolVersion:uT,contentLen:Ao.types.uint16be};static createEmpty(){return new w0(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new w0(...Object.values((0,Ao.decode)(e,w0.spec)))}serialize(){let e=(0,Ao.encode)(this,w0.spec).slice();return Buffer.from(e)}},bO=class YE{constructor(e,r){this.recordLayerHeader=e,this.fragment=r}get summary(){return{header:this.recordLayerHeader,fragment:lT(this.fragment)}}static createEmpty(){return new YE(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let r=e.readUInt8(0),s=e.readUInt8(1),n=e.readUInt8(2),i=e.readUInt16BE(3),o=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new YE({contentType:r,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,r=13+e,s=Buffer.alloc(r);return s.writeUInt8(this.recordLayerHeader.contentType,0),s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),s.writeUInt16BE(this.recordLayerHeader.epoch,3),s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),s.writeUInt16BE(e,11),this.fragment.copy(s,13),s}computeMACHeader(){return new aY(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},wO=t=>e=>(t.lastFlight=e,e.flatMap(r=>(r.messageSeq=t.sequenceNumber++,r.toFragment().chunk()))),rm=t=>(e,r)=>e.map(s=>new bO({contentType:s.type,protocolVersion:t.version,epoch:t.epoch,sequenceNumber:r,contentLen:s.fragment.length},s.fragment)),JE=(t=>(t[t.CloseNotify=0]="CloseNotify",t[t.UnexpectedMessage=10]="UnexpectedMessage",t[t.BadRecordMac=20]="BadRecordMac",t[t.DecryptionFailed=21]="DecryptionFailed",t[t.RecordOverflow=22]="RecordOverflow",t[t.DecompressionFailure=30]="DecompressionFailure",t[t.HandshakeFailure=40]="HandshakeFailure",t[t.NoCertificate=41]="NoCertificate",t[t.BadCertificate=42]="BadCertificate",t[t.UnsupportedCertificate=43]="UnsupportedCertificate",t[t.CertificateRevoked=44]="CertificateRevoked",t[t.CertificateExpired=45]="CertificateExpired",t[t.CertificateUnknown=46]="CertificateUnknown",t[t.IllegalParameter=47]="IllegalParameter",t[t.UnknownCa=48]="UnknownCa",t[t.AccessDenied=49]="AccessDenied",t[t.DecodeError=50]="DecodeError",t[t.DecryptError=51]="DecryptError",t[t.ExportRestriction=60]="ExportRestriction",t[t.ProtocolVersion=70]="ProtocolVersion",t[t.InsufficientSecurity=71]="InsufficientSecurity",t[t.InternalError=80]="InternalError",t[t.UserCanceled=90]="UserCanceled",t[t.NoRenegotiation=100]="NoRenegotiation",t[t.UnsupportedExtension=110]="UnsupportedExtension",t))(JE||{}),cY=dt("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),DE=dt("werift-dtls : packages/dtls/src/flight/flight.ts : err"),sm=class QE{constructor(e,r,s,n){this.transport=e,this.dtls=r,this.flight=s,this.nextFlight=n}state="PREPARING";static RetransmitCount=10;createPacket(e){let r=wO(this.dtls)(e);return this.dtls.bufferHandshakeCache(r,!0,this.flight),rm(this.dtls)(r.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let r=0;for(;r<=QE.RetransmitCount;r++){if(this.setState("SENDING"),this.send(e).catch(s=>{DE("fail to send",DE)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,xO.setTimeout)(1e3*((r+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else cY(this.dtls.sessionId,"retransmit",r,this.dtls.flight)}if(r>QE.RetransmitCount)throw DE(this.dtls.sessionId,"retransmit failed",r),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(r=>this.transport.send(r)));setState(e){this.state=e}},dY=class extends sm{constructor(t,e,r){super(t,e,1,3),this.cipher=r}async exec(t){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new yO({major:254,minor:253},new Ud,Buffer.from([]),Buffer.from([]),nO,[0],t);this.dtls.version=e.clientVersion,this.cipher.localRandom=Ud.from(e.random);let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},lY=dt("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),uY=class extends sm{constructor(t,e){super(t,e,3,5)}async exec(t){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;lY("dtls version",e.clientVersion),e.cookie=t.cookie,this.dtls.cookie=t.cookie;let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},s1={NULL:0,ECDHE:1},nm={NULL:0,RSA:1,ECDSA:2,PSK:3},im={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},om=class{id=0;name;signType;keyType;toString(){return this.name}};yY=dt("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),xY=class extends QX{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return hO(this)}init(t,e,r){let s=JX(t,r,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=s.clientWriteKey,this.serverWriteKey=s.serverWriteKey,this.clientNonce=s.clientNonce,this.serverNonce=s.serverNonce}encrypt(t,e,r){let s=t===Io.CLIENT,n=s?this.clientNonce:this.serverNonce,i=s?this.clientWriteKey:this.serverWriteKey;if(!n||!i)throw new Error;n.writeUInt16BE(r.epoch,this.nonceImplicitLength),n.writeUIntBE(r.sequenceNumber,this.nonceImplicitLength+2,6);let o=n.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(r,e.length),c=(0,n1.createCipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let d=c.update(e),u=c.final(),l=c.getAuthTag();return Buffer.concat([o,d,u,l])}encodeAdditionalBuffer(t,e){let r=Buffer.alloc(13);return r.writeUInt16BE(t.epoch,0),r.writeUintBE(t.sequenceNumber,2,6),r.writeUInt8(t.type,8),r.writeUInt16BE(t.version,9),r.writeUInt16BE(e,11),r}decrypt(t,e,r){let s=t===Io.CLIENT,n=s?this.serverNonce:this.clientNonce,i=s?this.serverWriteKey:this.clientWriteKey;if(!n||!i)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(n,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),d=this.encodeAdditionalBuffer(r,a.length),u=(0,n1.createDecipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(d,{plaintextLength:a.length});let l=u.update(a);try{let f=u.final();return f.length>0?Buffer.concat([l,f]):l}catch(f){throw yY("decrypt failed",f,t,lT(e),r,this.summary),f}}},mr={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},l0={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},u0={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},FD=fY(),HD=hY(),$D=pY(),VD=mY(),qD=gY();i1=class{static type=23},o1=class Fu{static type=65281;static spec={type:Md.types.uint16be,data:Md.types.uint8};type=Fu.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Fu}static deSerialize(e){return new Fu((0,Md.decode)(e,Fu.spec))}serialize(){let e=(0,Md.encode)(this,Fu.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},Yu=class Fa{static type=14;static spec={type:Ka.types.uint16be,data:Ka.types.buffer(Ka.types.uint16be)};type=Fa.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,r){return new Fa({profiles:e,mki:r})}static deSerialize(e){let r=new Fa((0,Ka.decode)(e,Fa.spec)),s=r.data.readUInt16BE(),n=new Array(s/2);for(let i=0;i<n.length;i++)n[i]=r.data.readUInt16BE(i*2+2);return r.profiles=n,r.mki=r.data.slice(s+2),r}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let r=Buffer.concat([e,...this.profiles.map(n=>{let i=Buffer.alloc(2);return i.writeUInt16BE(n),i}),this.mki]);this.data=r;let s=(0,Ka.encode)(this,Fa.spec).slice();return Buffer.from(s)}static fromData(e){let r=Buffer.alloc(4);return r.writeUInt16BE(Fa.type),r.writeUInt16BE(e.length,2),Fa.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},Hb=class v0{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:jd.types.array(sY,jd.types.uint24be,"bytes")};static createEmpty(){return new v0(void 0)}static deSerialize(e){return new v0(...Object.values((0,jd.decode)(e,v0.spec)))}serialize(){let e=(0,jd.encode)(this,v0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},EO=class _0{constructor(e=1){this.type=e}static spec={type:sf.types.uint8};static createEmpty(){return new _0}static deSerialize(e){return new _0(...Object.values((0,sf.decode)(e,_0.spec)))}serialize(){let e=(0,sf.encode)(this,_0.spec).slice();return Buffer.from(e)}},CO=class S0{constructor(e,r){this.algorithm=e,this.signature=r}msgType=15;messageSeq;static spec={algorithm:Wa.types.uint16be,signature:Wa.types.buffer(Wa.types.uint16be)};static createEmpty(){return new S0(void 0,void 0)}static deSerialize(e){let r=(0,Wa.decode)(e,S0.spec);return new S0(...Object.values(r))}serialize(){let e=(0,Wa.encode)(this,S0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},TO=class E0{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:Fd.types.buffer(Fd.types.uint8)};static createEmpty(){return new E0(void 0)}static deSerialize(e){let r=(0,Fd.decode)(e,E0.spec);return new E0(...Object.values(r))}serialize(){let e=(0,Fd.encode)(this,E0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},ZE=class eC{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new eC(void 0)}static deSerialize(e){return new eC(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},AO=class C0{constructor(e,r,s){this.certificateTypes=e,this.signatures=r,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:On.types.array(nY,On.types.uint8,"bytes"),signatures:On.types.array(oY,On.types.uint16be,"bytes"),authorities:On.types.array(iY,On.types.uint16be,"bytes")};static createEmpty(){return new C0(void 0,void 0,void 0)}static deSerialize(e){return new C0(...Object.values((0,On.decode)(e,C0.spec)))}serialize(){let e=(0,On.encode)(this,C0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},kO=class Ha{constructor(e,r,s,n,i,o){this.serverVersion=e,this.random=r,this.sessionId=s,this.cipherSuite=n,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:uT,random:Ud.spec,sessionId:Ln.types.buffer(Ln.types.uint8),cipherSuite:Ln.types.uint16be,compressionMethod:Ln.types.uint8};static createEmpty(){return new Ha(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Ln.decode)(e,Ha.spec),s=new Ha(...Object.values(r));return s.serialize().length<e.length?new Ha(...Object.values((0,Ln.decode)(e,{...Ha.spec,extensions:XE}))):s}serialize(){let e=this.extensions===void 0?(0,Ln.encode)(this,Ha.spec).slice():(0,Ln.encode)(this,{...Ha.spec,extensions:XE}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},IO=class T0{msgType=14;messageSeq;static spec={};static createEmpty(){return new T0}static deSerialize(e){return new T0(...Object.values((0,a1.decode)(e,T0.spec)))}serialize(){let e=(0,a1.encode)(this,T0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}};PO=class A0{constructor(e,r,s,n,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=r,this.publicKeyLength=s,this.publicKey=n,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:Dn.types.uint8,namedCurve:Dn.types.uint16be,publicKeyLength:Dn.types.uint8,publicKey:Dn.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Dn.types.uint8,signatureAlgorithm:Dn.types.uint8,signatureLength:Dn.types.uint16be,signature:Dn.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new A0(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Dn.decode)(e,A0.spec);return new A0(...Object.values(r))}serialize(){return bY(this,A0.spec)}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},nf=1,Kd=7,wY=[nf,Kd],BO=t=>{switch(t){case nf:case Kd:return 16}},DO=t=>{switch(t){case nf:return 14;case Kd:return 12}},vY=dt("werift-rtp : packages/rtp/src/codec/av1.ts"),tC=class OO{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let r=new OO,s=0;if(r.zBit_RtpStartsWithFragment=Ee(e[s],0),r.yBit_RtpEndsWithFragment=Ee(e[s],1),r.w_RtpNumObus=Ee(e[s],2,2),r.nBit_RtpStartsNewCodedVideoSequence=Ee(e[s],4),s++,r.nBit_RtpStartsNewCodedVideoSequence&&r.zBit_RtpStartsWithFragment)throw new Error;[...Array(r.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=MO(e.subarray(s)),c=s+a,d=c+o,u=!1;r.zBit_RtpStartsWithFragment&&i===0&&(u=!0),r.obu_or_fragment.push({data:e.subarray(c,d),isFragment:u}),s+=a+o});let n=!1;return(r.yBit_RtpEndsWithFragment||r.w_RtpNumObus===1&&r.zBit_RtpStartsWithFragment)&&(n=!0),r.obu_or_fragment.push({data:e.subarray(s),isFragment:n}),r};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let r=[],s=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,d)=>(a[d]=c,a),{}),n=Object.keys(s).length;for(let a of Object.keys(s).map(Number)){let c=s[a];if(!c)continue;let{data:d,isFragment:u}=c;if(u){let l=[];for(let f=a;f<n;f++){let h=s[f];if(h.isFragment)l.push(h.data),delete s[f];else break}l.length<=1&&(vY("fragment lost, maybe packet lost"),l=[]),r.push(Buffer.concat(l))}else r.push(d)}let i=r.map(a=>LO.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},LO=class UO{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let r=new UO,s=0;return r.obu_forbidden_bit=Ee(e[s],0),r.obu_type=jO[Ee(e[s],1,4)],r.obu_extension_flag=Ee(e[s],5),r.obu_has_size_field=Ee(e[s],6),r.obu_reserved_1bit=Ee(e[s],7),s++,r.payload=e.subarray(s),r}serialize(){let e=new Qb(8).set(this.obu_forbidden_bit).set(_Y[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,r=Buffer.alloc(0);return this.obu_has_size_field&&(r=NO.LEB128.encode(this.payload.length)),Buffer.concat([e,r,this.payload])}};jO={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"},_Y=Object.entries(jO).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),FO=class HO{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,r){let s=new HO,n=0,i=e[n];if(s.f=Ee(i,0),s.nri=Ee(i,1,2),s.nalUnitType=Ee(i,3,5),n++,s.s=Ee(e[n],0),s.e=Ee(e[n],1),s.r=Ee(e[n],2),s.nalUnitPayloadType=Ee(e[n],3,5),n++,0<s.nalUnitType&&s.nalUnitType<$a.stap_a)s.payload=this.packaging(e);else if(s.nalUnitType===$a.stap_a){let o=EY,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=CY,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}s.payload=a}else if(s.nalUnitType===$a.fu_a){r||(r=Buffer.alloc(0));let o=e.subarray(n);if(s.fragment=Buffer.concat([r,o]),s.e){let a=new za(Buffer.alloc(1)).writeBits(1,0).writeBits(2,s.nri).writeBits(5,s.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,s.fragment]);s.fragment=void 0,s.payload=this.packaging(c)}}return s}static packaging(e){return Buffer.concat([SY,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===$a.idrSlice||this.nalUnitPayloadType===$a.idrSlice}get isPartitionHead(){return this.nalUnitType===$a.fu_a||this.nalUnitType===$a.fu_b?this.s!==0:!0}},$a={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},SY=Buffer.from([0,0,0,1]),EY=1,CY=2,$O=class VO{payload;static deSerialize(e){let r=new VO;return r.payload=e,r}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),tr([1,1],[1,2]),FN([2,4,2,1],[312,e,0,0])])}},qO=class zO{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let r=new zO,s=0;if(r.xBit=Ee(e[s],0),r.nBit=Ee(e[s],2),r.sBit=Ee(e[s],3),r.pid=Ee(e[s],5,3),s++,r.xBit&&(r.iBit=Ee(e[s],0),r.lBit=Ee(e[s],1),r.tBit=Ee(e[s],2),r.kBit=Ee(e[s],3),s++),r.iBit)if(r.mBit=Ee(e[s],0),r.mBit){let n=L0(Ee(e[s],1,7)),i=L0(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Ee(e[s],1,7),s++;return r.lBit&&s++,(r.lBit||r.kBit)&&(r.tBit,r.kBit,s++),r.payload=e.subarray(s),r.payloadHeaderExist&&(r.size0=Ee(e[s],0,3),r.hBit=Ee(e[s],3),r.ver=Ee(e[s],4,3),r.pBit=Ee(e[s],7),s++,r.size1=e[s],s++,r.size2=e[s]),r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},KO=class WO{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:r,offset:s}=this.parseRtpPayload(e);return r.payload=e.subarray(s),r}static parseRtpPayload(e){let r=new WO,s=0;if(r.iBit=Ee(e[s],0),r.pBit=Ee(e[s],1),r.lBit=Ee(e[s],2),r.fBit=Ee(e[s],3),r.bBit=Ee(e[s],4),r.eBit=Ee(e[s],5),r.vBit=Ee(e[s],6),r.zBit=Ee(e[s],7),s++,r.iBit)if(r.m=Ee(e[s],0),r.m){let n=L0(Ee(e[s],1,7)),i=L0(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Ee(e[s],1,7),s++;if(r.lBit&&(r.tid=Ee(e[s],0,3),r.u=Ee(e[s],3),r.sid=Ee(e[s],4,3),r.d=Ee(e[s],7),s++,r.fBit===0&&(r.tl0PicIdx=e[s],s++)),r.fBit&&r.pBit)for(;;){r.pDiff=[...r.pDiff,Ee(e[s],0,7)];let n=Ee(e[s],7);if(s++,n===0)break}return r.vBit&&(r.n_s=Ee(e[s],0,3),r.y=Ee(e[s],3),r.g=Ee(e[s],4),s++,r.y&&[...Array(r.n_s+1)].forEach(()=>{r.width.push(e.readUInt16BE(s)),s+=2,r.height.push(e.readUInt16BE(s)),s+=2}),r.g&&(r.n_g=e[s],s++),r.n_g>0&&[...Array(r.n_g).keys()].forEach(n=>{r.pgT.push(Ee(e[s],0,3)),r.pgU.push(Ee(e[s],3));let i=Ee(e[s],4,2);s++,r.pgP_Diff[n]=[],i>0&&[...Array(i)].forEach(()=>{r.pgP_Diff[n].push(e[s]),s++})})),{offset:s,p:r}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},TY=class{payload;fragment;static deSerialize(t,e){return{}}static isDetectedFinalPacketInSequence(t){return!0}get isKeyframe(){return!0}};kY=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];RY={setTimeout:(...t)=>{let e=setTimeout(...t);return()=>clearTimeout(e)},setInterval:(...t)=>{let e=setInterval(()=>{t[0]()},...t.slice(1));return()=>clearInterval(e)}};$b=4,Do=class sC{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,r,s,n){let o=new sC({type:e,count:r,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new O0(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),tr([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[r,s,n]=os(e,[1,1,2]),i=Ee(r,0,2),o=Ee(r,2,1)>0,a=Ee(r,3,5);return new sC({version:i,padding:o,count:a,type:s,length:n})}},zD=class nC{static count=4;count=nC.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[r,s]=os(e,[4,4]),n=[];for(let i=8;i<e.length;i+=8)n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]});return new nC({senderSsrc:r,mediaSsrc:s,fir:n})}serialize(){let e=tr([4,4],[this.senderSsrc,this.mediaSsrc]),r=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{r.writeUInt32BE(s,i*8),r[i*8+4]=n}),Buffer.concat([e,r])}},V0=class iC{static count=1;count=iC.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s]=os(e,[4,4]);return new iC({senderSsrc:r,mediaSsrc:s})}serialize(){return tr([4,4],[this.senderSsrc,this.mediaSsrc])}},q0=class oC{static count=15;length;count=oC.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s,n,i,o]=os(e,[4,4,4,1,1]),a=Ee(o,0,6),c=(Ee(o,6,2)<<16)+(e[14]<<8)+e[15],d=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),u=[];for(let l=16;l<e.length;l+=4){let f=e.slice(l).readUIntBE(0,4);u.push(f)}return new oC({senderSsrc:r,mediaSsrc:s,uniqueID:tr([4],[n]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:u,bitrate:d})}serialize(){let e=Buffer.concat([tr([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),tr([1],[this.ssrcNum])]),r=new O0(24);r.set(6,0,this.brExp).set(18,6,this.brMantissa);let s=Buffer.concat(this.ssrcFeedbacks.map(i=>tr([4],[i]))),n=Buffer.concat([e,tr([3],[r.value]),s]);return this.length=n.length/4,n}},PY=dt("werift-rtp: /rtcp/psfb/index"),Ju=class aC{static type=206;type=aC.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return Do.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,r){let s;switch(r.count){case zD.count:s=zD.deSerialize(e);break;case V0.count:s=V0.deSerialize(e);break;case q0.count:s=q0.deSerialize(e);break;default:PY("unknown psfb packet",r.count);break}return new aC({feedback:s})}},Qu=class xb{ssrc=0;reports=[];static type=201;type=xb.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=tr([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Do.serialize(xb.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let[s]=os(e,[4]),n=4,i=[];for(let o=0;o<r;o++)i.push(c1.deSerialize(e.slice(n,n+24))),n+=24;return new xb({ssrc:s,reports:i})}},c1=class XO{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 tr([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[r,s,n,i,o,a,c]=os(e,[4,1,3,4,4,4,4]);return new XO({ssrc:r,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},YO=205,z0=class cC{static count=1;count=cC.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new Do({type:YO,count:this.count,version:2}))}static deSerialize(e,r){let[s,n]=os(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=os(e.subarray(o),[2,2]);i.push(a);for(let d=0;d<16;d++)c>>d&1&&i.push(a+d+1)}return new cC({header:r,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){let e=tr([4,4],[this.senderSsrc,this.mediaSourceSsrc]),r=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{let a=o-n-1;a>=0&&a<16?i|=1<<a:(r.push(tr([2,2],[n,i])),n=o,i=0)}),r.push(tr([2,2],[n,i]))}let s=Buffer.concat([e,Buffer.concat(r)]);return this.header.length=s.length/4,Buffer.concat([this.header.serialize(),s])}},BY=dt("werift/rtp/rtcp/rtpfb/twcc"),K0=class dC{static count=15;count=dC.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new Do({type:205,count:this.count,version:2}))}static deSerialize(e,r){let[s,n,i,o,a,c]=os(e,[4,4,2,2,3,1]),d=[],u=[],l=16;for(let h=0;h<o;){let m=Ee(e.slice(l,l+1)[0],0,1),v;switch(m){case 0:{let p=Gu.deSerialize(e.slice(l,l+2));v=p;let x=Math.min(o-h,p.runLength);if(p.packetStatus===1||p.packetStatus===2)for(let w=0;w<x;w++)u.push(new B0({type:p.packetStatus}));h+=x}break;case 1:{let p=QO.deSerialize(e.slice(l,l+2));v=p,p.symbolSize===0&&p.symbolList.forEach(x=>{x===1&&u.push(new B0({type:1}))}),p.symbolSize===1&&p.symbolList.forEach(x=>{(x===1||x===2)&&u.push(new B0({type:x}))}),h+=p.symbolList.length}break}if(!v)throw new Error;l+=2,d.push(v)}let f=l;return u.forEach(h=>{h.type===1&&(h.deSerialize(e.slice(f,f+1)),f++),h.type===2&&(h.deSerialize(e.slice(f,f+2)),f+=2)}),new dC({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:u,packetChunks:d,header:r})}serialize(){let e=tr([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),r=Buffer.concat(this.packetChunks.map(i=>i.serialize())),s=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){BY(o?.message);return}}).filter(i=>i)),n=Buffer.concat([e,r,s]);if(this.header.padding&&n.length%4!==0){let i=4-n.length%4,o=Buffer.alloc(i);return o[o.length-1]=o.length,this.header.length=Math.floor((n.length+o.length)/4),Buffer.concat([this.header.serialize(),n,o])}return this.header.length=Math.floor(n.length/4),Buffer.concat([this.header.serialize(),n])}get packetResults(){let e=this.baseSequenceNumber-1,r=this.packetChunks.filter(o=>o instanceof Gu).flatMap(o=>o.results(e)),s=0,i=BigInt(this.referenceTime)*64n;for(let o of r){let a=this.recvDeltas[s];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),s++)}return r}},Gu=class JO{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let r=Ee(e[0],1,2),s=(Ee(e[0],3,5)<<8)+e[1];return new JO({type:0,packetStatus:r,runLength:s})}serialize(){return new Qb(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let r=this.packetStatus===1||this.packetStatus===2,s=[];for(let n=0;n<=this.runLength;++n)s.push(new rL({sequenceNumber:++e,received:r}));return s}},QO=class ZO{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=Ee(e[0],1,1),n=[];function i(o,a){for(let c=0;c<o;c++)a(c)}switch(s){case 0:i(6,o=>n.push(Ee(e[0],2+o,1))),i(8,o=>n.push(Ee(e[1],o,1)));break;case 1:i(3,o=>n.push(Ee(e[0],2+o*2,2))),i(4,o=>n.push(Ee(e[1],o*2,2)));break;default:s=(Ee(e[0],2,6)<<8)+e[1]}return new ZO({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),r=new Qb(16).set(1).set(this.symbolSize),s=this.symbolSize===0?1:2;return this.symbolList.forEach(n=>{r.set(n,s)}),e.writeUInt16BE(r.value),e}},B0=class lC{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r,s;if(e.length===1?(r=1,s=250*e[0]):e.length===2&&(r=2,s=250*e.readInt16BE()),r===void 0||s===void 0)throw new Error;return new lC({type:r,delta:s})}deSerialize(e){let r=lC.deSerialize(e);this.delta=r.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},eL=(t=>(t[t.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",t[t.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",t[t.packetStatusChunkLength=2]="packetStatusChunkLength",t))(eL||{}),tL=(t=>(t[t.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",t[t.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",t[t.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",t[t.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",t))(tL||{}),rL=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(t){Object.assign(this,t)}},DY=dt("werift-rtp:packages/rtp/rtcp/rtpfb/index"),Hd=class uC{static type=YO;type=uC.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,r){let s;switch(r.count){case z0.count:s=z0.deSerialize(e,r);break;case K0.count:s=K0.deSerialize(e,r);break;default:DY("unknown rtpfb packet",r.count);break}return new uC({feedback:s,header:r})}},W0=class fC{static type=202;type=fC.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(r=>e+=r.length),e}serialize(){let e=Buffer.concat(this.chunks.map(r=>r.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return Do.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,r){let s=[];for(let n=0;n<e.length;){let i=fT.deSerialize(e.slice(n));s.push(i),n+=i.length}return new fC({chunks:s})}},fT=class sL{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(r=>e+=r.length),e+=1,e+=KD(e),e}serialize(){let e=Buffer.concat([tr([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);return Buffer.concat([e,Buffer.alloc(KD(e.length))])}static deSerialize(e){let r=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=hT.deSerialize(e.slice(n));s.push(o),n+=o.length}return new sL({source:r,items:s})}},hT=class nL{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([tr([1,1],[this.type,e.length]),e])}static deSerialize(e){let r=e[0],s=e[1],n=e.slice(2,2+s).toString();return new nL({type:r,text:n})}};$d=class bb{ssrc=0;senderInfo;reports=[];static type=200;type=bb.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Do.serialize(bb.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let s=e.readUInt32BE(),n=pT.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<r;c++)o.push(c1.deSerialize(e.subarray(i,i+24))),i+=24;return new bb({ssrc:s,senderInfo:n,reports:o})}},pT=class iL{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:oL(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return tr([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[r,s,n,i]=os(e,[8,4,4,4]);return new iL({ntpTimestamp:r,rtpTimestamp:s,packetCount:n,octetCount:i})}},oL=t=>{let[e,r]=os(tr([8],[t]),[4,4]);return+`${e}.${r}`},NY=dt("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),aL=class{static deSerialize(t){let e=0,r=[];for(;e<t.length;){let s=Do.deSerialize(t.subarray(e,e+$b));e+=$b;let n=t.subarray(e);e+=s.length*4,s.padding&&(n=n.subarray(0,n.length-n.subarray(-1)[0]));try{switch(s.type){case $d.type:r.push($d.deSerialize(n,s.count));break;case Qu.type:r.push(Qu.deSerialize(n,s.count));break;case W0.type:r.push(W0.deSerialize(n,s));break;case Hd.type:r.push(Hd.deSerialize(n,s));break;case Ju.type:r.push(Ju.deSerialize(n,s));break;default:break}}catch(i){NY("deSerialize RTCP",i)}}return r}};Xt={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"};LY=dt("packages/rtp/src/rtp/red/packet.ts"),mT=class wL{header;blocks=[];static deSerialize(e){let r=e instanceof ArrayBuffer?Buffer.from(e):e,s=new wL,n=0;return[s.header,n]=hC.deSerialize(r),s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=r.subarray(n,n+i);s.blocks.push({block:c,blockPT:a,timestampOffset:o}),n+=i}else{let c=r.subarray(n);s.blocks.push({block:c,blockPT:a})}}),s}serialize(){this.header=new hC;for(let{timestampOffset:r,blockPT:s,block:n}of this.blocks)r?this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:r}):this.header.fields.push({fBit:0,blockPT:s});let e=this.header.serialize();for(let{block:r}of this.blocks)e=Buffer.concat([e,r]);return e}},hC=class vL{fields=[];static deSerialize(e){let r=0,s=new vL;for(;;){let n={};s.fields.push(n);let i=new za(e.subarray(r));if(n.fBit=i.readBits(1),n.blockPT=i.readBits(7),r++,n.fBit===0)break;n.timestampOffset=i.readBits(14),n.blockLength=i.readBits(10),r+=3}return[s,r]}serialize(){let e=Buffer.alloc(0);for(let r of this.fields)try{if(r.timestampOffset&&r.blockLength){let s=new za(Buffer.alloc(4)).writeBits(1,r.fBit).writeBits(7,r.blockPT).writeBits(14,r.timestampOffset).writeBits(10,r.blockLength);e=Buffer.concat([e,s.uint8Array])}else{let s=new za(Buffer.alloc(1)).writeBits(1,0).writeBits(7,r.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){LY(s?.message)}return e}},_L=class{constructor(t=1){this.distance=t}cache=[];cacheSize=10;push(t){this.cache.push(t),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let t=new mT,e=this.cache.slice(-(this.distance+1)),r=e.pop();return r&&(e.forEach(s=>{let n=Od(r.timestamp,-s.timestamp);n>UY||t.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),t.blocks.push({block:r.block,blockPT:r.blockPT})),t}},UY=16383,SL=class{size=150;sequenceNumbers=[];push(t,e){let r=[];return t.blocks.forEach(({blockPT:n,timestampOffset:i,block:o},a)=>{let c=$r(e.header.sequenceNumber,-(t.blocks.length-(a+1)));i?r.push(new Bo(new Po({timestamp:Od(e.header.timestamp,-i),payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):r.push(new Bo(new Po({timestamp:e.header.timestamp,payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),r.filter(n=>this.sequenceNumbers.includes(n.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(n.header.sequenceNumber),!0))}},Va={OneByte:48862,TwoByte:4096},WD=2,GD=4,XD=8,YD=12,JD=4,Po=class EL{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=Va.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r=new EL,s=0,n=e[s++];r.version=Ee(n,0,2),r.padding=Ee(n,2)>0,r.extension=Ee(n,3)>0,r.csrcLength=Ee(n,4,4),r.csrc=[...Array(r.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=YD-1;let i=e[1];r.marker=Ee(i,0)>0,r.payloadType=Ee(i,1,7),r.sequenceNumber=e.readUInt16BE(WD),r.timestamp=e.readUInt32BE(GD),r.ssrc=e.readUInt32BE(XD);for(let o=0;o<r.csrc.length;o++){let a=YD+o*JD;r.csrc[o]=e.subarray(a).readUInt32BE()}if(r.extension){r.extensionProfile=e.subarray(s).readUInt16BE(),s+=2;let o=e.subarray(s).readUInt16BE()*4;switch(r.extensionLength=o,s+=2,r.extensionProfile){case Va.OneByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s]>>4,d=(e[s]&(e[s]^240))+1;if(s++,c===15)break;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;case Va.TwoByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s];s++;let d=e[s];s++;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;default:{let a={id:0,payload:e.subarray(s,s+o)};r.extensions=[...r.extensions,a],s+=r.extensions[0].payload.length}break}}return r.payloadOffset=s,r.padding&&(r.paddingSize=e[e.length-1]),r}get serializeSize(){let{csrc:e,extensionProfile:r,extensions:s}=this,n=12+e.length*JD;if(s.length>0||this.extension===!0){let i=4;switch(r){case Va.OneByte:for(let o of s)i+=1+o.payload.length;break;case Va.TwoByte:for(let o of s)i+=2+o.payload.length;break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){let r=Buffer.alloc(e),s=0,n=new O0(8);n.set(2,0,this.version),this.padding&&n.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&n.set(1,3,1),n.set(4,4,this.csrc.length),r.writeUInt8(n.value,s++);let i=new O0(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),r.writeUInt8(i.value,s++),r.writeUInt16BE(this.sequenceNumber,WD),s+=2,r.writeUInt32BE(this.timestamp,GD),s+=4,r.writeUInt32BE(this.ssrc,XD),s+=4;for(let o of this.csrc)r.writeUInt32BE(o,s),s+=4;if(this.extension){let o=s;r.writeUInt16BE(this.extensionProfile,s),s+=4;let a=s;switch(this.extensionProfile){case Va.OneByte:for(let u of this.extensions)r.writeUInt8(u.id<<4|u.payload.length-1,s++),u.payload.copy(r,s),s+=u.payload.length;break;case Va.TwoByte:for(let u of this.extensions)r.writeUInt8(u.id,s++),r.writeUInt8(u.payload.length,s++),u.payload.copy(r,s),s+=u.payload.length;break;default:{let u=this.extensions[0].payload.length;if(u%4!=0)throw new Error;this.extensions[0].payload.copy(r,s),s+=u}}let c=s-a,d=Math.trunc((c+3)/4)*4;r.writeUInt16BE(Math.trunc(d/4),o+2);for(let u=0;u<d-c;u++)r.writeUInt8(0,s),s++}return this.payloadOffset=s,r}},Bo=class pC{constructor(e,r){this.header=e,this.payload=r}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new pC(new Po({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:r}=this.header;if(this.payload.copy(e,r),this.header.padding){let s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,s])}return e}static deSerialize(e){let r=Po.deSerialize(e);return new pC(r,e.subarray(r.payloadOffset,e.length-r.paddingSize))}clear(){this.payload=null}};AL=class{constructor(t,e,r,s){this.srtpSessionKey=t,this.srtpSessionSalt=e,this.srtcpSessionKey=r,this.srtcpSessionSalt=s}encryptRtp(t,e,r){return Buffer.from([])}decryptRtp(t,e,r){return[]}encryptRTCP(t,e){return Buffer.from([])}decryptRTCP(t){return[]}},Vd=class extends Error{constructor(t){super(t),this.name="SrtpAuthenticationError"}},QD=12,MY=8;jY=class extends AL{constructor(t,e,r,s,n,i){super(t,e,r,s),this.srtpSessionAuthTag=n,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.generateCounter(t.sequenceNumber,r,t.ssrc,this.srtpSessionSalt),o=(0,Un.createCipheriv)("aes-128-ctr",this.srtpSessionKey,n).update(e),a=this.generateSrtpAuthTag(r,s,o);return Buffer.concat([s,o,a])}decryptRtp(t,e,r=yT(t,this.authTagLength)){let s=t.length-this.authTagLength,n=t.subarray(0,s),i=t.subarray(s),o=this.generateSrtpAuthTag(e,n.subarray(0,r.payloadOffset),n.subarray(r.payloadOffset));eN(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(r.sequenceNumber,e,r.ssrc,this.srtpSessionSalt),c=(0,Un.createDecipheriv)("aes-128-ctr",this.srtpSessionKey,a),d=n.subarray(r.payloadOffset),u=c.update(d),l=Buffer.concat([n.subarray(0,r.payloadOffset),u]);return[l,RL(r,l,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=Buffer.from(t),s=r.readUInt32BE(4),n=this.generateCounter(e&65535,e>>16,s,this.srtcpSessionSalt);(0,Un.createCipheriv)("aes-128-ctr",this.srtcpSessionKey,n).update(r.slice(8)).copy(r,8),r=Buffer.concat([r,Buffer.alloc(4)]),r.writeUInt32BE(e,r.length-4),r[r.length-4]|=128;let a=this.generateSrtcpAuthTag(r);return r=Buffer.concat([r,a]),r}decryptRTCP(t){let e=kL(t,this.authTagLength,ZD),r=t.length-(this.authTagLength+ZD),s=t.subarray(0,t.length-this.authTagLength),n=t.subarray(t.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);eN(n,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(t).slice(0,r);if(t[r]>>>7===0)return[o,e];let c=t.readUInt32BE(r);c&=~(1<<31);let d=t.readUInt32BE(4),u=this.generateCounter(c&65535,c>>16,d,this.srtcpSessionSalt);return(0,Un.createDecipheriv)("aes-128-ctr",this.srtcpSessionKey,u).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(t){return(0,Un.createHmac)("sha1",this.srtcpSessionAuthTag).update(t).digest().slice(0,10)}generateCounter(t,e,r,s){let n=Buffer.alloc(16);n.writeUInt32BE(r,4),n.writeUInt32BE(e,8),n.writeUInt32BE(Number(BigInt(t)<<16n),12);for(let i=0;i<s.length;i++)n[i]^=s[i];return n}generateSrtpAuthTag(t,...e){let r=(0,Un.createHmac)("sha1",this.srtpSessionAuthTag),s=Buffer.alloc(4);s.writeUInt32BE(t);for(let n of e)r.update(n);return r.update(s).digest().subarray(0,10)}},ZD=4;FY=class extends AL{aeadAuthTagLen=16;rtpIvWriter=P0([2,4,4,2],!0);rtcpIvWriter=P0([2,4,2,4],!0);aadWriter=P0([4],!0);constructor(t,e,r,s){super(t,e,r,s)}encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.rtpInitializationVector(t,r),i=(0,Zu.createCipheriv)("aes-128-gcm",this.srtpSessionKey,n);i.setAAD(s);let o=i.update(e);i.final();let a=i.getAuthTag();return Buffer.concat([s,o,a])}decryptRtp(t,e,r=yT(t,this.aeadAuthTagLen)){let s=t.subarray(0,r.payloadOffset),n=t.length-this.aeadAuthTagLen,i=t.subarray(n),o=Buffer.from([]);o=rC(o,t.length-this.aeadAuthTagLen),s.copy(o);let a=this.rtpInitializationVector(r,e),c=t.slice(r.payloadOffset,n),d=(0,Zu.createDecipheriv)("aes-128-gcm",this.srtpSessionKey,a);d.setAAD(s),d.setAuthTag(i);let u=d.update(c);return rN(d,"SRTP"),u.copy(o,r.payloadOffset),[o,RL(r,o,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=t.readUInt32BE(4),s=t.length+this.aeadAuthTagLen,n=Buffer.from([]);n=rC(n,s+NE),t.slice(0,8).copy(n);let i=this.rtcpInitializationVector(r,e),o=this.rtcpAdditionalAuthenticatedData(t,e),a=(0,Zu.createCipheriv)("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(t.slice(8));return a.final(),c.copy(n,8),a.getAuthTag().copy(n,8+c.length),o.slice(8,12).copy(n,s),n}decryptRTCP(t){let e=kL(t,this.aeadAuthTagLen,NE),r=t.length-NE,s=r-this.aeadAuthTagLen,n=t.readUInt32BE(4),i=t.readUInt32BE(r),o=i>>>31===1,a=i&~(tN<<24),c=this.rtcpInitializationVector(n,a),d=o?Buffer.concat([t.subarray(0,8),t.subarray(r)]):Buffer.concat([t.subarray(0,s),t.subarray(r)]),u=o?t.slice(8,s):Buffer.alloc(0),l=o?Buffer.alloc(s):Buffer.from(t.subarray(0,s));o&&t.slice(0,8).copy(l);let f=(0,Zu.createDecipheriv)("aes-128-gcm",this.srtcpSessionKey,c);f.setAAD(d),f.setAuthTag(t.subarray(s,r));let h=f.update(u);return rN(f,"SRTCP"),o&&h.copy(l,8),[l,e]}rtpInitializationVector(t,e){let r=this.rtpIvWriter([0,t.ssrc,e,t.sequenceNumber]);for(let s=0;s<r.length;s++)r[s]^=this.srtpSessionSalt[s];return r}rtcpInitializationVector(t,e){let r=this.rtcpIvWriter([0,t,0,e]);for(let s=0;s<r.length;s++)r[s]^=this.srtcpSessionSalt[s];return r}rtcpAdditionalAuthenticatedData(t,e){let r=Buffer.concat([t.subarray(0,8),this.aadWriter([e])]);return r[8]|=tN,r}},NE=4,tN=128;PL=class{constructor(t,e,r){this.masterKey=t,this.masterSalt=e,this.profile=r;{let s=14-e.length;s>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(s)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=(0,wb.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,wb.createHmac)("sha1",this.srtcpSessionAuthTag),r){case nf:this.cipher=new jY(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case Kd:this.cipher=new FY(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new vb.default.AES(this.masterKey);return Buffer.from(s.encrypt(e))}generateSessionSalt(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new vb.default.AES(this.masterKey);return e=Buffer.from(s.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let o=r.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^r[o];let s=Buffer.concat([e,Buffer.from([0,0])]),n=Buffer.concat([e,Buffer.from([0,1])]),i=new vb.default.AES(this.masterKey);return s=Buffer.from(i.encrypt(s)),n=Buffer.from(i.encrypt(n)),Buffer.concat([s,n.subarray(0,4)])}getSrtpSsrcState(t){let e=this.srtpSSRCStates[t];return e||(e={ssrc:t,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[t]=e,e)}getSrtcpSsrcState(t){let e=this.srtcpSSRCStates[t];return e||(e={srtcpIndex:0,ssrc:t},this.srtcpSSRCStates[t]=e,e)}updateRolloverCount(t,e){e.rolloverHasProcessed?t===0?e.lastSequenceNumber>f0&&e.rolloverCounter++:e.lastSequenceNumber<f0&&t>sN-f0?e.rolloverCounter>0&&e.rolloverCounter--:t<f0&&e.lastSequenceNumber>sN-f0&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=t}generateSrtpAuthTag(t,e){this.srtpSessionAuth=(0,wb.createHmac)("sha1",this.srtpSessionAuthTag);let r=Buffer.alloc(4);return r.writeUInt32BE(e),this.srtpSessionAuth.update(t).update(r).digest().slice(0,10)}index(t){let e=this.srtcpSSRCStates[t];return e?e.srtcpIndex:0}setIndex(t,e){let r=this.getSrtcpSsrcState(t);r.srtcpIndex=e%2147483647}},f0=100,sN=65535,HY=class extends PL{constructor(t,e,r){super(t,e,r)}encryptRTCP(t){let e=t.readUInt32BE(4),r=this.getSrtcpSsrcState(e);return r.srtcpIndex++,r.srtcpIndex>>$Y&&(r.srtcpIndex=0),this.cipher.encryptRTCP(t,r.srtcpIndex)}decryptRTCP(t){return this.cipher.decryptRTCP(t)}},$Y=2147483647,BL=class{constructor(t){this.ContextCls=t}localContext;remoteContext;onData;start(t,e,r,s,n){this.localContext=new this.ContextCls(t,e,n),this.remoteContext=new this.ContextCls(r,s,n)}},DL=class extends BL{constructor(t){super(HY),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRTCP(t);return e};encrypt(t){return this.localContext.encryptRTCP(t)}},VY=class extends PL{constructor(t,e,r){super(t,e,r)}encryptRtp(t,e){let r=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,r),this.cipher.encryptRtp(e,t,r.rolloverCounter)}decryptRtp(t){let e=yT(t,this.rtpAuthTagLength),r=this.srtpSSRCStates[e.ssrc],s=r?{...r}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,s);let n=this.cipher.decryptRtp(t,s.rolloverCounter,e);return r?Object.assign(r,s):this.srtpSSRCStates[e.ssrc]=s,n}get rtpAuthTagLength(){return this.profile===Kd?16:10}},NL=class extends BL{constructor(t){super(VY),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRtp(t);return e};encrypt(t,e){return this.localContext.encryptRtp(t,e)}},qY=class{constructor(t){this.props=t}sequenceNumber=sT();timestamp=Ub();create(t){this.sequenceNumber=$r(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=Od(this.timestamp,e);let r=new Po({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new Bo(r,t)}},is=dt("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),zY=class extends sm{constructor(t,e,r,s){super(t,e,5,7),this.cipher=r,this.srtp=s}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,4);let e=(()=>{switch(t.msg_type){case 2:return kO.deSerialize(t.fragment);case 11:return Hb.deSerialize(t.fragment);case 12:return PO.deSerialize(t.fragment);case 13:return AO.deSerialize(t.fragment);case 14:return IO.deSerialize(t.fragment)}})();e&&of[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){is(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let t=this.dtls.requestedCertificateTypes.length>0;is(this.dtls.sessionId,"send flight5",t);let e=[t&&this.sendCertificate(),this.sendClientKeyExchange(),t&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(r=>r);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let t=new Hb([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(s=>s.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let t=new TO(this.cipher.localKeyPair.publicKey),e=this.createPacket([t]),r=Buffer.concat(e.map(a=>a.serialize())),s=this.cipher.localKeyPair,n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error("not exist");let i=cO(n.publicKey,s.privateKey,s.curve);is(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?lO(i,o):dO(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=vO(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),is(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),r}sendCertificateVerify(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(t,"sha256"),r=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case Ai.ecdsa_3:return WE.ecdsa_secp256r1_sha256;case Ai.rsa_1:return WE.rsa_pkcs1_sha256}})();if(!r)throw new Error;is(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,r);let s=new CO(r,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let t=EO.createEmpty().serialize(),e=rm(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new ZE(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);this.dtls.recordSequenceNumber=0;let n=this.cipher.encryptPacket(s).serialize();return is(this.dtls.sessionId,"finished",this.cipher.cipher.summary),n}},of={};of[2]=({cipher:t,srtp:e,dtls:r})=>s=>{is(r.sessionId,"serverHello",s.cipherSuite),t.remoteRandom=Ud.from(s.random),t.cipherSuite=s.cipherSuite,is(r.sessionId,"selected cipherSuite",t.cipherSuite),s.extensions&&s.extensions.forEach(n=>{switch(n.type){case Yu.type:{let i=Yu.fromData(n.data),o=F0.findMatchingSRTPProfile(i.profiles,r.options.srtpProfiles||[]);if(is(r.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case i1.type:r.remoteExtendedMasterSecret=!0;break;case o1.type:is(r.sessionId,"RenegotiationIndication");break}})};of[11]=({cipher:t,dtls:e})=>r=>{is(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};of[12]=({cipher:t,dtls:e})=>r=>{if(!t.localRandom||!t.remoteRandom)throw new Error;is(e.sessionId,"ServerKeyExchange",r),is(e.sessionId,"selected curve",r.namedCurve),t.remoteKeyPair={curve:r.namedCurve,publicKey:r.publicKey},t.localKeyPair=SO(r.namedCurve)};of[13]=({dtls:t})=>e=>{is(t.sessionId,"certificate_request",e),t.requestedCertificateTypes=e.certificateTypes,t.requestedSignatureAlgorithms=e.signatures};of[14]=({dtls:t})=>e=>{is(t.sessionId,"server_hello_done",e)};OL=class k0{constructor(e,r){this.serverVersion=e,this.cookie=r}msgType=3;messageSeq;static spec={serverVersion:uT,cookie:qd.types.buffer(qd.types.uint8)};static createEmpty(){return new k0(void 0,void 0)}static deSerialize(e){return new k0(...Object.values((0,qd.decode)(e,k0.spec)))}serialize(){let e=(0,qd.encode)(this,k0.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new nn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},KY=dt("werift-dtls : packages/dtls/src/context/dtls.ts : log"),nN=class{constructor(t,e){this.options=t,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([t],[e])=>Number(t)-Number(e)).flatMap(([,{data:t}])=>t.sort((e,r)=>e.message_seq-r.message_seq))}checkHandshakesExist=t=>!t.find(e=>this.sortedHandshakeCache.find(r=>r.msg_type===e)==null);bufferHandshakeCache(t,e,r){this.handshakeCache[r]||(this.handshakeCache[r]={data:[],isLocal:e,flight:r});let s=t.filter(n=>{let i=this.handshakeCache[r].data.find(o=>o.msg_type===n.msg_type);return i?(KY(this.sessionId,"exist",i.summary,e,r),!1):!0});this.handshakeCache[r].data=[...this.handshakeCache[r].data,...s]}},WY=class{constructor(t){this.socket=t}send=t=>this.socket.send(t)},mC=class Eo{static type=10;static spec={type:Ti.types.uint16be,data:Ti.types.array(Ti.types.uint16be,Ti.types.uint16be,"bytes")};type=Eo.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Eo}static fromData(e){return new Eo({type:Eo.type,data:(0,Ti.decode)(e,Eo.spec.data)})}static deSerialize(e){return new Eo((0,Ti.decode)(e,Eo.spec))}serialize(){return Buffer.from((0,Ti.encode)(this,Eo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},gC=class qa{static type=13;static spec={type:Ci.types.uint16be,data:Ci.types.array({hash:Ci.types.uint8,signature:Ci.types.uint8},Ci.types.uint16be,"bytes")};type=qa.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new qa}static deSerialize(e){return new qa((0,Ci.decode)(e,qa.spec))}serialize(){let e=(0,Ci.encode)(this,qa.spec).slice();return Buffer.from(e)}static fromData(e){let r=Buffer.alloc(2);return r.writeUInt16BE(qa.type),qa.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},iN=class _b{constructor(e,r){this.level=e,this.description=r}static spec={level:zd.types.uint8,description:zd.types.uint8};static deSerialize(e){return new _b(...Object.values((0,zd.decode)(e,_b.spec)))}serialize(){let e=(0,zd.encode)(this,_b.spec).slice();return Buffer.from(e)}},oN=dt("werift-dtls : packages/dtls/record/receive.ts : log"),OE=dt("werift-dtls : packages/dtls/record/receive.ts : err"),GY=t=>{let e=0,r=[];for(;t.length>e;){let s=t.readUInt16BE(e+11);if(t.length<e+(12+s))break;let n=bO.deSerialize(t.subarray(e));r.push(n),e+=13+s}return r},XY=(t,e)=>r=>{switch(r.recordLayerHeader.contentType){case 20:return oN(t.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=r.fragment;try{r.recordLayerHeader.epoch>0&&(oN(t.sessionId,"decrypt handshake"),n=e.decryptPacket(r))}catch(i){throw OE(t.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;n.length>i;){let a=nn.deSerialize(n.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw OE(t.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(r)}];case 21:{let n=iN.deSerialize(r.fragment);if(JE[n.description]==null){let i=e.decryptPacket(r);n=iN.deSerialize(i)}if(OE(t.sessionId,"ContentType.alert",n,JE[n.description],"flight",t.flight,"lastFlight",t.lastFlight),n.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},aN=dt("werift-dtls : packages/dtls/src/socket.ts : log"),cN=dt("werift-dtls : packages/dtls/src/socket.ts : err"),xT=class{constructor(t,e){this.options=t,this.sessionType=e,this.dtls=new nN(this.options,this.sessionType),this.cipher=new j0(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new WY(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Be;onData=new Be;onError=new Be;onClose=new Be;transport;cipher;dtls;srtp=new F0;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){aN("renegotiation",this.sessionType),this.connected=!1,this.cipher=new j0(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new nN(this.options,this.sessionType),this.srtp=new F0,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=t=>{let e=GY(t);for(let r of e)try{let s=XY(this.dtls,this.cipher)(r);for(let n of s)switch(n.type){case 22:{let i=n.data,o=this.handleFragmentHandshake([i]),a=Object.values(o.reduce((c,d)=>(c[d.msg_type]||(c[d.msg_type]=[]),c[d.msg_type].push(d),c),{})).map(c=>nn.assemble(c)).sort((c,d)=>c.msg_type-d.msg_type);this.onHandleHandshakes(a).catch(c=>{cN(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(n.data);break;case 21:this.onClose.execute();break}}catch(s){cN(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(aN(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let t=Yu.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(t.extension)}{let t=mC.createEmpty();t.data=aT,this.extensions.push(t.extension)}{let t=gC.createEmpty();t.data=dT,this.extensions.push(t.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:i1.type,data:Buffer.alloc(0)});{let t=o1.createEmpty();this.extensions.push(t.extension)}}waitForReady=t=>new Promise(async(e,r)=>{for(let s=0;s<10;s++)if(t()){e();break}else await(0,LL.setTimeout)(100*s);r("waitForReady timeout")});handleFragmentHandshake(t){let e=t.filter(r=>r.fragment_length!==r.length?(this.bufferFragmentedHandshakes.push(r),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[r]=this.bufferFragmentedHandshakes.slice(-1);r.fragment_offset+r.fragment_length===r.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async t=>{let e=rm(this.dtls)([{type:23,fragment:t}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(t,e){let r=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",t*2+e*2),{clientKey:s,serverKey:n,clientSalt:i,serverSalt:o}=(0,Nd.decode)(r,{clientKey:Nd.types.buffer(t),serverKey:Nd.types.buffer(t),clientSalt:Nd.types.buffer(e),serverSalt:Nd.types.buffer(e)});return this.sessionType===Io.CLIENT?{localKey:s,localSalt:i,remoteKey:n,remoteSalt:o}:{localKey:n,localSalt:o,remoteKey:s,remoteSalt:i}}exportKeyingMaterial(t,e){return GX(t,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===Io.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},LE=dt("werift-dtls : packages/dtls/src/client.ts : log"),yC=class extends xT{constructor(t){super(t,Io.CLIENT),this.onHandleHandshakes=this.handleHandshakes,LE(this.dtls.sessionId,"start client")}async connect(){await new dY(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async t=>{LE(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 3:{let r=OL.deSerialize(e.fragment);await new uY(this.transport,this.dtls).exec(r)}break;case 2:{if(this.connected)return;this.flight5=new zY(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let r=[11,12,this.options.certificateRequest&&13].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),LE(this.dtls.sessionId,"dtls connected");break}}},Si=dt("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),YY=(t,e,r,s)=>n=>{Si("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(l=>{switch(l.type){case mC.type:{let f=mC.fromData(l.data).data;Si(e.sessionId,"curves",f);let h=f.filter(m=>aT.includes(m))[0];r.namedCurve=h,Si(e.sessionId,"curve selected",r.namedCurve)}break;case gC.type:{if(!r.signatureHashAlgorithm)throw new Error("need to set certificate");let f=gC.fromData(l.data).data;Si(e.sessionId,"hash,signature",f);let h=f.find(v=>v.signature===r.signatureHashAlgorithm?.signature)?.signature,m=f.find(v=>v.hash===r.signatureHashAlgorithm?.hash)?.hash;if(h==null||m==null)throw new Error("invalid signatureHash")}break;case Yu.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let f=Yu.fromData(l.data);Si(e.sessionId,"srtp profiles",f.profiles);let h=F0.findMatchingSRTPProfile(f.profiles,e.options?.srtpProfiles);if(!h)throw new Error;s.srtpProfile=h,Si(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case i1.type:e.remoteExtendedMasterSecret=!0;break;case o1.type:Si(e.sessionId,"RenegotiationIndication",l.data);break;case 43:{let h=[...l.data.subarray(1)].map(m=>m.toString(10));Si("dtls supported version",h)}break}}),r.localRandom=new Ud,r.remoteRandom=Ud.from(n.random);let i=n.cipherSuites;Si(e.sessionId,"cipher suites",i);let o=(()=>{switch(r.signatureHashAlgorithm?.signature){case Ai.ecdsa_3:return jb.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Ai.rsa_1:return jb.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");r.cipherSuite=o,Si(e.sessionId,"selected cipherSuite",r.cipherSuite),r.localKeyPair=SO(r.namedCurve),e.cookie||=(0,UL.randomBytes)(20);let a=new OL({major:254,minor:253},e.cookie),c=wO(e)([a]),u=rm(e)(c.map(l=>({type:22,fragment:l.serialize()})),++e.recordSequenceNumber).map(l=>l.serialize());for(let l of u)t.send(l)},dN=dt("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),JY=class extends sm{constructor(t,e,r,s){super(t,e,4,6),this.cipher=r,this.srtp=s}async exec(t,e=!1){if(this.dtls.flight===4){dN(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([t],!1,4);let r=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(s=>s);this.dtls.lastMessage=r,await this.transmit(r)}sendServerHello(){let t=[];this.srtp.srtpProfile&&t.push(Yu.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&t.push({type:i1.type,data:Buffer.alloc(0)});let e=o1.createEmpty();t.push(e.extension);let r=new kO(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,t),s=this.createPacket([r]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificate(){let t=new Hb([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerKeyExchange(){let t=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new PO(cT.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,t.length,t),r=this.createPacket([e]);return Buffer.concat(r.map(s=>s.serialize()))}sendCertificateRequest(){let t=new AO(iO,dT,[]);dN(this.dtls.sessionId,"sendCertificateRequest",t);let e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerHelloDone(){let t=new IO,e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}},ef=dt("werift-dtls : packages/dtls/flight/server/flight6.ts"),QY=class extends sm{constructor(t,e,r){super(t,e,6),this.cipher=r}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,5);let e=(()=>{switch(t.msg_type){case 11:return Hb.deSerialize(t.fragment);case 15:return CO.deSerialize(t.fragment);case 16:return TO.deSerialize(t.fragment);case 20:return ZE.deSerialize(t.fragment)}})();if(e){let r=am[e.msgType];if(!r)return;r({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){ef(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let t=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=t,await this.transmit(t)}sendChangeCipherSpec(){let t=EO.createEmpty().serialize(),e=rm(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new ZE(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},am={};am[16]=({cipher:t,dtls:e})=>r=>{if(t.remoteKeyPair={curve:t.namedCurve,publicKey:r.publicKey},!t.remoteKeyPair.publicKey||!t.localKeyPair||!t.remoteRandom||!t.localRandom)throw new Error("not exist");let s=cO(t.remoteKeyPair.publicKey,t.localKeyPair.privateKey,t.localKeyPair.curve);ef(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));t.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?lO(s,n):dO(s,t.remoteRandom.serialize(),t.localRandom.serialize()),t.cipher=vO(t.cipherSuite),t.cipher.init(t.masterSecret,t.localRandom.serialize(),t.remoteRandom.serialize()),ef(e.sessionId,"setup cipher",t.cipher.summary)};am[11]=({cipher:t,dtls:e})=>r=>{ef(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};am[15]=({cipher:t,dtls:e})=>r=>{if(!t.remoteCertificate)throw new Error("client certificate missing before certificate verify");ef(e.sessionId,"certificate_verify",r.algorithm)};am[20]=({dtls:t})=>e=>{ef(t.sessionId,"finished",e)};Uu=dt("werift-dtls : packages/dtls/src/server.ts : log"),ML=class extends xT{constructor(t){super(t,Io.SERVER),this.onHandleHandshakes=this.handleHandshakes,Uu(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async t=>{Uu(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let r=yO.deSerialize(e.fragment);r.cookie.length===0?(Uu(this.dtls.sessionId,"send flight2"),YY(this.transport,this.dtls,this.cipher,this.srtp)(r)):this.dtls.cookie&&r.cookie.equals(this.dtls.cookie)?(Uu(this.dtls.sessionId,"send flight4"),await new JY(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):Uu("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:r.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new QY(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let r=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),Uu(this.dtls.sessionId,"dtls connected")}break}}},d1=554869826,jL=8,FL=1398035790,To=20,bT=24,wT=1,vT=2,HL=6,$L=50,ZY=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],_T=(t=>(t[t.REQUEST=0]="REQUEST",t[t.INDICATION=16]="INDICATION",t[t.RESPONSE=256]="RESPONSE",t[t.ERROR=272]="ERROR",t))(_T||{}),ST=(t=>(t[t.BINDING=1]="BINDING",t[t.SHARED_SECRET=2]="SHARED_SECRET",t[t.ALLOCATE=3]="ALLOCATE",t[t.REFRESH=4]="REFRESH",t[t.SEND=6]="SEND",t[t.DATA=7]="DATA",t[t.CREATE_PERMISSION=8]="CREATE_PERMISSION",t[t.CHANNEL_BIND=9]="CHANNEL_BIND",t))(ST||{});lN=class{queue=[];wait=new Be;put(t){this.queue.push(t),this.queue.length===1&&this.wait.execute(t)}get(){let t=this.queue.shift();return t||new Promise(e=>{this.wait.subscribe(r=>{this.queue.shift(),e(r)})})}},xC=t=>{let e,r,s=new Promise((i,o)=>{e=i,r=o});s.then(()=>{n.execute(void 0),n.complete()}).catch(i=>{n.execute(i??new Error),n.complete()});let n=new Be;return t(e,r,n).catch(()=>{}),{awaitable:s,resolve:e,reject:r}};TT=Buffer.alloc(6);TT.writeUInt16BE(d1>>16,0);TT.writeUInt32BE(d1,2);p0=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t,0),e},m0=t=>t.readUInt32BE(0),rJ=t=>{let e=Buffer.alloc(4);return e.writeUInt16BE(t,0),e},sJ=t=>t.readUInt16BE(0),uN=t=>new xE(t.toString()).toBuffer(),fN=t=>{let e=new xE(t);return BigInt(e.toString())},UE=t=>Buffer.from(t,"utf8"),ME=t=>t.toString("utf8"),jE=t=>t,FE=t=>t,nJ=t=>Buffer.from([]),iJ=t=>null,zL=[[1,"MAPPED-ADDRESS",Hu,$u],[3,"CHANGE-REQUEST",p0,m0],[4,"SOURCE-ADDRESS",Hu,$u],[5,"CHANGED-ADDRESS",Hu,$u],[6,"USERNAME",UE,ME],[8,"MESSAGE-INTEGRITY",jE,FE],[9,"ERROR-CODE",tJ,eJ],[12,"CHANNEL-NUMBER",rJ,sJ],[13,"LIFETIME",p0,m0],[18,"XOR-PEER-ADDRESS",Eb,Sb],[19,"DATA",jE,FE],[20,"REALM",UE,ME],[21,"NONCE",jE,FE],[22,"XOR-RELAYED-ADDRESS",Eb,Sb],[25,"REQUESTED-TRANSPORT",p0,m0],[32,"XOR-MAPPED-ADDRESS",Eb,Sb],[36,"PRIORITY",p0,m0],[37,"USE-CANDIDATE",nJ,iJ],[32802,"SOFTWARE",UE,ME],[32808,"FINGERPRINT",p0,m0],[32809,"ICE-CONTROLLED",uN,fN],[32810,"ICE-CONTROLLING",uN,fN],[32811,"RESPONSE-ORIGIN",Hu,$u],[32812,"OTHER-ADDRESS",Hu,$u]],KL=class{constructor(t=[]){this.attributes=t}getAttributes(){return this.attributes}setAttribute(t,e){let r=this.attributes.find(s=>s[0]===t);return r?r[1]=e:this.attributes.push([t,e]),this}getAttributeValue(t){let e=this.attributes.find(r=>r[0]===t);if(e)return e[1]}get attributesKeys(){return this.attributes.map(t=>t[0])}clear(){this.attributes=[]}},hN=zL.reduce((t,e)=>(t[e[0]]=e,t),{}),oJ=zL.reduce((t,e)=>(t[e[1]]=e,t),{});sn=class extends KL{constructor(t,e,r=VL(),s=[]){super(s),this.messageMethod=t,this.messageClass=e,this.transactionId=r}toJSON(){return this.json}get json(){return{messageMethod:ST[this.messageMethod],messageClass:_T[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let t=Buffer.from([]);for(let r of this.attributesKeys){let s=this.getAttributeValue(r),[n,,i]=oJ[r],o=i.name===Eb.name?i(s,this.transactionId):i(s),a=o.length,c=4*Math.floor((a+3)/4)-a,d=Buffer.alloc(4);d.writeUInt16BE(n,0),d.writeUInt16BE(a,2),t=Buffer.concat([t,d,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(t.length,2),e.writeUInt32BE(d1,4),Buffer.concat([e,this.transactionId,t])}addMessageIntegrity(t){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(t)),this}messageIntegrity(t){let e=AT(this.bytes,this.bytes.length-To+bT);return Buffer.from((0,ET.createHmac)("sha1",t).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",WL(this.bytes))}},AT=(t,e)=>{let r=Buffer.alloc(t.length);return t.copy(r,0,0,2),r.writeUInt16BE(e,2),t.copy(r,4,4),r};GL=class extends Error{response;addr},XL=class extends GL{constructor(t,e){super(),this.response=t,this.addr=e}get str(){let t="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[r,s]=e;t+=` (${r} - ${s})`}return t}},cJ=class extends GL{get str(){return"STUN transaction timed out"}},HE=dt("werift-ice:packages/ice/src/stun/transaction.ts"),kT=class{constructor(t,e,r,s){this.request=t,this.addr=e,this.protocol=r,this.retransmissions=s,this.triesMax=1+(this.retransmissions?this.retransmissions:HL)}timeoutDelay=$L;ended=!1;tries=0;triesMax;onResponse=new Be;responseReceived=(t,e)=>{this.onResponse.length>0&&(t.messageClass===256?(this.onResponse.execute(t,e),this.onResponse.complete()):this.onResponse.error(new XL(t,e)))};run=async()=>{try{return this.retry().catch(e=>{HE("retry failed",e)}),await this.onResponse.asPromise()}catch(t){throw t}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(t=>{HE("send stun failed",t)}),await new Promise(t=>setTimeout(t,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(HE(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new cJ))};cancel(){this.ended=!0}},pN=dt("werift-ice : packages/ice/src/stun/protocol.ts"),Vb=class YL{static type="stun";type=YL.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Be;onDataReceived=new Be;constructor(){}connectionMade=async(e,r,s)=>{e?this.transport=await Mb.init("udp4",{portRange:r,interfaceAddresses:s}):this.transport=await Mb.init("udp6",{portRange:r,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,r){try{let s=l1(e);if(!s){this.localCandidate&&this.onDataReceived.execute(e);return}(s.messageClass===256||s.messageClass===272)&&this.transactionsKeys.includes(s.transactionIdHex)?this.transactions[s.transactionIdHex].responseReceived(s,r):s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){pN("datagramReceived error",s)}}getExtraInfo(){let{address:e,port:r}=this.transport.address;return[e,r]}async sendStun(e,r){if(this.transport.closed)return;let s=e.bytes;await this.transport.send(s,r).catch(()=>{pN("sendStun failed",r,e)})}async sendData(e,r){this.transport.closed||await this.transport.send(e,r)}async request(e,r,s,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");s&&(e.addMessageIntegrity(s),e.addFingerprint());let i=new kT(e,r,this,n);this.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},_s=dt("werift-ice:packages/ice/src/turn/protocol.ts"),dJ=500,lJ=600,uJ=285212672,ZL=class e7{constructor(e){this.turn=e,e.onData.subscribe((r,s)=>{this.handleStunMessage(r,s)}).disposer(this.disposer)}static type="turn";type=e7.type;localCandidate;disposer=new JN;onRequestReceived=new Be;onDataReceived=new Be;handleStunMessage=(e,r)=>{try{let s=l1(e);if(!s){this.onDataReceived.execute(e);return}if(s.messageClass===256||s.messageClass===272){let n=this.turn.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){_s("datagramReceived error",s)}};async request(e,r,s){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");s&&(e.addMessageIntegrity(s),e.addFingerprint());let n=new kT(e,r,this);this.turn.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(i){throw i}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,r){await this.turn.sendData(e,r)}async sendStun(e,r){await this.turn.sendData(e.bytes,r)}async close(){return this.disposer.dispose(),this.turn.close()}},t7=class r7{constructor(e,r,s,n,i,o={}){this.server=e,this.username=r,this.password=s,this.lifetime=n,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??dJ}static type="turn";type=r7.type;onData=new Be;onRequestReceived=new Be;onDataReceived=new Be;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};let e=new sn(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",uJ);let[r]=await this.requestWithRetry(e,this.server).catch(n=>{throw _s("connect error",n),n});this.relayedAddress=r.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=r.getAttributeValue("XOR-MAPPED-ADDRESS");let s=r.getAttributeValue("LIFETIME");_s("connect",this.relayedAddress,this.mappedAddress,{exp:s}),this.refresh(s)}handleChannelData(e){let[r,s]=wC.jspack.Unpack("!HH",e.slice(0,4)),n=this.addrByChannel[r];if(n){let i=e.subarray(4,4+s);this.onData.execute(i,n)}}handleSTUNMessage(e,r){try{let s=l1(e);if(!s)throw new Error("not stun message");if(s.messageClass===256||s.messageClass===272){let n=this.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onData.execute(e,r);if(s.getAttributeValue("DATA")){let n=s.getAttributeValue("DATA");this.onData.execute(n,r)}}catch{_s("parse error",e.toString())}}dataReceived(e,r){let s=(n,i)=>{n.length>=4&&mN(n)?this.handleChannelData(n):this.handleSTUNMessage(n,i)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,n]=os(this.tcpBuffer.subarray(0,4),[2,2]);n+=bC(n);let i=mN(this.tcpBuffer)?4+n:20+n;if(this.tcpBuffer.length<i)break;s(this.tcpBuffer.subarray(0,i),r),this.tcpBuffer=this.tcpBuffer.subarray(i)}else s(e,r)}async send(e,r){if(!this.transport.closed)if(this.transport.type==="tcp"){let s=bC(e.length);await this.transport.send(s>0?Buffer.concat([e,Buffer.alloc(s)]):e,r)}else await this.transport.send(e,r)}async createPermission(e){let r=new sn(8,0);r.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(r,this.server).catch(s=>{throw s})}refresh=e=>{this.refreshHandle=xC(async(r,s,n)=>{let i=!0;for(n.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;_s("refresh delay",o,{exp:e}),await(0,QL.setTimeout)(o);let a=new sn(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),_s("refresh",{exp:e})}catch(c){_s("refresh error",c)}}})};async request(e,r){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let s=new kT(e,r,this);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(n){throw n}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,r){let s,n;try{[s,n]=await this.request(e,r)}catch(i){if(!(i instanceof XL))throw _s("requestWithRetry error",i),i;this.server=i.addr;let[o]=i.response.getAttributeValue("ERROR-CODE"),a=i.response.getAttributeValue("NONCE"),c=i.response.getAttributeValue("REALM");if((o===401&&c||o===438&&this.realm)&&a)_s("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=n7(this.username,this.realm,this.password),e.transactionId=VL(),[s,n]=await this.request(e,this.server);else throw i}return[s,n]}async sendData(e,r){let s=await this.getChannel(r).catch(i=>new Error("channelBind error"));if(s instanceof Error){await this.getPermission(r);let i=new sn(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",r);await this.sendStun(i,this.server);return}let n=wC.jspack.Pack("!HH",[s.number,e.length]);await this.send(Buffer.concat([Buffer.from(n),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(s=>{throw _s("createPermission error",s),s}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let r=this.channelByAddr[e.join(":")];return r?this.channelRefreshAt<Ku(Date.now()/1e3)&&(this.channelBinding=this.channelBind(r.number,e),this.channelRefreshAt=Ku(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(s=>{throw _s("channelBind error",s),s}),this.channelBinding=void 0,_s("channelBind refresh",r)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},r=this.channelByAddr[e.join(":")],this.addrByChannel[r.number]=e,this.channelBinding=this.channelBind(r.number,e),await this.channelBinding.catch(s=>{throw _s("channelBind error",s),s}),this.channelRefreshAt=Ku(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,_s("channelBind",r)),r}async channelBind(e,r){let s=new sn(9,0);s.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",r);let[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,r){await this.send(e.bytes,r)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};Ga=class o7{constructor(e,r,s,n,i,o,a,c,d,u,l,f){this.foundation=e,this.component=r,this.transport=s,this.priority=n,this.host=i,this.port=o,this.type=a,this.relatedAddress=c,this.relatedPort=d,this.tcptype=u,this.generation=l,this.ufrag=f}static fromSdp(e){let r=e.split(" ");if(r.length<8)throw new Error("SDP does not have enough properties");let s={foundation:r[0],component:Number(r[1]),transport:r[2],priority:Number(r[3]),host:r[4],port:Number(r[5]),type:r[7]};for(let l=8,f=r.length-1;l<f;l+=2)r[l]==="raddr"?s.related_address=r[l+1]:r[l]==="rport"?s.related_port=Number(r[l+1]):r[l]==="tcptype"?s.tcptype=r[l+1]:r[l]==="generation"?s.generation=Number(r[l+1]):r[l]==="ufrag"&&(s.ufrag=r[l+1]);let{foundation:n,component:i,transport:o,priority:a,host:c,port:d,type:u}=s;return new o7(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let r=(0,_C.isIPv4)(this.host),s=(0,_C.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&r===s}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}};fJ=class{cache=new Map;mdnsInstance=(0,c7.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(t){return new Promise((e,r)=>{let s=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(n)},n=setTimeout(()=>{s(),r(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===t&&(s(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(t,"A")})}close(){this.mdnsInstance.destroy()}},hJ=dt("werift-ice : packages/ice/src/ice.ts : log"),CC=class{constructor(t,e,r){this.protocol=t,this.remoteCandidate=e,this.iceControlling=r}id=(0,d7.randomUUID)().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(t){this._state=t}get localCandidate(){if(!this.protocol.localCandidate)throw new Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return zb(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},TC=1,I0=2,l7=5,AC=6,u7=(t=>(t[t.FROZEN=0]="FROZEN",t[t.WAITING=1]="WAITING",t[t.IN_PROGRESS=2]="IN_PROGRESS",t[t.SUCCEEDED=3]="SUCCEEDED",t[t.FAILED=4]="FAILED",t))(u7||{}),f7={useIpv4:!0,useIpv6:!0};pJ=dt("werift-ice : packages/ice/src/utils.ts");gJ=t=>{if(!t)return;let[e,r]=t.split(":");return[e,Number.parseInt(r)]},Ut=dt("werift-ice : packages/ice/src/ice.ts : log"),b7=class{constructor(t,e){this._iceControlling=t,this.options={...f7,...e};let{stunServer:r,turnServer:s}=this.options;this.stunServer=IC(r)??["stun.l.google.com",19302],this.turnServer=IC(s),this.restart(),Ut("new Connection",this.options)}localUsername=h0(4);localPassword=h0(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new lb((0,a7.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new lN;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Be;stateChanged=new Be;onIceCandidate=new Be;get iceControlling(){return this._iceControlling}set iceControlling(t){if(!(this.generation>0||this.nominated)){this._iceControlling=t;for(let e of this.checkList)e.iceControlling=t}}async restart(){this.generation++,this.localUsername=h0(4),this.localPassword=h0(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 lN,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let t of this.protocols)t.localCandidate&&(t.localCandidate.generation=this.generation,t.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){Ut("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:t,usernameFragment:e,password:r}){Ut("setRemoteParams",{iceLite:t,usernameFragment:e,password:r}),this.remoteIsLite=t,this.remoteUsername=e,this.remotePassword=r}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let t=x7(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let s=t.filter(n=>Object.values(e).includes(n));s.length&&(t=s)}this.options.additionalHostAddresses&&(t=Array.from(new Set([...this.options.additionalHostAddresses,...t])));let r=this.getCandidatePromises(t,5);await Promise.allSettled(r),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(t){this.localCandidates.push(t),this.onIceCandidate.execute(t)}ensureProtocol(t){t.onRequestReceived.subscribe((e,r,s)=>{if(e.messageMethod!==1){this.respondError(e,r,t,[400,"Bad Request"]);return}let n=e.getAttributeValue("USERNAME"),{remoteUsername:i}=gN(n),o=this.userHistory[i]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,r,t,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,r,t,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,r,t))return;let c=new sn(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",r).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),t.sendStun(c,r).catch(d=>{Ut("sendStun error",d)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,r,t]):this.checkIncoming(e,r,t)}),t.onDataReceived.subscribe(e=>{try{let r=this.nominated;r&&r.protocol===t&&(r.packetsReceived++,r.bytesReceived+=e.length),this.onData.execute(e)}catch(r){Ut("dataReceived",r)}})}getCandidatePromises(t,e=5){let r=[];t=t.filter(c=>!this.protocols.find(d=>d.localIp===c));let s=t.map(async c=>{let d=new Vb;this.ensureProtocol(d);try{await d.connectionMade((0,SC.isIPv4)(c),this.options.portRange,this.options.interfaceAddresses),d.localIp=c,this.protocols.push(d),Ut("protocol",d.localIp);let u=[c,d.getExtraInfo()[1]];return d.localCandidate=new Ga(qb("host","udp",u[0]),1,"udp",D0("host"),u[0],u[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(d),this.appendLocalCandidate(d.localCandidate),d}catch(u){Ut("error protocol STUN",u)}});r.push(...s.map(c=>c.then(d=>d?.localCandidate)));let{stunServer:n,turnServer:i}=this;if(n){let c=s.map(async d=>{let u=await d;return u?new Promise(async(f,h)=>{let m=setTimeout(h,e*1e3);if(u.localCandidate?.host&&(0,SC.isIPv4)(u.localCandidate?.host)){let v=await p7(u,n).catch(p=>{Ut("error",p)});v&&this.appendLocalCandidate(v),clearTimeout(m),f(v)}else clearTimeout(m),f()}).catch(f=>{Ut("query STUN server",f)}):void 0});r.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let d=await vC({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async f=>{if(this.options.turnTransport!=="tcp")return await vC({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw f});this.ensureProtocol(d),this.protocols.push(d);let u=d.turn.relayedAddress,l=d.turn.mappedAddress;return Ut("turn candidateAddress",u),d.localCandidate=new Ga(qb("relay","udp",u[0]),1,"udp",D0("relay"),u[0],u[1],"relay",l[0],l[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(d.localCandidate),d.localCandidate})().catch(d=>{Ut("query TURN server",d)});this.options.forceTurn&&(r=[]),r.push(c)}return r}async connect(){if(Ut("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),Ut("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await EC.setTimeout(20);let t=I0;for(;this.checkList.length>0&&t===I0;)t=await this.checkListState.get(),Ut("checkListState",t);for(let e of this.checkList)e.handle?.resolve?.();if(t!==TC)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[t]=this.checkList;if(!t)return;t.state===0&&t.updateState(1);let e=new Set(t.localCandidate.foundation);for(let r of this.checkList)r.component===t.component&&!e.has(r.localCandidate.foundation)&&r.state===0&&(r.updateState(1),e.add(r.localCandidate.foundation))}schedulingChecks(){{let t=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===Vb.type)).find(e=>e.state===1);if(t)return t.handle=this.checkStart(t),!0}{let t=this.checkList.find(e=>e.state===0);if(t)return t.handle=this.checkStart(t),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=xC(async(t,e,r)=>{let s=0,n=!1,i=new AbortController;r.once(()=>{n=!0,s+=AC,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await EC.setTimeout(l7*(.8+.4*Math.random())*1e3,void 0,{signal:i.signal});let d=this.nominated;if(!d||n)break;let u=this.buildRequest({nominate:!1,localUsername:o,remoteUsername:a,iceControlling:c});try{await d.protocol.request(u,d.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),s=0,this.state==="disconnected"&&this.setState("connected")}catch{if(d.id===this.nominated?.id){Ut("no stun response"),s++,this.setState("disconnected");break}}if(s>=AC){Ut("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(t=>{t(I0)})),this.nominated=void 0;for(let t of this.protocols)t.close&&await t.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(t){this.state=t,this.stateChanged.execute(t)}async addRemoteCandidate(t){if(!t){this.remoteCandidatesEnd=!0;return}if(t.host.includes(".local"))try{this.lookup||(this.lookup=new fJ);let e=await this.lookup.lookup(t.host);t.host=e}catch{return}try{kC(t)}catch{return}Ut("addRemoteCandidate",t),this._remoteCandidates.push(t),this.pairRemoteCandidate(t),this.sortCheckList()}send=async t=>{let e=this.nominated;if(e)await e.protocol.sendData(t,e.remoteAddr),e.packetsSent++,e.bytesSent+=t.length;else return};getDefaultCandidate(){let t=this.localCandidates.sort((r,s)=>r.priority-s.priority),[e]=t;return e}set remoteCandidates(t){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of t){try{kC(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){h7(this.checkList,this.iceControlling)}findPair(t,e){return this.checkList.find(s=>(0,Cb.default)(s.protocol,t)&&(0,Cb.default)(s.remoteCandidate,e))}switchRole(t){Ut("switch role",t),this.iceControlling=t,this.sortCheckList()}checkComplete(t){if(t.handle=void 0,t.state===3){if(t.nominated&&(t.remoteCandidate.generation==null||t.remoteCandidate.generation===this.generation)&&this.nominated==null){Ut("nominated",t.toJSON()),this.nominated=t,this.nominating=!1;for(let e of this.checkList)e.component===t.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(Ut("ICE completed"),this.checkListState.put(new Promise(e=>e(TC))),this.checkListDone=!0);return}Ut("not completed",t.toJSON());for(let e of this.checkList)e.localCandidate.foundation===t.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:r})=>!e.includes(r)))return}!this.iceControlling&&this.checkList.find(({state:r})=>r===3)||this.checkListDone||(Ut("ICE failed"),this.checkListState.put(new Promise(e=>{e(I0)})))}checkStart=t=>xC(async e=>{Ut("check start",t.toJSON()),t.updateState(2);let r={},{remotePassword:s,remoteUsername:n,generation:i}=this,o=t.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling}),d=performance.now();try{let[u,l]=await t.protocol.request(c,t.remoteAddr,Buffer.from(s,"utf8"),4),h=(performance.now()-d)/1e3;t.rtt=h,t.totalRoundTripTime+=h,t.roundTripTimeMeasurements++,Ut("response received",c.toJSON(),u.toJSON(),l,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i,rtt:h}),r.response=u,r.addr=l}catch(u){let l=u;if(Ut("failure case",c.toJSON(),l.response?JSON.stringify(l.response.toJSON(),null,2):u,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i},t.remoteAddr),l.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(t).awaitable,e();return}if(l.response?.getAttributeValue("ERROR-CODE")[0]===401){Ut("retry 401",t.toJSON()),await this.checkStart(t).awaitable,e();return}else{Ut("checkStart CandidatePairState.FAILED",t.toJSON()),t.updateState(4),this.checkComplete(t),e();return}}if(!(0,Cb.default)(r.addr,t.remoteAddr)){t.updateState(4),this.checkComplete(t),e();return}if(a||t.remoteNominated)t.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let u=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling});try{await t.protocol.request(u,t.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{t.updateState(4),this.checkComplete(t);return}t.nominated=!0}t.updateState(3),this.checkComplete(t),e()});addPair(t){this.checkList.push(t),this.sortCheckList()}checkIncoming(t,e,r){let s=t.getAttributeValue("USERNAME"),{remoteUsername:n}=gN(s),i,[o,a]=e;for(let d of this.remoteCandidates)if(d.host===o&&d.port===a){i=d;break}i||(i=new Ga(h0(10),1,"udp",t.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(r,i);c||(c=new CC(r,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=n,Ut("Triggered Checks",t.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),t.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(t,e){if(t.localCandidate?.canPairWith(e)&&!this.findPair(t,e)){let r=new CC(t,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(r))return;r.updateState(1),this.addPair(r)}}pairLocalProtocol(t){for(let e of this.remoteCandidates)this.tryPair(t,e)}pairRemoteCandidate=t=>{for(let e of this.protocols)this.tryPair(e,t)};buildRequest({nominate:t,remoteUsername:e,localUsername:r,iceControlling:s}){let n=yJ({remoteUsername:e,localUsername:r}),i=new sn(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",D0("prflx")),s?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),t&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(t,e,r,s){let n=new sn(t.messageMethod,272,t.transactionId);n.setAttribute("ERROR-CODE",s).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),r.sendStun(n,e).catch(i=>{Ut("sendStun error",i)})}},yJ=({remoteUsername:t,localUsername:e})=>`${t}:${e}`,gN=t=>{let[e,r]=t.split(":");return{remoteUsername:e,localUsername:r}};IT=class extends w7.EventEmitter{addEventListener=(t,e)=>{this.addListener(t,e)};removeEventListener=(t,e)=>{this.removeListener(t,e)}},xJ=dt("werift:packages/webrtc/src/dataChannel.ts");RT=class extends IT{constructor(t,e,r=!0){if(super(),this.sctp=t,this.parameters=e,this.sendOpen=r,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else r&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Be;stateChanged=new Be;onMessage=new Be;error=new Be;bufferedAmountLow=new Be;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(t){if(t<0||t>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=t}setId(t){this.id=t}setReadyState(t){if(t!==this.readyState){switch(this.readyState=t,this.stateChange.execute(t),this.stateChanged.execute(t),t){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}xJ("change state",t)}}addBufferedAmount(t){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+t<=this.bufferedAmountLowThreshold;this.bufferedAmount+=t,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(t){let e=this.sctp.datachannelSend(this,t);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},PT=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(t={}){Object.assign(this,t)}},bJ=()=>({type:"ccm",parameter:"fir"}),cm=()=>({type:"nack"}),af=()=>({type:"nack",parameter:"pli"}),dm=()=>({type:"goog-remb"}),_7=()=>({type:"transport-cc"}),Xa=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(t){Object.assign(this,t)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let t=`${this.name}/${this.clockRate}`;return this.channels===2&&(t+="/2"),t}},ki=class{id;uri;constructor(t){Object.assign(this,t)}},wJ=class{cname;mux=!1;ssrc;constructor(t={}){Object.assign(this,t)}},S7=class{type;parameter;constructor(t={}){Object.assign(this,t)}},E7=class{ssrc;constructor(t={}){Object.assign(this,t)}},C7=class{ssrc;payloadType;rtx;constructor(t){Object.assign(this,t)}},BT=class{rid;direction;constructor(t){Object.assign(this,t)}},T7=(t={})=>new Xa({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[cm(),af(),dm()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...t}),DT=(t={})=>new Xa({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[cm(),af(),dm()],...t}),A7=(t={})=>new Xa({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[cm(),af(),dm()],...t}),k7=(t={})=>new Xa({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[cm(),af(),dm()],...t}),NT=(t={})=>new Xa({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...t}),OT=(t={})=>new Xa({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...t}),LT=[k7(),A7(),DT(),T7(),NT(),OT()].map(t=>t.mimeType),vJ=LT.filter(t=>t.toLowerCase().startsWith("video/")),_J=LT.filter(t=>t.toLowerCase().startsWith("audio/"));xN=2,bN=3,PJ=0,mb=50,wN=51,vN=53,BJ=56,DJ=57,NJ="0.0.0.0",_N=9,BC={auto:"actpass",client:"active",server:"passive"},SN=Object.keys(BC).reduce((t,e)=>{let r=BC[e];return t[r]=e,t},{}),OJ=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],D7=["cname","msid","mslabel","label"],EN={SRTP_AES128_CM_HMAC_SHA1_80:nf,SRTP_AEAD_AES_128_GCM:Kd},Ab=["sendonly","sendrecv"],LJ=["sendrecv","recvonly"],N7=class extends Map{constructor(t){if(super(),t)for(let e of t)this.set(e.id,e)}};O7=class{constructor(t,e,r,s,n){this.kind=t,this.receiver=r,this.sender=s,this._direction=n,e&&this.setDtlsTransport(e)}id=(0,B7.randomUUID)().toString();onTrack=new Be;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(t){this._codecs=t}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(t){this._direction=t,Ab.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(t){this._currentDirection=t}setDtlsTransport(t){this.receiver.setDtlsTransport(t),this.sender.setDtlsTransport(t)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(t){this.receiver.addTrack(t)&&this.onTrack.execute(t,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(t){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(t.toLowerCase()))?.payloadType}getCodecStats(){let t=Ya(),e=[];if(!this.dtlsTransport)return e;let r=Ft("transport",this.dtlsTransport.id);for(let s of this.codecs){let n={type:"codec",id:Ft("codec",s.payloadType,r),timestamp:t,payloadType:s.payloadType,transportId:r,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,sdpFmtpLine:s.parameters};e.push(n)}return e}},L7="inactive",UT="sendonly",MT="recvonly",jT="sendrecv",kb=[L7,UT,MT,jT],Y0=class extends IT{uuid=(0,FT.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Be;onReceiveRtcp=new Be;onSourceChanged=new Be;stopped=!1;muted=!0;constructor(t){super(),Object.assign(this,t),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=t=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(t)?Bo.deSerialize(t):t;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},U7=class{id;tracks=[];constructor(t){Array.isArray(t)?this.tracks=t:Object.assign(this,t),this.id??=(0,FT.randomUUID)().toString()}addTrack(t){t.streamId=this.id,this.tracks.push(t)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(t=>t.kind==="audio")}getVideoTracks(){return this.tracks.filter(t=>t.kind==="video")}},UJ=dt("werift:packages/webrtc/src/utils.ts");MJ={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"};VT=(t,e)=>kb[kb.indexOf(t)&kb.indexOf(e)];qT=Date.now,FJ=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,F7=()=>FJ+process.hrtime.bigint()/1000n,J0=()=>Date.now()/1e3,H7=()=>{let e=(PC.performance.timeOrigin+PC.performance.now()-Date.UTC(1900,0,1))/1e3,[r,s]=e.toString().split(".").map(Number);return tr([4,4],[r,s]).readBigUInt64BE()},zT=t=>{let e=tr([8],[t]),[,r,s]=os(e,[2,2,2,2]);return tr([2,2],[r,s]).readUInt32BE()};HJ=j0.createSelfSignedCertificateWithKey,$J=class{static async rtpSource({port:t,kind:e,cb:r}){t??=await oT();let s=new Y0({kind:e}),n=(0,P7.createSocket)("udp4");n.bind(t);let i=a=>{r&&(a=r(a)),s.writeRtp(a)};return n.addListener("message",i),[s,t,()=>{n.removeListener("message",i);try{n.close()}catch{}}]}},V7=(t,e)=>{if(!t||typeof t!="object")return e!==null&&typeof e=="object"?e:t;if(!e||typeof e!="object")return e??t;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let s=e[r];s!=null&&(t[r]=s)}return t},VJ=dt("werift:packages/webrtc/src/media/receiver/nack.ts"),CN=150,qJ=class{constructor(t){this.receiver=t}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Be;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(t){return this._lost[t]}setLost(t,e){this._lost[t]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(r){VJ("failed to send nack",r)}},5))}removeLost(t){delete this._lost[t]}addPacket(t){let{sequenceNumber:e,ssrc:r}=t.header;if(this.mediaSourceSsrc=r,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===$r(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>$r(this.newEstSeqNum,1)){for(let s=$r(this.newEstSeqNum,1);s<e;s=$r(s,1))this.setLost(s,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>CN&&(this._lost=Object.entries(this._lost).slice(-CN).reduce((t,[e,r])=>(t[e]=r,t),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(t=>{if(this._lost[t]++>this.retryCount)return this.removeLost(t),t})}sendNack=()=>new Promise((t,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let r=new z0({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),s=new Hd({feedback:r});this.receiver.dtlsTransport.sendRtcp([s]).then(t).catch(e),this.updateRetryCount(),this.onPacketLost.execute(r)}})},zJ=dt("werift:packages/webrtc/media/receiver/receiverTwcc"),KJ=class{constructor(t,e,r){this.dtlsTransport=t,this.rtcpSsrc=e,this.mediaSourceSsrc=r,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(t){this.extensionInfo[t]={tsn:t,timestamp:F7()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,q7.setTimeout)(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let t=Object.values(this.extensionInfo).sort((u,l)=>u.tsn-l.tsn),e=t[0].tsn,r=t.slice(-1)[0].tsn,s=[],n=t[0].tsn,i=$r(r-e,1),o,a,c=[];for(let u=e;u<=r;u++){let l=this.extensionInfo[u]?.timestamp;if(l){this.lastTimestamp||(this.lastTimestamp=l),o||(o=this.lastTimestamp);let f=l-this.lastTimestamp;this.lastTimestamp=l;let h=new B0({delta:Number(f)});h.parseDelta(),c.push(h),a!=null&&a.status!==h.type&&(s.push(new Gu({packetStatus:a.status,runLength:u-a.minTSN})),a={minTSN:u,status:h.type}),u===r&&(a!=null?s.push(new Gu({packetStatus:a.status,runLength:u-a.minTSN+1})):s.push(new Gu({packetStatus:h.type,runLength:1}))),a==null&&(a={minTSN:u,status:h.type})}}if(!o)return;let d=new Hd({feedback:new K0({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:GN(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{zJ(u)}),this.extensionInfo={},this.fbPktCount=WN(this.fbPktCount,1)}},WJ=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(t){this.clockRate=t}add(t,e=Date.now()/1e3){let r=this.max_seq==null||Zb(t.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=t.header.sequenceNumber),r){let s=Ku(e*this.clockRate);if(this.max_seq!=null&&t.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=t.header.sequenceNumber,t.header.timestamp!==this.last_timestamp&&this.packets_received>1){let n=Math.abs(s-(this.last_arrival??0)-(t.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=s,this.last_timestamp=t.header.timestamp}}get fraction_lost(){let t=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let r=t-e;return t==0||r<=0?0:Math.floor((r<<8)/t)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let t=this.packets_expected-this.packets_received;return t<0?0:t}},Rn=dt("werift:packages/webrtc/src/transport/dtls.ts"),DC=class X7{constructor(e,r,s,n=[]){this.config=e,this.iceTransport=r,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=X7.localCertificate}id=(0,W7.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Be;onRtcp=new Be;onRtp=new Be;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new Gb(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:r,signatureHash:s}=await j0.createSelfSignedCertificateWithKey({signature:Ai.ecdsa_3,hash:M0.sha256_4},Ro.secp256r1_23);return this.localCertificate=new KT(r,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let r=XJ([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new Gb(r,s)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,r)=>{this.role==="server"?this.dtls=new ML({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:TN(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new yC({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:TN(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(s=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(s)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(s=>{this.setState("failed"),Rn("dtls failed",s),r(s)}),this.dtls instanceof yC&&(await(0,G7.setTimeout)(100),this.dtls.connect().catch(s=>{this.setState("failed"),Rn("dtls connect failed",s),r(s)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),Rn("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let r=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let d=$T(a);if(!d)return[];let u=Kb(c);if(!u)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:d,normalizedValue:u}]});if(r.length===0)throw new Error("no supported remote fingerprint algorithms");let s=JJ(r),n=r.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,Kb(HT(e,c))),a),new Map);if(!n.some(({normalizedAlgorithm:a,normalizedValue:c})=>i.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");Rn("selected SRTP Profile",e);let{localKey:r,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(BO(e),DO(e)),o={keys:{localMasterKey:r,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new NL(o),this.srtcp=new DL(o)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&GO(e))if(this.bytesReceived+=e.length,this.packetsReceived++,cL(e)){let r;try{r=this.srtcp.decrypt(e)}catch(n){if(n instanceof Vd){Rn("dropping invalid SRTCP packet",n);return}throw n}let s;try{s=aL.deSerialize(r)}catch(n){Rn("dropping malformed SRTCP packet",n);return}for(let n of s)try{this.onRtcp.execute(n)}catch(i){Rn("RTCP error",i)}}else{let r;try{r=this.srtp.decrypt(e)}catch(n){if(n instanceof Vd){Rn("dropping invalid SRTP packet",n);return}throw n}let s;try{s=Bo.deSerialize(r)}catch(n){Rn("dropping malformed SRTP packet",n);return}try{this.onRtp.execute(s)}catch(n){Rn("RTP error",n)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,r){try{let s=this.srtp.encrypt(e,r);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})),s.length}catch(s){return Rn("failed to send",s),0}}async sendRtcp(e){let r=Buffer.concat(e.map(n=>n.serialize())),s=this.srtcp.encrypt(r);if(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())return s.length;this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})}setState(e){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=Ya(),r=[],n={type:"transport",id:Ft("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?Ft("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?Ft("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?Ft("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(r.push(n),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:Ft("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};r.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:Ft("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};r.push(o)}let i=await this.iceTransport.getStats();return r.push(...i),r}},GJ=["new","connecting","connected","closed","failed"],KT=class{constructor(t,e,r){this.certPem=e,this.signatureHash=r;let s=Q0.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=Q0.PrivateKey.fromPEM(Buffer.from(t)).toPEM()}publicKey;privateKey;getFingerprints(){return[new Wb("sha-256",HT(Q0.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},Wb=class{constructor(t,e){this.algorithm=t,this.value=e}},Gb=class{constructor(t=[],e){this.fingerprints=t,this.role=e}},XJ=t=>{let e=new Set;return t.filter(({algorithm:r,value:s})=>{let n=`${$T(r)??r.trim().toLowerCase()}:${Kb(s)}`;return e.has(n)?!1:(e.add(n),!0)})},YJ=["sha512","sha384","sha256","sha224","sha1"],JJ=t=>YJ.find(e=>t.some(({normalizedAlgorithm:r})=>r===e))??t[0].normalizedAlgorithm,QJ=class{constructor(t){this.ice=t,t.onData.subscribe(e=>{M7(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=t=>this.ice.send(t);async close(){this.closed=!0,this.ice.close()}},TN=t=>new QJ(t),AN=dt("werift:packages/webrtc/src/transport/ice.ts"),J7=class{constructor(t){this.iceGather=t,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=(0,Y7.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Be;onIceCandidate=new Be;onNegotiationNeeded=new Be;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(t){t!==this.state&&(this.state=t,this.onStateChange.execute(t))}gather(){return this.iceGather.gather()}addRemoteCandidate=t=>{if(!this.connection.remoteCandidatesEnd)return t?this.connection.addRemoteCandidate(Z7(t)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(t,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==t.usernameFragment||this.connection.remotePassword!==t.password)&&(this.renominating?(AN("renomination",t),this.connection.resetNominatedPair(),this.renominating=!1):(AN("restart",t),this.restart())),this.connection.setRemoteParams(t)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new Be,this.setState("checking");try{await this.connection.connect()}catch(t){throw this.setState("failed"),t}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let t=Ya(),e=[];for(let s of this.localCandidates){let n={type:"local-candidate",id:Ft("local-candidate",s.foundation),timestamp:t,transportId:Ft("transport",this.id),address:s.ip,port:s.port,protocol:s.protocol,candidateType:s.type,priority:s.priority,foundation:s.foundation};e.push(n)}for(let s of this.connection.remoteCandidates){let n=tf(s),i={type:"remote-candidate",id:Ft("remote-candidate",n.foundation),timestamp:t,transportId:Ft("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(s=>s.nominated),...this.connection.candidatePairs.filter(s=>!s.nominated)]:[];for(let s of r){let n={type:"candidate-pair",id:Ft("candidate-pair",s.foundation),timestamp:t,transportId:Ft("transport",this.id),localCandidateId:Ft("local-candidate",s.localCandidate.foundation),remoteCandidateId:Ft("remote-candidate",s.remoteCandidate.foundation),state:s.state,nominated:s.nominated,packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived,currentRoundTripTime:s.rtt};e.push(n)}return e}},ZJ=["new","checking","connected","completed","disconnected","failed","closed"],eQ=["new","gathering","complete"],Q7=class{constructor(t={}){this.options=t,this.connection=new b7(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(tf(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Be;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(tf)}get localParameters(){return new GT({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(t){t!==this.gatheringState&&(this.gatheringState=t,this.onGatheringStateChange.execute(t))}};eU=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(t){Object.assign(this,t)}static fromSdp(t){let e=Ga.fromSdp(t);return tf(e).toJSON()}static isThis(t){if(typeof t?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},WT=class{constructor(t,e,r,s,n,i,o,a,c){this.component=t,this.foundation=e,this.ip=r,this.port=s,this.priority=n,this.protocol=i,this.type=o,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new eU({candidate:JT(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(t){try{if(!t.candidate)throw new Error("candidate is required");let e=QT(t.candidate);return e.sdpMLineIndex=t.sdpMLineIndex??void 0,e.sdpMid=t.sdpMid??void 0,e}catch{}}},GT=class{iceLite=!1;usernameFragment;password;constructor(t={}){Object.assign(this,t)}},Ii=class rU{constructor(e=0,r=Buffer.from("")){this.flags=e,this._body=r}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return rU.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(um(this.body.length))].map(()=>Buffer.from("\0"))])}},XT=class extends Ii{constructor(t=0,e){super(t,e),this.flags=t,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=SU(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let t=Buffer.alloc(16);return t.writeUInt32BE(this.initiateTag,0),t.writeUInt32BE(this.advertisedRwnd,4),t.writeUInt16BE(this.outboundStreams,8),t.writeUInt16BE(this.inboundStreams,10),t.writeUInt32BE(this.initialTsn,12),Buffer.concat([t,_U(this.params)])}},Pb=class sU extends XT{static type=1;get type(){return sU.type}},NC=class nU extends XT{static type=2;get type(){return nU.type}},tQ=class iU extends XT{static type=130;get type(){return iU.type}},Bb=class oU extends Ii{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0);let s=4;for(;s<r.length;)this.streams.push([r.readUInt16BE(s),r.readUInt16BE(s+2)]),s+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return oU.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([r,s])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(r,0),n.writeUInt16BE(s,2),n})])}},Db=class aU extends Ii{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.tsn=r.readUInt32BE(0),this.streamId=r.readUInt16BE(4),this.streamSeqNum=r.readUInt16BE(6),this.protocol=r.readUInt32BE(8),this.userData=r.slice(12))}static type=0;get type(){return aU.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.tsn,4),r.writeUInt16BE(this.streamId,8),r.writeUInt16BE(this.streamSeqNum,10),r.writeUInt32BE(this.protocol,12);let s=Buffer.concat([r,this.userData]);return e%4&&(s=Buffer.concat([s,...[...Array(um(e))].map(()=>Buffer.from("\0"))])),s}},OC=class cU extends Ii{static type=10;get type(){return cU.type}},LC=class dU extends Ii{static type=11;get type(){return dU.type}},lm=class extends Ii{constructor(t=0,e=void 0){super(t,e),this.flags=t,e&&(this.params=SU(e))}params=[];get body(){return _U(this.params)}},UC=class lU extends lm{static type=6;get type(){return lU.type}},Nb=class MC extends lm{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 MC.type}get descriptions(){return this.params.map(([e,r])=>({name:(Object.entries(MC.CODE).find(([,n])=>n===e)||[])[0],body:r}))}},jC=class uU extends lm{static type=4;get type(){return uU.type}},fU=class hU extends lm{static type=5;get type(){return hU.type}},FC=class pU extends lm{static type=130;get type(){return pU.type}},HC=class mU extends Ii{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0),this.advertisedRwnd=r.readUInt32BE(4);let s=r.readUInt16BE(8),n=r.readUInt16BE(10),i=12;[...Array(s)].forEach(()=>{this.gaps.push([r.readUInt16BE(i),r.readUInt16BE(i+2)]),i+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(r.readUInt32BE(i)),i+=4})}}static type=3;get type(){return mU.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.cumulativeTsn,4),r.writeUInt32BE(this.advertisedRwnd,8),r.writeUInt16BE(this.gaps.length,12),r.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([r,...this.gaps.map(n=>{let i=Buffer.alloc(4);return i.writeUInt16BE(n[0],0),i.writeUInt16BE(n[1],2),i})]);return s=Buffer.concat([s,...this.duplicates.map(n=>{let i=Buffer.alloc(4);return i.writeUInt32BE(n,0),i})]),s}},gU=class yU extends Ii{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.cumulativeTsn=r.readUInt32BE(0))}static type=7;get type(){return yU.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},xU=class bU extends Ii{static type=8;get type(){return bU.type}},wU=class vU extends Ii{static type=14;get type(){return vU.type}},rQ=[Db,Pb,NC,HC,jC,fU,UC,gU,xU,Nb,OC,LC,wU,FC,Bb],sQ=rQ.reduce((t,e)=>(t[e.type]=e,t),{});$C=class VC{constructor(e,r,s,n){this.requestSequence=e,this.responseSequence=r,this.lastTsn=s,this.streams=n}static type=13;get type(){return VC.type}get bytes(){let e=Buffer.from(ko.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(r=>Buffer.from(ko.jspack.Pack("!H",[r])))])}static parse(e){let[r,s,n]=ko.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(ko.jspack.Unpack("!H",e.slice(o))[0]);return new VC(r,s,n,i)}},EU=class qC{constructor(e,r){this.requestSequence=e,this.newStreams=r}static type=17;get type(){return qC.type}get bytes(){return Buffer.from(ko.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[r,s]=ko.jspack.Unpack("!LHH",e);return new qC(r,s)}},gb={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Ob=class zC{constructor(e,r){this.responseSequence=e,this.result=r}static type=16;get type(){return zC.type}get bytes(){return Buffer.from(ko.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[r,s]=ko.jspack.Unpack("!LL",e);return new zC(r,s)}},kN={13:$C,16:Ob,17:EU},Nt=dt("werift/sctp/sctp"),cQ=24,dQ=60,IN=65535,Pn=1200,R0=1,CU=2,KC=4,RN=10,lQ=8,PN=1/8,BN=1/4,DN=3,uQ=1,fQ=60,Xb=2**32,hQ=200,pQ=30,NN=135,ON=7,LN=32776,UN=49152,mQ=["new","closed","connected","connecting"],gQ=class WC{constructor(e,r=5e3){this.transport=e,this.port=r,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Be;stateChanged=aQ(mQ);onReconfigStreams=new Be;onReceive=new Be;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,Z0.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Ub();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=IN;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*Pn;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=IN;localTsn=Number(Ub());lastSackedTsn=Dd(this.localTsn);advancedPeerAckTsn=Dd(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=DN;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=pQ;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,r=5e3){let s=new WC(e,r);return s.isServer=!1,s}static server(e,r=5e3){let s=new WC(e,r);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let r,[,,s,n]=nQ(e);if(n.filter(o=>o.type===Pb.type).length>0){if(n.length!=1)throw new Error;r=0}else r=this.localVerificationTag;if(s===r){this.sackHasNewDataInPacket=!1;for(let o of n)await this.receiveChunk(o);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{Nt("send delayed sack failed",e.message)})},hQ))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],r;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%Xb;n===r?e[e.length-1][1]=i:e.push([i,i]),r=Vu(n)});let s=new HC(0,void 0);s.cumulativeTsn=this.lastReceivedTsn,s.advertisedRwnd=Math.max(0,this.advertisedRwnd),s.duplicates=[...this.sackDuplicates],s.gaps=e,await this.sendChunk(s).catch(n=>{Nt("send sack failed",n.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Db.type:this.receiveDataChunk(e);break;case Pb.type:{if(!this.isServer)return;let r=e;Nt("receive init",r),this.lastReceivedTsn=Dd(r.initialTsn),this.reconfigResponseSeq=Dd(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new NC;s.initiateTag=this.localVerificationTag,s.advertisedRwnd=this.advertisedRwnd,s.outboundStreams=this._outboundStreamsCount,s.inboundStreams=this._inboundStreamsCount,s.initialTsn=this.localTsn,this.setExtensions(s.params);let n=Date.now()/1e3,i=Buffer.from(Rb.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,Z0.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([ON,i]),Nt("send initAck",s),await this.sendChunk(s).catch(o=>{Nt("send initAck failed",o.message)})}break;case NC.type:{if(this.associationState!=2)return;let r=e;this.timer1Cancel(),this.lastReceivedTsn=Dd(r.initialTsn),this.reconfigResponseSeq=Dd(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new OC;for(let[n,i]of r.params)if(n===ON){s.body=i;break}await this.sendChunk(s).catch(n=>{Nt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case HC.type:await this.receiveSackChunk(e);break;case jC.type:{let r=new fU;r.params=e.params,await this.sendChunk(r).catch(s=>{Nt("send heartbeat ack failed",s.message)})}break;case UC.type:this.setState(1);break;case gU.type:{this.timer2Cancel(),this.setState(7);let r=new xU;await this.sendChunk(r).catch(s=>{Nt("send shutdown ack failed",s.message)}),this.t2Start(r),this.setState(6)}break;case Nb.type:Nt("ErrorChunk",e.descriptions);break;case OC.type:{if(!this.isServer)return;let s=e.body,n=(0,Z0.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=cQ||!s.slice(4).equals(n)){Nt("x State cookie is invalid");return}let i=Date.now()/1e3,o=Rb.jspack.Unpack("!L",s)[0];if(o<i-dQ||o>i){let c=new Nb(0,void 0);c.params.push([Nb.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(d=>{Nt("send errorChunk failed",d.message)});return}let a=new LC;await this.sendChunk(a).catch(c=>{Nt("send cookieAck failed",c.message)}),this.setState(4)}break;case LC.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case wU.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case FC.type:{if(this.associationState!=4)return;let r=e;for(let[s,n]of r.params){let i=kN[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case Bb.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[r,s]of e)r===UN?this.remotePartialReliability=!0:r===LN&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Nt("receiveReconfigParam",kN[e.type]),e.type){case $C.type:{let r=e,s=new Ob(r.requestSequence,gb.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s),await Promise.all(r.streams.map(async n=>{delete this.inboundStreams[n],this.outboundStreamSeq[n]&&(this.reconfigQueue.includes(n)||this.reconfigQueue.push(n))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(r.streams)}break;case Ob.type:{let r=e;if(r.result!==gb.ReconfigResultSuccessPerformed)Nt("OutgoingSSNResetRequestParam failed",Object.keys(gb).find(s=>gb[s]===r.result));else if(r.responseSequence===this.reconfigRequest?.requestSequence){let s=this.reconfigRequest.streams.map(n=>(delete this.outboundStreamSeq[n],n));this.onReconfigStreams.execute(s),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=DN,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case EU.type:{let r=e;this._inboundStreamsCount+=r.newStreams;let s=new Ob(r.requestSequence,1);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&R0)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let r=this.getInboundStream(e.streamId);r.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let s of r.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}async receiveSackChunk(e){if(Ei(this.lastSackedTsn,e.cumulativeTsn))return;let r=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let s=this.flightSize>=this.cwnd,n=0,i=0;for(;this.sentQueue.length>0&&qu(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();n++,a?.acked||(i+=a.bookSize,this.flightSizeDecrease(a)),n===1&&a.sentCount===1&&this.updateRto(r-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let o=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(u=>{for(let l=u[0];l<u[1]+1;l++)c=(e.cumulativeTsn+l)%Xb,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(Ei(u.tsn,c))break;a.has(u.tsn)&&!u.acked&&(i+=u.bookSize,u.acked=!0,this.flightSizeDecrease(u),d=u.tsn)}for(let u of this.sentQueue){if(Ei(u.tsn,d))break;a.has(u.tsn)||(u.misses++,u.misses===3&&(u.misses=0,this.maybeAbandon(u)||(u.retransmit=!0),u.acked=!1,this.flightSizeDecrease(u),o=!0))}}this.fastRecoveryExit===void 0?(n&&s&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,Pn):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=Pn))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Pn),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):qu(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():n>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,qu(this.lastReceivedTsn,e.cumulativeTsn))return;let r=s=>Ei(s,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let s of[...this.sackMisOrdered].sort())if(s===Vu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let[s,n]of e.streams){let i=this.getInboundStream(s);i.streamSequenceNumber=$r(n,1);for(let o of i.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-BN)*this.rttvar+BN*Math.abs(this.srtt-e),this.srtt=(1-PN)*this.srtt+PN*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(uQ,Math.min(this.srtt+4*this.rttvar,fQ))}receive(e,r,s){this.onReceive.execute(e,r,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new yQ),this.inboundStreams[e]}markReceived(e){if(qu(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let s of[...this.sackMisOrdered].sort())if(s===Vu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;let r=s=>Ei(s,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r)),!1}send=async(e,r,s,{expiry:n,maxRetransmits:i,ordered:o}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=o&&this.outboundStreamSeq[e]||0,c=Math.ceil(s.length/Pn),d=0,u=[];for(let l=0;l<c;l++){let f=new Db(0,void 0);f.flags=0,o||(f.flags=KC),l===0&&(f.flags|=CU),l===c-1&&(f.flags|=R0),f.tsn=this.localTsn,f.streamId=e,f.streamSeqNum=a,f.protocol=r,f.userData=s.slice(d,d+Pn),f.bookSize=f.userData.length,f.expiry=n,f.maxRetransmits=i,d+=Pn,this.localTsn=Vu(this.localTsn),u.push(f)}for(u.forEach(l=>{this.outboundQueue.push(l)}),o&&(this.outboundStreamSeq[e]=$r(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(n=>{Nt("send forwardTsn failed",n.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*Pn:4*Pn,r=Math.min(this.flightSize+e,this.cwnd),s=!0;for(let n of this.sentQueue){if(n.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=r)break;this.flightSizeIncrease(n),n.misses=0,n.retransmit=!1,n.sentCount++,await this.sendChunk(n).catch(i=>{Nt("send data failed",i.message)}),s&&this.timer3Restart()}s=!1}for(;this.outboundQueue.length>0&&this.flightSize<r&&this.peerRwnd>0;){let n=this.outboundQueue.shift();if(!n)break;if(n.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(n);break}this.sentQueue.push(n),this.flightSizeIncrease(n),n.sentCount++,n.sentTime=Date.now()/1e3,await this.sendChunk(n).catch(i=>{Nt("send data outboundQueue failed",i.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],r=e.slice(0,NN);this.reconfigQueue=e.slice(NN);let s=new $C(this.reconfigRequestSeq,this.reconfigResponseSeq,Dd(this.localTsn),r);this.reconfigRequestSeq=Vu(this.reconfigRequestSeq),this.reconfigRequest=s,await this.sendReconfigParam(s),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Nt("sendReconfigParam",e);let r=new FC;r.params.push([e.type,e.bytes]),await this.sendChunk(r).catch(s=>{Nt("send reconfig failed",s.message)})}async sendResetRequest(e){Nt("sendResetRequest",e);let r=new Db(0,void 0);r.streamId=e,this.outboundQueue.push(r),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>lQ)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Nt("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>RN)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Nt("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Pn),this.cwnd=Pn,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(Nt("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>RN)Nt("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Nt("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Nt("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new jC;e.params.push([1,Buffer.from(Rb.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(r=>{Nt("send heartbeat failed",r.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){Ei(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,r={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn,e++,s.flags&KC||(r[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new Bb(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(r).map(([s,n])=>[Number(s),n]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let s=this.sentQueue.findIndex(n=>n.type===e.type);for(let n=s;n>=0;n--){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&R0)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&R0)break}return!0}static getCapabilities(){return new xQ(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 Pb;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Nt("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(r){Nt("send init failed",r.message)}}setExtensions(e){let r=[];this.localPartialReliability&&(e.push([UN,Buffer.from("")]),r.push(Bb.type)),r.push(tQ.type),e.push([LN,Buffer.from(r)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let r=iQ(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(r)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,Nt("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new UC;await this.sendChunk(e).catch(r=>{Nt("send abort failed",r.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},yQ=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(t){if(this.reassembly.length===0||Ei(t.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(t);return}for(let[e,r]of oQ(this.reassembly)){if(r.tsn===t.tsn)throw new Error("duplicate chunk in reassembly");if(Ei(r.tsn,t.tsn)){this.reassembly.splice(e,0,t);break}}}*popMessages(){let t=0,e,r,s;for(;t<this.reassembly.length;){let n=this.reassembly[t];if(e===void 0){if(s=!(n.flags&KC),!(n.flags&CU)){if(s)break;t++;continue}if(s&&Zb(n.streamSeqNum,this.streamSequenceNumber))break;r=n.tsn,e=t}else if(n.tsn!==r){if(s)break;e=void 0,t++;continue}if(n.flags&R0){let i=this.reassembly.slice(e,t+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);i.pop();let o=Buffer.concat(i);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(t+1)],s&&n.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=$r(this.streamSequenceNumber,1)),t=e,yield[n.streamId,n.protocol,o]}else t++;r=Vu(r)}}pruneChunks(t){let e=-1,r=0;for(let[s,n]of this.reassembly.entries())if(qu(t,n.tsn))e=s,r+=n.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),r}},xQ=class{constructor(t){this.maxMessageSize=t}};Mu=dt("werift:packages/webrtc/src/transport/sctp.ts"),zu=65536,TU=class AU{constructor(e=5e3,r=zu){this.port=e,this.maxMessageSize=r}dtlsTransport;sctp;onDataChannel=new Be;id=(0,tU.randomUUID)().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=zu;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(r=>r()),this.dtlsTransport=e,this.sctp=new gQ(new bQ(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(r=>{r.forEach(s=>{let n=this.dataChannels[s];n&&(n.setReadyState("closing"),n.setReadyState("closed"),delete this.dataChannels[s])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.negotiated&&r.readyState!=="open"&&r.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(r=>{r==="closed"&&this.sctp.setState(1)})].map(r=>r.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(r=>r.label===e)}datachannelReceive=async(e,r,s)=>{if(r===mb&&s.length>0)switch(Mu("DCEP",e,r,s),s[0]){case bN:{if(s.length<12){Mu("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))Mu("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=Ib.jspack.Unpack("!BBHLHH",s),d=12,u=s.slice(d,d+a).toString("utf8");d+=a;let l=s.slice(d,d+c).toString("utf8");Mu("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:u,protocol:l});let f=(i&3)===1?o:void 0,h=(i&3)===2?o:void 0,m=new PT({label:u,ordered:(i&128)===0,maxPacketLifeTime:h,maxRetransmits:f,protocol:l,id:e}),v=new RT(this,m,!1);v.isCreatedByRemote=!0,this.dataChannels[e]=v,this.onDataChannel.execute(v),v.setReadyState("open")}let n=this.dataChannels[e];this.dataChannelQueue.push([n,mb,Buffer.from(Ib.jspack.Pack("!B",[xN]))]),await this.dataChannelFlush()}break;case xN:{Mu("DATA_CHANNEL_ACK",e,r);let n=this.dataChannels[e];if(!n)throw new Error("channel not found");n.setReadyState("open")}break}else{let n=this.dataChannels[e];if(n){let i=(()=>{switch(r){case wN:return s.toString("utf8");case BJ:return"";case vN:return s;case DJ:return Buffer.from([]);default:throw new Error}})();n.messagesReceived++,n.bytesReceived+=s.length,n.onMessage.execute(i),n.emit("message",{data:i}),n.onmessage&&n.onmessage({data:i})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let r=PJ,s=0,n=0;e.ordered||(r=128),e.maxRetransmits?(r=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(r=2,n=e.maxPacketLifeTime);let i=Ib.jspack.Pack("!BBHLHH",[bN,r,s,n,e.label.length,e.protocol.length]),o=Buffer.concat([Buffer.from(i),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,mb,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,r,s]=this.dataChannelQueue.shift(),n=e.id;if(n===void 0){for(n=this.dataChannelId;Object.keys(this.dataChannels).includes(n.toString());)n+=2;this.dataChannels[n]=e,e.setId(n)}if(r===mb)await this.sctp.send(n,r,s,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(n,r,s,{expiry:i,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-s.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,r)=>{let s=Buffer.isBuffer(r)?r:Buffer.from(r),n=v7(r);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof r=="string"?[e,wN,s]:[e,vN,s]),this.sctp.associationState!==4&&Mu("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return AU.getCapabilities(this.maxMessageSize)}static getCapabilities(e=zu){return new YT(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??zu}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(r=>r[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(r=>r!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},YT=class{constructor(t){this.maxMessageSize=t}},bQ=class{constructor(t){this.dtls=t}set onData(t){this.dtls.dataReceiver=t}send=t=>this.dtls.sendData(t);close(){}},N0=class kU{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[r,s]=wQ(e),n=new kU;r.forEach(o=>{if(o.startsWith("v="))n.version=Number.parseInt(o.slice(2),10);else if(o.startsWith("o="))n.origin=o.slice(2);else if(o.startsWith("s="))n.name=o.slice(2);else if(o.startsWith("c="))n.host=$E(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=VE(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new Wb(d,u))}break;case"ice-lite":n.iceLite=!0;break;case"ice-options":n.iceOptions=c;break;case"ice-pwd":n.icePassword=c;break;case"ice-ufrag":n.iceUsernameFragment=c;break;case"group":Lb(n.group,c);break;case"msid-semantic":Lb(n.msidSemantic,c);break;case"setup":n.dtlsRole=SN[c];break;case"extmap-allow-mixed":n.extMapAllowMixed=!0;break}}});let i=n.group.find(o=>o.semantic==="BUNDLE");return s.forEach(o=>{let c=o[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let d=c[1],u=c[4].split(" "),l=["audio","video"].includes(d)?u.map(m=>Number(m)):void 0,f=new Yb(d,Number.parseInt(c[2]),c[3],l||u);if(f.dtlsParams=new Gb([...n.dtlsFingerprints],n.dtlsRole),f.iceParams=new GT({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword}),f.iceOptions=n.iceOptions,n.media.push(f),o.slice(1).forEach(m=>{if(m.startsWith("c="))f.host=$E(m.slice(2));else if(m.startsWith("a=")){let[v,p]=VE(m);switch(v){case"candidate":if(!p)throw new Error;f.iceCandidates.push(QT(p));break;case"end-of-candidates":f.iceCandidatesComplete=!0;break;case"extmap":{let[x,w]=p.split(" ");x.includes("/")&&([x]=x.split("/")),f.rtp.headerExtensions.push(new ki({id:Number.parseInt(x),uri:w}))}break;case"fingerprint":{if(!p)throw new Error;let[x,w]=p.split(" ");f.dtlsParams?.fingerprints.push(new Wb(x,w))}break;case"ice-options":f.iceOptions=p;break;case"ice-pwd":f.iceParams.password=p;break;case"ice-ufrag":f.iceParams.usernameFragment=p;break;case"ice-lite":f.iceParams.iceLite=!0;break;case"max-message-size":f.sctpCapabilities=new YT(Number.parseInt(p,10));break;case"mid":f.rtp.muxId=p;break;case"msid":f.msid=p;break;case"rtcp":{let[x,w]=Co(p," ");f.rtcpPort=Number.parseInt(x),f.rtcpHost=$E(w)}break;case"rtcp-mux":f.rtcpMux=!0;break;case"setup":f.dtlsParams.role=SN[p];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":f.direction=v;break;case"rtpmap":{let[x,w]=Co(p," "),[E,P,j]=w.split("/"),T;f.kind==="audio"&&(T=j?Number.parseInt(j):1);let k=new Xa({mimeType:f.kind+"/"+E,channels:T,clockRate:Number.parseInt(P),payloadType:Number.parseInt(x)});f.rtp.codecs.push(k)}break;case"sctpmap":{if(!p)throw new Error;let[x,w]=Co(p," ");f.sctpMap[Number.parseInt(x)]=w,f.sctpPort=Number.parseInt(x)}break;case"sctp-port":if(!p)throw new Error;f.sctpPort=Number.parseInt(p);break;case"ssrc":{let[x,w]=Co(p," "),E=Number.parseInt(x),[P,j]=Co(w,":"),T=f.ssrc.find(k=>k.ssrc===E);T||(T=new Jb({ssrc:E}),f.ssrc.push(T)),D7.includes(P)&&(T[P]=j)}break;case"ssrc-group":Lb(f.ssrcGroup,p);break;case"rid":{let[x,w]=Co(p," ");f.simulcastParameters.push(new BT({rid:x,direction:w}))}break}}}),(!f.iceParams.usernameFragment||!f.iceParams.password)&&f.rtp.muxId&&i&&i.items.includes(f.rtp.muxId))for(let m=0;m<i.items.length;m++){if(!i.items.includes(m.toString()))continue;let v=n.media[m];if(v.iceParams?.usernameFragment&&v.iceParams.password){f.iceParams={...v.iceParams};break}}f.dtlsParams.role||(f.dtlsParams=void 0);let h=m=>f.rtp.codecs.find(v=>v.payloadType===m);o.slice(1).forEach(m=>{if(m.startsWith("a=")){let[v,p]=VE(m);if(v==="fmtp"){let[x,w]=Co(p," "),E=h(Number(x));E.parameters=w}else if(v==="rtcp-fb"){let[x,w,E]=p.split(" ");f.rtp.codecs.forEach(P=>{["*",P.payloadType.toString()].includes(x)&&P.rtcpFeedback.push(new S7({type:w,parameter:E}))})}}})}),n}webrtcTrackId(e){if(e.msid?.includes(" ")){let r=e.msid.split(" ");for(let s of this.msidSemantic)if(s.semantic==="WMS"&&(s.items.includes(r[0])||s.items.includes("*")))return r[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${GC(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(n=>e.push(`a=group:${n.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));let r=this.media.map(n=>n.toString()).join("");return e.join(`\r
133
+ `)+`\r
134
+ `+r}toJSON(){return new IU(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},Yb=class{constructor(t,e,r,s){this.kind=t,this.port=e,this.profile=r,this.fmt=s}host;direction;msid;rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];toString(){let t=[];if(t.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&t.push(`c=${GC(this.host)}`),this.iceCandidates.forEach(e=>{t.push(`a=candidate:${JT(e)}`)}),this.iceCandidatesComplete&&t.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&t.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&t.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&t.push("a=ice-lite"),this.iceOptions&&t.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{t.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),t.push(`a=setup:${BC[this.dtlsParams.role]}`)),this.direction&&t.push(`a=${this.direction}`),this.rtp.muxId&&t.push(`a=mid:${this.rtp.muxId}`),this.msid&&t.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(t.push(`a=rtcp:${this.rtcpPort} ${GC(this.rtcpHost)}`),this.rtcpMux&&t.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{t.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{D7.forEach(r=>{let s=e[r];s!==void 0&&t.push(`a=ssrc:${e.ssrc} ${r}:${s}`)})}),this.rtp.codecs.forEach(e=>{t.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(r=>{let s=r.type;r.parameter&&(s+=` ${r.parameter}`),t.push(`a=rtcp-fb:${e.payloadType} ${s}`)}),e.parameters&&t.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let r=this.sctpMap[Number(e)];t.push(`a=sctpmap:${e} ${r}`)}),this.sctpPort&&t.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&t.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>t.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{t.push(`a=rid:${n.rid} ${n.direction}`)});let e="a=simulcast:",r=this.simulcastParameters.filter(n=>n.direction==="recv");r.length&&(e+=`recv ${r.map(n=>n.rid).join(";")} `);let s=this.simulcastParameters.filter(n=>n.direction==="send");s.length&&(e+=`send ${s.map(n=>n.rid).join(";")}`),t.push(e)}return t.join(`\r
135
+ `)+`\r
136
+ `}},Xu=class{constructor(t,e){this.semantic=t,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};IU=class{constructor(t,e){this.sdp=t,this.type=e}static isThis(t){if(typeof t?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};Jb=class{ssrc;cname;msid;msLabel;label;constructor(t){Object.assign(this,t)}},yb=dt("werift:packages/webrtc/src/media/rtpReceiver.ts"),ZT=class{constructor(t,e,r){this.config=t,this.kind=e,this.rtcpSsrc=r}codecs={};get codecArray(){return Object.values(this.codecs).sort((t,e)=>t.payloadType-e.payloadType)}ssrcByRtx={};nack=new qJ(this);audioRedHandler=new SL;type="receiver";uuid=(0,I7.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Be;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(t){this.dtlsTransport=t}get track(){return this.tracks[0]??new Y0({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===_7().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===af().type)}prepareReceive(t){t.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),t.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(t){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new KJ(this.dtlsTransport,this.rtcpSsrc,t))}addTrack(t){return this.tracks.find(r=>{if(r.rid)return r.rid===t.rid;if(r.ssrc)return r.ssrc===t.ssrc})?!1:(this.tracks.push(t),t.ssrc&&(this.trackBySSRC[t.ssrc]=t),t.rid&&(this.trackByRID[t.rid]=t),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,Tb.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=Object.entries(this.remoteStreams).map(([r,s])=>{let n=0,i=0;if(this.lastSRtimestamp[r]){n=this.lastSRtimestamp[r];let o=J0()-this.receiveLastSRTimestamp[r];o>0&&o<65536&&(i=Ku(o*65536))}return new c1({ssrc:Number(r),fractionLost:s.fraction_lost,packetsLost:s.packets_lost,highestSequence:s.max_seq,jitter:s.jitter,lsr:n,dlsr:i})}),e=new Qu({ssrc:this.rtcpSsrc,reports:t});try{this.config.debug.receiverReportDelay&&await(0,Tb.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(r){yb("sendRtcp failed",r),await(0,Tb.setTimeout)(500+Math.random()*1e3)}}}catch{}}}async getStats(){let t=Ya(),e=[];if(!this.dtlsTransport)return e;let r=Ft("transport",this.dtlsTransport.id);for(let s of this.tracks){if(!s.ssrc)continue;let n=this.remoteStreams[s.ssrc];if(!n)continue;let i={type:"inbound-rtp",id:Ft("inbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:this.codecs[0]?Ft("codec",this.codecs[0].payloadType,r):void 0,mid:this.sdesMid,trackIdentifier:s.id,packetsReceived:n.packets_received,packetsLost:n.packets_lost,jitter:n.jitter};if(e.push(i),this.lastSRtimestamp[s.ssrc]){let o={type:"remote-outbound-rtp",id:Ft("remote-outbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[s.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(t){if(!this.pliEnabled){yb("pli not supported",{mediaSsrc:t});return}if(this.stopped)return;yb("sendRtcpPLI",{mediaSsrc:t});let e=new Ju({feedback:new V0({senderSsrc:this.rtcpSsrc,mediaSsrc:t})});try{await this.dtlsTransport.sendRtcp([e])}catch(r){yb(r)}}handleRtcpPacket(t){switch(t.type){case $d.type:{let e=t;this.lastSRtimestamp[e.ssrc]=zT(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=J0();let r=this.trackBySSRC[t.ssrc];r&&r.onReceiveRtcp.execute(t)}break}this.onRtcp.execute(t)}handleRtpBySsrc=(t,e)=>{let r=this.trackBySSRC[t.header.ssrc];this.handleRTP(t,e,r)};handleRtpByRid=(t,e,r)=>{let s=this.trackByRID[e];this.trackBySSRC[t.header.ssrc]||(this.trackBySSRC[t.header.ssrc]=s),this.handleRTP(t,r,s)};handleRTP(t,e,r){if(this.stopped)return;let s=this.codecs[t.header.payloadType];if(!s)return;if(this.remoteStreams[t.header.ssrc]=this.remoteStreams[t.header.ssrc]??new WJ(s.clockRate),this.remoteStreams[t.header.ssrc].add(t),this.receiverTWCC){let i=e[Xt.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(t.header.ssrc);if(s.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[t.header.ssrc],o=em(s.parameters??""),a=this.codecs[o.apt];if(t.payload.length<2)return;t=CL(t,a.payloadType,i),r=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=mT.deSerialize(t.payload),!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())))){if(r?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(t),r)if(n){if(r.kind==="audio"){let i=this.audioRedHandler.push(n,t);for(let o of i)r.onReceiveRtp.execute(o.clone(),e)}}else r.onReceiveRtp.execute(t.clone(),e);this.runRtcp()}}},g0=dt("werift:packages/webrtc/src/media/router.ts"),RU=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(t){this.ssrcTable[t.ssrc]=t}registerRtpReceiver(t,e){g0("registerRtpReceiver",e),this.ssrcTable[e]=t}registerRtpReceiverBySsrc(t,e){g0("registerRtpReceiverBySsrc",e),e.encodings.filter(r=>r.ssrc!=null).forEach((r,s)=>{this.registerRtpReceiver(t.receiver,r.ssrc),t.addTrack(new Y0({ssrc:r.ssrc,kind:t.kind,id:t.sender.trackId,remote:!0,codec:e.codecs[s]})),r.rtx&&this.registerRtpReceiver(t.receiver,r.rtx.ssrc)}),e.headerExtensions.forEach(r=>{this.extIdUriMap[r.id]=r.uri})}registerRtpReceiverByRid(t,e,r){let[s]=r.codecs;g0("registerRtpReceiverByRid",e),t.addTrack(new Y0({rid:e.rid,kind:t.kind,id:t.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=t.receiver}routeRtp=t=>{let e=dL(t.header.extensions,this.extIdUriMap),r=this.ssrcTable[t.header.ssrc],s=e[Xt.sdesRTPStreamID];if(typeof s=="string"?(r=this.ridTable[s],r.latestRid=s,r.handleRtpByRid(t,s,e)):r?r.handleRtpBySsrc(t,e):(r=Object.values(this.ridTable).filter(o=>o instanceof ZT).find(o=>o.trackBySSRC[t.header.ssrc]),r&&(g0("simulcast register receiver by ssrc",t.header.ssrc),this.registerRtpReceiver(r,t.header.ssrc),r.handleRtpBySsrc(t,e))),!r){g0("ssrcReceiver not found");return}let n=e[Xt.sdesMid];typeof n=="string"&&(r.sdesMid=n);let i=e[Xt.repairedRtpStreamId];typeof i=="string"&&(r.latestRepairedRid=i)};routeRtcp=t=>{let e=[];switch(t.type){case $d.type:t=t,e.push(this.ssrcTable[t.ssrc]);break;case Qu.type:t=t,t.reports.forEach(r=>{e.push(this.ssrcTable[r.ssrc])});break;case W0.type:{let r=t}break;case Hd.type:{let r=t;r.feedback&&e.push(this.ssrcTable[r.feedback.mediaSourceSsrc])}break;case Ju.type:{let r=t;switch(r.feedback.count){case q0.count:{let s=r.feedback;e.push(this.ssrcTable[s.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[r.feedback.senderSsrc]||this.ssrcTable[r.feedback.mediaSsrc])}}break}e.filter(r=>r).forEach(r=>r.handleRtcpPacket(t))}},_Q=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(t,e,r){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=r,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=r):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),r<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=r),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),r>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=r)),this.numPackets++,this.totalSize+=t}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let t=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/t*8*1e3;return $0(e)}get sendBitrate(){let t=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/t*8*1e3;return $0(e)}},ju=20,SQ=10,EQ=class{congestion=!1;onAvailableBitrate=new Be;onCongestion=new Be;onCongestionScore=new Be;congestionCounter=0;cumulativeResult=new _Q;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(t){this._congestionScore=t,this.onCongestionScore.execute(t)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(t){this._availableBitrate=t,this.onAvailableBitrate.execute(t)}constructor(){}receiveTWCC(t){let r=qT()-this.cumulativeResult.firstPacketSentAtMs;r>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<ju?this.congestionCounter++:this.congestionScore<SQ&&this.congestionScore++,this.congestionCounter>=ju&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let s of t.packetResults){if(!s.received)continue;let n=s.sequenceNumber,i=this.sentInfos[n];i&&s.receivedAtMs&&this.cumulativeResult.addPacket(i.size,i.sendingAtMs,s.receivedAtMs)}if(r>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-ju){let s=$0(ju/2)+1,n=$0(ju/4)+1,i=s-(s-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-ju&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(t){Object.keys(t).map(e=>Number(e)).sort().filter(e=>e<t.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[t.wideSeq]=t}},qE=dt("werift:packages/webrtc/src/media/rtpSender.ts"),MN=128,jN=.85,PU=class{constructor(t){this.trackOrKind=t,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof t!="string"&&(t.streamId&&(this.streamId=t.streamId),this.registerTrack(t))}type="sender";kind;ssrc=JC.jspack.Unpack("!L",(0,YC.randomBytes)(4))[0];rtxSsrc=JC.jspack.Unpack("!L",(0,YC.randomBytes)(4))[0];streamId=(0,QC.randomUUID)().toString();trackId=(0,QC.randomUUID)().toString();onReady=new Be;onRtcp=new Be;onPictureLossIndication=new Be;onGenericNack=new Be;senderBWE=new EQ;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=sT();redRedundantPayloadType;_redDistance=2;redEncoder=new _L(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(t){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=t,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(t){this._redDistance=t,this.redEncoder.distance=t}prepareSend(t){this.cname=t.rtcp?.cname,this.mid=t.muxId,this.headerExtensions=t.headerExtensions,this.rtpStreamId=t.rtpStreamId,this.repairedRtpStreamId=t.repairedRtpStreamId,this.codec=t.codecs[0],this.track&&(this.track.codec=this.codec),t.codecs.forEach(e=>{let r=em(e.parameters??"");e.name.toLowerCase()==="rtx"&&r.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(t){if(t.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),t.id=this.trackId;let{unSubscribe:e}=t.onReceiveRtp.subscribe(async r=>{await this.sendRtp(r)});this.track=t,this.disposeTrack=e,this.codec&&(t.codec=this.codec),t.onSourceChanged.subscribe(r=>{this.replaceRTP(r)})}async replaceTrack(t){if(t!==null){if(t.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=t.header||(await t.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(t),qE("replaceTrack","ssrc",t.ssrc,"rid",t.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,ZC.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=[new $d({ssrc:this.ssrc,senderInfo:new pT({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=zT(this.ntpTimestamp),this.lastSentSRTimestamp=J0(),this.cname&&t.push(new W0({chunks:[new fT({source:this.ssrc,items:[new hT({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(t)}catch(e){qE("sendRtcp failed",e),await(0,ZC.setTimeout)(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:t,timestamp:e},r=!1){this.sequenceNumber!=null&&(this.seqOffset=$r(this.sequenceNumber,-t),r&&(this.seqOffset=$r(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Od(this.timestamp,-e),r&&(this.timestampOffset=$r(this.timestampOffset,1))),this.rtpCache=[],qE("replaceRTP",this.sequenceNumber,t,this.seqOffset)}async sendRtp(t){if(this.dtlsTransport.state!=="connected"||!this.codec)return;t=Buffer.isBuffer(t)?Bo.deSerialize(t):t;let{header:e,payload:r}=t;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=Od(e.timestamp,this.timestampOffset),e.sequenceNumber=$r(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let s=H7(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Xt.sdesMid:return this.mid?lL(this.mid):void 0;case Xt.sdesRTPStreamID:return this.rtpStreamId?uL(this.rtpStreamId):void 0;case Xt.repairedRtpStreamId:return this.repairedRtpStreamId?fL(this.repairedRtpStreamId):void 0;case Xt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=$r(this.dtlsTransport.transportSequenceNumber,1),hL(this.dtlsTransport.transportSequenceNumber);case Xt.absSendTime:return pL(s)}})();if(u)return{id:d.id,payload:u}}).filter(d=>d);for(let d of n){let u=e.extensions.find(l=>l.id===d.id);u?u.payload=d.payload:e.extensions.push(d)}e.extensions=e.extensions.sort((d,u)=>d.id-u.id),this.ntpTimestamp=s,this.rtpTimestamp=e.timestamp,this.octetCount+=r.length,this.packetCount=Od(this.packetCount,1),this.rtpCache[e.sequenceNumber%MN]=t;let i=r;this.redRedundantPayloadType&&(this.redEncoder.push({block:i,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),i=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(i,e);this.runRtcp();let a=qT(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(t){switch(t.type){case $d.type:case Qu.type:t.reports.filter(r=>r.ssrc===this.ssrc).forEach(r=>{if(this.lastSRtimestamp===r.lsr&&r.dlsr&&this.lastSentSRTimestamp){let s=J0()-this.lastSentSRTimestamp-r.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=jN*this.rtt+(1-jN)*s}});break;case Hd.type:{let e=t;switch(e.feedback.count){case K0.count:{let r=e.feedback;this.senderBWE.receiveTWCC(r)}break;case z0.count:{let r=e.feedback;r.lost.forEach(async s=>{let n=this.rtpCache[s%MN];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=TL(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=$r(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(n.payload,n.header))}),this.onGenericNack.execute(r)}break}}break;case Ju.type:{let e=t;switch(e.feedback.count){case q0.count:{let r=e.feedback;this.receiverEstimatedMaxBitrate=r.bitrate}break;case V0.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(t)}getParameters(){return{encodings:[]}}setParameters(t){}async getStats(){let t=Ya(),e=[];if(!this.dtlsTransport)return e;let r=Ft("transport",this.dtlsTransport.id),s={type:"outbound-rtp",id:Ft("outbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:this.codec?Ft("codec",this.codec.payloadType,r):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(s),this.track){let n={type:"media-source",id:Ft("media-source",this.trackId),timestamp:t,trackIdentifier:this.trackId,kind:this.kind};e.push(n)}if(this.rtt!==void 0){let n={type:"remote-inbound-rtp",id:Ft("remote-inbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:s.codecId,localId:s.id,roundTripTime:this.rtt};e.push(n)}return e}},CQ=dt("werift:packages/webrtc/src/transport/sctpManager.ts"),TQ=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Be;constructor(){}createSctpTransport(t){let e=new TU(5e3,t);return e.mid=void 0,e.onDataChannel.subscribe(r=>{this.dataChannelsOpened++,this.dataChannels.push(r),this.onDataChannel.execute(r)}),this.sctpTransport=e,e}createDataChannel(t,e={}){let s={...{protocol:"",ordered:!0,negotiated:!1},...e};if(s.maxPacketLifeTime&&s.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let n=new PT({id:s.id,label:t,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new RT(this.sctpTransport,n);return this.dataChannelsOpened++,this.dataChannels.push(i),i.stateChange.subscribe(o=>{if(o==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(i);a!==-1&&this.dataChannels.splice(a,1)}}),i}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),CQ("sctp connected"))}setRemoteSCTP(t,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(t.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=t.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=t.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let t=Ya(),e=[];for(let r of this.dataChannels){let s={type:"data-channel",id:Ft("data-channel",r.id),timestamp:t,label:r.label,protocol:r.protocol,dataChannelIdentifier:r.id,state:r.readyState,messagesSent:r.messagesSent||0,bytesSent:r.bytesSent||0,messagesReceived:r.messagesReceived||0,bytesReceived:r.bytesReceived||0};e.push(s)}return e}},DU=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:t,midSuffix:e,bundlePolicy:r}){this.cname=t,this.midSuffix=e??!1,this.bundlePolicy=r}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(t=>t.direction==="inactive")}createMediaDescriptionForTransceiver(t,e){let r=new Yb(t.kind,9,"UDP/TLS/RTP/SAVPF",t.codecs.map(s=>s.payloadType));return r.direction=e,r.msid=t.msid,r.rtp={codecs:t.codecs,headerExtensions:t.headerExtensions,muxId:t.mid},r.rtcpHost="0.0.0.0",r.rtcpPort=9,r.rtcpMux=!0,r.ssrc=[new Jb({ssrc:t.sender.ssrc,cname:this.cname})],t.options.simulcast&&(r.simulcastParameters=t.options.simulcast.map(s=>new BT(s))),r.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(r.ssrc.push(new Jb({ssrc:t.sender.rtxSsrc,cname:this.cname})),r.ssrcGroup=[new Xu("FID",[t.sender.ssrc.toString(),t.sender.rtxSsrc.toString()])]),this.addTransportDescription(r,t.dtlsTransport),r}createMediaDescriptionForSctp(t){let e=new Yb("application",_N,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=t.port,e.rtp.muxId=t.mid,e.sctpCapabilities=t.getCapabilities(),this.addTransportDescription(e,t.dtlsTransport),e}addTransportDescription(t,e){let r=e.iceTransport;t.iceCandidates=r.localCandidates,t.iceCandidatesComplete=r.gatheringState==="complete",t.iceParams=r.localParameters,t.iceOptions="trickle",t.host=NJ,t.port=_N,t.direction==="inactive"&&(t.port=0,t.msid=void 0),t.dtlsParams||(t.dtlsParams=e.localParameters,t.dtlsParams.fingerprints||(t.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(t=""){let e="";for(let r=0;e=(r++).toString()+t,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:t,isLocal:e,signalingState:r,type:s}){let n=N0.parse(t);return this.validateDescription({description:n,isLocal:e,signalingState:r}),n.type=s,n}validateDescription({description:t,isLocal:e,signalingState:r}){if(e){if(t.type==="offer"){if(!["stable","have-local-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}else if(t.type==="offer"){if(!["stable","have-remote-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(t,e){let r=new N0;XC("offer",r),(this.currentLocalDescription?.media??[]).forEach((n,i)=>{let o=n.rtp.muxId;if(o)if(n.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=i,r.media.push(this.createMediaDescriptionForSctp(e))}else{let a=t.find(c=>c.mid===o);if(!a){if(n.direction==="inactive"){r.media.push(n);return}throw new Error("transceiver not found")}a.mLineIndex=i,r.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let n of t.filter(i=>!r.media.find(o=>o.rtp.muxId===i.mid))){n.mid==null&&(n.mid=this.allocateMid(this.midSuffix?"av":""));let i=this.createMediaDescriptionForTransceiver(n,n.direction);n.mLineIndex===void 0?(n.mLineIndex=r.media.length,r.media.push(i)):r.media[n.mLineIndex]=i}if(e&&!r.media.find(n=>n.kind==="application")&&(e.mLineIndex=r.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),r.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let n=r.media.map(i=>i.rtp.muxId).filter(i=>i);if(n.length){let i=new Xu("BUNDLE",n);r.group.push(i)}}return r}buildAnswerSdp({transceivers:t,sctpTransport:e,signalingState:r}){if(!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let s=new N0;XC("answer",s);for(let n of this._remoteDescription.media){let i,o;if(["audio","video"].includes(n.kind)){let a=t.find(c=>c.mid===n.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,VT(a.direction,a.offerDirection)),i=a.dtlsTransport}else if(n.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");o=this.createMediaDescriptionForSctp(e),i=e.dtlsTransport}else throw new Error("invalid kind");o.dtlsParams&&(i.role==="auto"?o.dtlsParams.role="client":o.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(o.simulcastParameters=n.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),s.media.push(o)}if(this.bundlePolicy!=="disable"){let n=new Xu("BUNDLE",[]);for(let i of s.media)i.rtp.muxId&&n.items.push(i.rtp.muxId);s.group.push(n)}return s}setLocalDescription(t){this.currentLocalDescription=t,t.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=t}setRemoteDescription(t,e){if(!t.sdp||!t.type||t.type==="rollback"||t.type==="pranswer")throw new Error("invalid sessionDescription");let r=this.parseSdp({sdp:t.sdp,isLocal:!1,signalingState:e,type:t.type});return r.type==="answer"?(this.currentRemoteDescription=r,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=r,r}registerMid(t){this.seenMid.add(t)}get remoteIsBundled(){let t=this._remoteDescription;return t?t.group.find(r=>r.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(t,e,r){let s=new Map(e.map(o=>[o?.mLineIndex,o])),n=e.find(o=>o?.dtlsTransport)?.dtlsTransport??r?.dtlsTransport;t.media.filter(o=>["audio","video"].includes(o.kind)).forEach((o,a)=>{let d=(s.get(a)??e[a])?.dtlsTransport??n;if(!d)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(o,d)});let i=t.media.find(o=>o.kind==="application");r&&i&&this.addTransportDescription(i,r.dtlsTransport),this.setLocalDescription(t)}},y0=dt("werift:packages/webrtc/src/transport/secureTransportManager.ts"),AQ=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Be;iceConnectionStateChange=new Be;onIceCandidate=new Be;connectionStateChange=new Be;config;transceiverManager;sctpManager;constructor({config:t,transceiverManager:e,sctpManager:r}){if(this.config=t,this.transceiverManager=e,this.sctpManager=r,this.config.dtls){let{keys:s}=this.config.dtls;s&&this.setupCertificate(s)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,r)=>(e.map(s=>s.id).includes(r.id)||e.push(r),e),[])}get iceTransports(){return this.dtlsTransports.map(t=>t.iceTransport)}setupCertificate(t){this.certificate=new KT(t.keyPem,t.certPem,t.signatureHash)}createTransport(){let t=this.iceTransports.find(n=>n.state!=="closed"),e=new Q7({...$7(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});t&&(e.connection.localUsername=t.connection.localUsername,e.connection.localPassword=t.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let r=new J7(e);return r.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new DC(this.config,r,this.certificate,kQ)}handleNewIceCandidate({candidate:t,media:e,remoteIsBundled:r,transceiver:s,sctpTransport:n,bundlePolicy:i}){return i==="max-bundle"||r?(t.sdpMLineIndex=0,e&&(t.sdpMid=e.rtp.muxId)):(s&&(t.sdpMLineIndex=s.mLineIndex,t.sdpMid=s.mid),n&&(t.sdpMLineIndex=n.mLineIndex,t.sdpMid=n.mid)),t.foundation&&!t.foundation.startsWith("candidate:")&&(t.foundation="candidate:"+t.foundation),this.onIceCandidate.execute(t),t}async addIceCandidate(t,e){let r=WT.fromJSON(e);if(!r)return;let s;typeof r.sdpMid=="number"&&(s=this.getTransportByMid(r.sdpMid)),!s&&typeof r.sdpMLineIndex=="number"&&(s=this.getTransportByMLineIndex(t,r.sdpMLineIndex)),s||(s=this.iceTransports[0]),s?await s.addRemoteCandidate(r):y0("iceTransport not found for candidate",r)}getTransportByMid(t){let e,r=this.transceiverManager.getTransceivers().find(s=>s.mid===t);return r?e=r.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===t&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(t,e){let r=t.media[e];return r?this.getTransportByMid(r.rtp.muxId):void 0}restartIce(){for(let t of this.iceTransports)t.restart()}setLocalRole({type:t,role:e}){for(let r of this.dtlsTransports){let s=r.iceTransport;t==="offer"?s.connection.iceControlling=!0:s.connection.iceControlling=!1,s.connection.remoteIsLite&&(s.connection.iceControlling=!0),t==="answer"&&e&&(r.role=e)}}updateIceGatheringState(){let t=this.iceTransports;function e(...s){return t.filter(n=>s.includes(n.gatheringState)).length===t.length}let r;t.length&&e("complete")?r="complete":!t.length||e("new","complete")?r="new":t.map(s=>s.gatheringState).includes("gathering")?r="gathering":r="new",this.iceGatheringState!==r&&(this.iceGatheringState=r,this.iceGatheringStateChange.execute(r))}updateIceConnectionState(){let t=this.iceTransports,e;function r(...n){return t.filter(i=>n.includes(i.state)).length===t.length}function s(...n){return t.some(i=>n.includes(i.state))}this.connectionState==="closed"?e="closed":s("failed")?e="failed":s("disconnected")?e="disconnected":r("new","closed")?e="new":s("new","checking")?e="checking":r("completed","closed")?e="completed":r("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(y0("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(t){let e=this.iceTransports.find(r=>r.state==="connected"||r.state==="completed");t&&e?y0("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(r=>r.gather())).catch(r=>{y0("gatherCandidates failed",r)})}setConnectionState(t){y0("connectionStateChange",t),this.connectionState=t,this.connectionStateChange.execute(t)}async getStats(){let t=[];for(let e of this.dtlsTransports){let r=await e.getStats();r&&t.push(...r)}return t}async ensureCerts(){this.certificate||(this.certificate=await DC.SetupCertificate());for(let t of this.dtlsTransports)t.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(t=>t.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},kQ=[EN.SRTP_AEAD_AES_128_GCM,EN.SRTP_AES128_CM_HMAC_SHA1_80],Bn=dt("werift:packages/webrtc/src/peerConnection.ts"),IQ=class extends IT{cname=(0,BU.randomUUID)().toString();config=NU();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new RU;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Be;iceConnectionStateChange=new Be;signalingStateChange=new Be;connectionStateChange=new Be;onDataChannel=new Be;onRemoteTransceiverAdded=new Be;onTransceiverAdded=new Be;onIceCandidate=new Be;onNegotiationneeded=new Be;onTrack=new Be;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(t={}){super(),this.setConfiguration(t),this.sdpManager=new DU({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new OU(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:r,transceiver:s})=>{let n={track:e,streams:[r],transceiver:s,receiver:s.receiver};this.onTrack.execute(e),this.emit("track",n),this.ontrack&&this.ontrack(n)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new TQ,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let r={channel:e};this.ondatachannel?.(r),this.emit("datachannel",r)}),this.secureManager=new AQ({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let r=e?e.toJSON():void 0;this.onIceCandidate.execute(r),this.onicecandidate?.({candidate:r}),this.emit("icecandidate",{candidate:r})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(t){if(V7(this.config,t),this.config.icePortRange){let[e,r]=this.config.icePortRange;if(e===r)throw new Error("should not be same value");if(e>=r)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,r]of yN([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(r.payloadType==null)switch(r.payloadType=96+e,r.name.toLowerCase()){case"rtx":r.parameters=`apt=${r.payloadType-1}`;break;case"red":if(r.contentType==="audio"){let s=r.payloadType+1;r.parameters=`${s}/${s}`,r.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,r)=>{e.id=1+r})}getConfiguration(){return this.config}async createOffer({iceRestart:t}={}){(t||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let r of this.transceiverManager.getTransceivers())r.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(r),r.headerExtensions.length===0&&(r.headerExtensions=this.config.headerExtensions[r.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let t=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return t.setDtlsTransport(e),t}createDataChannel(t,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let r=this.sctpManager.createDataChannel(t,e);if(!r.sctp.dtlsTransport){let s=this.findOrCreateTransport();r.sctp.setDtlsTransport(s)}return r}removeTrack(t){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(t),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let t=this.dtlsTransports.find(n=>n.state!=="closed"),e=t?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&t)return t;let r=this.secureManager.createTransport();r.onRtp.subscribe(n=>{this.router.routeRtp(n)}),r.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});let s=r.iceTransport;return s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),s.onIceCandidate.subscribe(n=>{if(!this.localDescription){Bn("localDescription not found when ice candidate was gathered");return}if(!n){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){Bn("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:n,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(i=>i?.dtlsTransport?.iceTransport.id===s.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===s.id?this.sctpTransport:void 0})}),r}async setLocalDescription(t){t=t??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let r=this.sdpManager.parseSdp({sdp:t.sdp,isLocal:!0,signalingState:this.signalingState,type:t.type});r.type==="offer"?this.setSignalingState("have-local-offer"):r.type==="answer"&&this.setSignalingState("stable");for(let[n,i]of yN(r.media)){let o=i.rtp.muxId;if(this.sdpManager.registerMid(o),["audio","video"].includes(i.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(n);a&&(a.mid=o)}i.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=o)}let s=r.media.find(n=>n.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:r.type,role:s}),["answer","pranswer"].includes(r.type))for(let n of this.transceiverManager.getTransceivers()){let i=VT(n.direction,n.offerDirection);n.setCurrentDirection(i)}return this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(n=>{Bn("gatherCandidates failed",n)}),r.type==="answer"&&this.connect().catch(n=>{Bn("connect failed",n),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),r}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(t){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,t)}async connect(){Bn("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:r}=e;if(r.state==="connected")return;let s=()=>e.state==="connected";s()||(this.secureManager.setConnectionState("connecting"),await r.start().catch(n=>{throw Bn("iceTransport.start failed",n),n}),!s()&&(await e.start().catch(n=>{throw Bn("dtlsTransport.start failed",n),n}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(t){t instanceof N0&&(t=t.toSdp());let e=this.sdpManager.setRemoteDescription(t,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let r,s=(o,a)=>o.kind===a.kind&&[void 0,a.rtp.muxId].includes(o.mid),n=e.media.map((o,a)=>{let c;if(["audio","video"].includes(o.kind)){let u=this.transceiverManager.getTransceivers().find(l=>s(l,o));if(!u)u=this.addTransceiver(o.kind,{direction:"recvonly"}),u.mid=o.rtp.muxId,this.onRemoteTransceiverAdded.execute(u);else if(u.direction==="inactive"&&u.stopping){u.stopped=!0,t.type==="answer"&&u.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.transceiverManager.setRemoteRTP(u,o,e.type,a)}else if(o.kind==="application"){let u=this.sctpTransport;u||(u=this.createSctpTransport(),u.mid=o.rtp.muxId),this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.sctpManager.setRemoteSCTP(o,a)}else throw new Error("invalid media kind");let d=c.iceTransport;if(o.iceParams){let u=!!this.sdpManager.inactiveRemoteMedia;d.setRemoteParams(o.iceParams,u),o.iceParams?.iceLite&&(d.connection.iceControlling=!0)}return o.dtlsParams&&c.setRemoteParams(o.dtlsParams),o.iceCandidates.forEach(d.addRemoteCandidate),o.iceCandidatesComplete&&d.addRemoteCandidate(void 0),e.type==="answer"&&o.dtlsParams?.role&&(c.role=o.dtlsParams.role==="client"?"server":"client"),d});n=n.filter(o=>!!o);let i=this.transceiverManager.getTransceivers().filter(o=>e.media.find(a=>s(o,a))==null);if(t.type==="answer")for(let o of i)o.stop(),o.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(Bn("caller start connect"),this.connect().catch(o=>{Bn("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(t,e={}){let r=this.findOrCreateTransport(),s=this.transceiverManager.addTransceiver(t,r,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),s}addTrack(t,e){if(this.isClosed)throw new Error("is closed");let r=this.transceiverManager.addTrack(t,e);if(!r.dtlsTransport){let s=this.findOrCreateTransport();r.setDtlsTransport(s)}return this.needNegotiation(),r.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(t){Bn("signalingStateChange",t),this.signalingState=t,this.signalingStateChange.execute(t),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let t=Ya();return{type:"peer-connection",id:Ft("peer-connection"),timestamp:t,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(t){let e=[];e.push(this.createPeerConnectionStats());let r=await this.transceiverManager.getStats(t);e.push(...r);let s=await this.secureManager.getStats();if(e.push(...s),this.sctpTransport){let n=await this.sctpManager.getStats();n&&e.push(...n)}return new N7(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),Bn("peerConnection closed"))}},eT=(t,e)=>t.find(r=>r.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;RQ=NU(),PQ=dt("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),OU=class{constructor(t,e,r){this.cname=t,this.config=e,this.router=r}transceivers=[];onTransceiverAdded=new Be;onRemoteTransceiverAdded=new Be;onTrack=new Be;onNegotiationNeeded=new Be;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(t=>t.sender)}getReceivers(){return this.getTransceivers().map(t=>t.receiver)}getTransceiverByMLineIndex(t){return this.transceivers.find(e=>e.mLineIndex===t)}pushTransceiver(t){this.transceivers.push(t)}replaceTransceiver(t,e){this.transceivers[e]=t}addTransceiver(t,e,r={}){let s=typeof t=="string"?t:t.kind,n=r.direction||"sendrecv",i=new PU(t),o=new ZT(this.config,s,i.ssrc),a=new O7(s,e,o,i,n);a.options=r,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(u=>u.currentDirection==="inactive"&&!u.usedForSender),d=this.transceivers.find(u=>u.currentDirection==="inactive"&&!u.usedForSender);return c>-1&&d?(this.replaceTransceiver(a,c),a.mLineIndex=d.mLineIndex,a.mid=d.mid,d.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(t,e){if(this.getSenders().find(n=>n.track?.uuid===t.uuid))throw new Error("Track already added");let r=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&Ab.includes(n.direction)===!0);if(r)return r.sender.registerTrack(t),r;let s=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&Ab.includes(n.direction)===!1&&!n.usedForSender);if(s){switch(s.sender.registerTrack(t),s.direction){case"recvonly":s.setDirection("sendrecv");break;case"inactive":s.setDirection("sendonly");break}return s}else return this.addTransceiver(t,void 0,{direction:"sendrecv"})}removeTrack(t){if(!this.getSenders().find(({ssrc:r})=>t.ssrc===r))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:r}})=>t.ssrc===r);if(!e)throw new Error("No matching transceiver found");if(t.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(t){let e=this.config.codecs[t.kind].filter(r=>{switch(r.direction){case"recvonly":return!!LJ.includes(t.direction);case"sendonly":return!!Ab.includes(t.direction);case"sendrecv":return!![jT,MT,UT].includes(t.direction);case"all":return!0;default:return!1}});t.codecs=e}getLocalRtpParams(t){if(t.mid==null)throw new Error("mid not assigned");return{codecs:t.codecs,muxId:t.mid,headerExtensions:t.headerExtensions,rtcp:{cname:this.cname,ssrc:t.sender.ssrc,mux:!0}}}getRemoteRtpParams(t,e){return{muxId:t.rtp.muxId,rtcp:t.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((s,n)=>{if(n.name.toLowerCase()==="rtx"){let i=em(n.parameters??""),o=s[i.apt];return o&&t.ssrc.length===2&&(o.rtx=new E7({ssrc:t.ssrc[1].ssrc})),s}return s[n.payloadType]=new C7({ssrc:t.ssrc[0]?.ssrc,payloadType:n.payloadType}),s},{}))}}setRemoteRTP(t,e,r,s){if(t.mid||(t.mid=e.rtp.muxId),t.mLineIndex=s,t.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],d=eT(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let l=em(d.parameters??"").apt,f=e.rtp.codecs.find(h=>h.payloadType===l);return f?!!eT(c,f):!1}return!0}),PQ("negotiated codecs",t.codecs),t.codecs.length===0)throw new Error("negotiate codecs failed.");t.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let n=e.direction??"inactive",i=j7(n);["answer","pranswer"].includes(r)?t.setCurrentDirection(i):t.offerDirection=i;let o=this.getLocalRtpParams(t);if(t.sender.prepareSend(o),["recvonly","sendrecv"].includes(t.direction)){let a=this.getRemoteRtpParams(e,t);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(t,c,a);t.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(t,a)}if(["sendonly","sendrecv"].includes(n)){if(e.msid){let[a,c]=e.msid.split(" ");t.receiver.remoteStreamId=a,t.receiver.remoteTrackId=c}this.onTrack.execute({track:t.receiver.track,transceiver:t,stream:new U7({id:t.receiver.remoteStreamId,tracks:[t.receiver.track]})})}e.ssrc[0]?.ssrc&&t.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(t){let e=[];for(let r of this.transceivers){let s=!t||r.sender.track===t||r.receiver.track===t;if(r.sender){let n=await r.sender.getStats();if(n)for(let i of n)i.type==="outbound-rtp"||i.type==="media-source"?s&&e.push(i):e.push(i)}if(r.receiver){let n=await r.receiver.getStats();if(n)for(let i of n)i.type==="inbound-rtp"||i.type==="remote-outbound-rtp"?s&&e.push(i):e.push(i)}if(s){let n=r.getCodecStats();n&&e.push(...n)}}return e}close(){for(let t of this.transceivers)t.receiver.stop(),t.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},BQ=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],DQ=["closed","failed","disconnected","new","connecting","connected"]});var Fre={};ic(Fre,{SessionPool:()=>q1,URUN_API:()=>zA,coalesceSameRole:()=>aF,createUrunExtension:()=>K1,default:()=>jre,makeSessionFactory:()=>z1,makeStreamSimple:()=>cF,resolveSessionEnv:()=>iF,toResponsesInput:()=>oF});module.exports=GA(Fre);g();var h3e=Fe(Y1(),1);var $A={};ic($A,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>lte,ACTIVATION_DEGRADED_AFTER_MS:()=>ute,ACTIVATION_HINT_PATH:()=>gj,ACTIVATION_STILL_AFTER_MS:()=>dte,ACTIVITY_DOM_EVENTS:()=>OA,ACTIVITY_FIELD:()=>Tj,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>vte,ActivationMonitor:()=>bj,App:()=>Gte,BACKOFF_BASE_MS:()=>T1,BACKOFF_MAX_ATTEMPTS:()=>lf,BACKOFF_MAX_MS:()=>A1,CaptureController:()=>Gj,CaptureUnavailableError:()=>Wj,ClientTokenError:()=>Am,DATA_CHANNEL_MESSAGE_CEILING:()=>dre,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>Vj,DEFAULT_GATEWAY_URL:()=>Kj,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>pm,DEFAULT_REFERENCE_JPEG_QUALITY:()=>cre,DEFAULT_REFERENCE_MAX_SIZE:()=>are,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>yA,DERIVED_LEG_SEP:()=>gm,DGRAM_HEADER_BYTES:()=>F1,FOREGROUND_COALESCE_MS:()=>_te,FrameReassembler:()=>Uj,INPUT_PRESENCE_DEFAULT_HZ:()=>ire,INPUT_PRESENCE_FIELD:()=>Xj,InvalidDurationError:()=>H1,LEGACY_ACTIVATION_HINT_PATH:()=>yj,PLATFORM_DOC_NAME:()=>mj,PermanentLockedError:()=>Cj,PinRequiresActiveTempError:()=>Ej,ProduceAckTimeoutError:()=>hA,RecordingNotFoundError:()=>_j,RecordingsClient:()=>jA,RecordingsError:()=>Uo,RecordingsUnauthorizedError:()=>UA,RequestAbortError:()=>C1,RequestCancelledError:()=>pA,RequestDocSyncError:()=>uA,RequestError:()=>ec,RequestTimeoutError:()=>lA,RetainNotTempError:()=>Sj,RuntimeArtifactNotFoundError:()=>vj,RuntimeArtifactsClient:()=>j1,RuntimeArtifactsError:()=>an,RuntimeArtifactsUnauthorizedError:()=>wj,Session:()=>qj,SessionAllocationError:()=>Mn,SessionEndError:()=>Wd,SessionEndUnavailableError:()=>E1,SessionFailedError:()=>Xd,StreamDirectionConflict:()=>fA,TransportNegotiator:()=>jj,TransportSessionMismatchError:()=>x1,TransportSessionSignaling:()=>Fj,VISIBILITY_FIELD:()=>Aj,WIRE_MESSAGE_BUDGET:()=>lre,WT_CONTROL_FRAME_MAX:()=>Dj,WebRtcSession:()=>Hj,WebTransportSession:()=>Mj,WtControlDecoder:()=>Oj,activationHintFrom:()=>xj,cameraCaptureAvailable:()=>gre,captureStillFromVideo:()=>yre,computeBackoffDelay:()=>_m,createActivityTracker:()=>kj,createCameraWarp:()=>bre,createClientToken:()=>Xte,createInputPresencePublisher:()=>ore,createRecordingsClient:()=>wte,createRuntimeArtifactsClient:()=>hte,createStore:()=>Jte,derivedLegName:()=>UM,derivedLegRole:()=>wA,describeSessionFailure:()=>mA,describeSessionPhase:()=>_M,encodeWtControlFrame:()=>Nj,fitWithin:()=>HA,isDurationString:()=>MA,isPendingRecording:()=>ere,isRetryableSessionError:()=>k1,isWakingPhase:()=>gA,mediaRecorderChunkSource:()=>Bj,normalizeReferenceImage:()=>pre,normalizeRetention:()=>xte,observeLeaveConfirm:()=>Pj,observePageLifecycle:()=>Ij,observePageTeardown:()=>Rj,parseDgramHeader:()=>Lj,prewake:()=>PM,referenceImageErrorMessage:()=>mre,releaseSessionBeacon:()=>bA,sessionFailureFromMediaError:()=>vM,sharedCaptureController:()=>nre,videoStream:()=>Zte,whenLive:()=>xA,writeDgramHeader:()=>Cte});g();var pj=require("module");g();var oM=require("module"),_1=Fe(require("process"),1),uM=Fe(require("os"),1),rA=Fe(require("tty"),1);g();g();g();g();var Kr=()=>new Map,Pm=t=>{let e=Kr();return t.forEach((r,s)=>{e.set(s,r)}),e},As=(t,e,r)=>{let s=t.get(e);return s===void 0&&t.set(e,s=r()),s};var YA=(t,e)=>{for(let[r,s]of t)if(e(s,r))return!0;return!1};g();var Hn=()=>new Set;g();var Dm=t=>t[t.length-1];var JA=(t,e)=>{for(let r=0;r<e.length;r++)t.push(e[r])},cn=Array.from;var Q1=Array.isArray;var el=class{constructor(){this._observers=Kr()}on(e,r){return As(this._observers,e,Hn).add(r),r}once(e,r){let s=(...n)=>{this.off(e,s),r(...n)};this.on(e,s)}off(e,r){let s=this._observers.get(e);s!==void 0&&(s.delete(r),s.size===0&&this._observers.delete(e))}emit(e,r){return cn((this._observers.get(e)||Kr()).values()).forEach(s=>s(...r))}destroy(){this._observers=Kr()}},Nm=class{constructor(){this._observers=Kr()}on(e,r){As(this._observers,e,Hn).add(r)}once(e,r){let s=(...n)=>{this.off(e,s),r(...n)};this.on(e,s)}off(e,r){let s=this._observers.get(e);s!==void 0&&(s.delete(r),s.size===0&&this._observers.delete(e))}emit(e,r){return cn((this._observers.get(e)||Kr()).values()).forEach(s=>s(...r))}destroy(){this._observers=Kr()}};g();var as=Math.floor;var tl=Math.abs;var rl=(t,e)=>t<e?t:e,Pi=(t,e)=>t>e?t:e,Jre=Number.isNaN,QA=Math.pow;var Om=t=>t!==0?t<0:1/t<0;g();g();var ew=Number.MAX_SAFE_INTEGER,Zre=Number.MIN_SAFE_INTEGER,ese=1<<31;var ZA=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&as(t)===t),tse=Number.isNaN,rse=Number.parseInt;g();var tw=String.fromCharCode,nse=String.fromCodePoint,ise=tw(65535),mF=t=>t.toLowerCase(),gF=/^\s*/g,yF=t=>t.replace(gF,""),xF=/([A-Z])/g,rw=(t,e)=>yF(t.replace(xF,r=>`${e}${mF(r)}`));var bF=t=>{let e=unescape(encodeURIComponent(t)),r=e.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=e.codePointAt(n);return s},il=typeof TextEncoder<"u"?new TextEncoder:null,wF=t=>il.encode(t),tk=il?wF:bF;var nl=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});nl&&nl.decode(new Uint8Array).length===1&&(nl=null);var oc=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},yr=()=>new oc;var Mm=t=>{let e=t.cpos;for(let r=0;r<t.bufs.length;r++)e+=t.bufs[r].length;return e};var $t=t=>{let e=new Uint8Array(Mm(t)),r=0;for(let s=0;s<t.bufs.length;s++){let n=t.bufs[s];e.set(n,r),r+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),r),e},vF=(t,e)=>{let r=t.cbuf.length;r-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(Pi(r,e)*2),t.cpos=0)},Cr=(t,e)=>{let r=t.cbuf.length;t.cpos===r&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(r*2),t.cpos=0),t.cbuf[t.cpos++]=e};var jm=Cr;var ze=(t,e)=>{for(;e>127;)Cr(t,128|127&e),e=as(e/128);Cr(t,127&e)},Fm=(t,e)=>{let r=Om(e);for(r&&(e=-e),Cr(t,(e>63?128:0)|(r?64:0)|63&e),e=as(e/64);e>0;)Cr(t,(e>127?128:0)|127&e),e=as(e/128)},sw=new Uint8Array(3e4),_F=sw.length/3,SF=(t,e)=>{if(e.length<_F){let r=il.encodeInto(e,sw).written||0;ze(t,r);for(let s=0;s<r;s++)Cr(t,sw[s])}else Jt(t,tk(e))},EF=(t,e)=>{let r=unescape(encodeURIComponent(e)),s=r.length;ze(t,s);for(let n=0;n<s;n++)Cr(t,r.codePointAt(n))},Bi=il&&il.encodeInto?SF:EF;var Ef=(t,e)=>{let r=t.cbuf.length,s=t.cpos,n=rl(r-s,e.length),i=e.length-n;t.cbuf.set(e.subarray(0,n),s),t.cpos+=n,i>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Pi(r*2,i)),t.cbuf.set(e.subarray(n)),t.cpos=i)},Jt=(t,e)=>{ze(t,e.byteLength),Ef(t,e)},nw=(t,e)=>{vF(t,e);let r=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,r},CF=(t,e)=>nw(t,4).setFloat32(0,e,!1),TF=(t,e)=>nw(t,8).setFloat64(0,e,!1),AF=(t,e)=>nw(t,8).setBigInt64(0,e,!1);var sk=new DataView(new ArrayBuffer(4)),kF=t=>(sk.setFloat32(0,t),sk.getFloat32(0)===t),al=(t,e)=>{switch(typeof e){case"string":Cr(t,119),Bi(t,e);break;case"number":ZA(e)&&tl(e)<=2147483647?(Cr(t,125),Fm(t,e)):kF(e)?(Cr(t,124),CF(t,e)):(Cr(t,123),TF(t,e));break;case"bigint":Cr(t,122),AF(t,e);break;case"object":if(e===null)Cr(t,126);else if(Q1(e)){Cr(t,117),ze(t,e.length);for(let r=0;r<e.length;r++)al(t,e[r])}else if(e instanceof Uint8Array)Cr(t,116),Jt(t,e);else{Cr(t,118);let r=Object.keys(e);ze(t,r.length);for(let s=0;s<r.length;s++){let n=r[s];Bi(t,n),al(t,e[n])}}break;case"boolean":Cr(t,e?120:121);break;default:Cr(t,127)}},Sf=class extends oc{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ze(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};var nk=t=>{t.count>0&&(Fm(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ze(t.encoder,t.count-2))},ac=class{constructor(){this.encoder=new oc,this.s=0,this.count=0}write(e){this.s===e?this.count++:(nk(this),this.count=1,this.s=e)}toUint8Array(){return nk(this),$t(this.encoder)}};var ik=t=>{if(t.count>0){let e=t.diff*2+(t.count===1?0:1);Fm(t.encoder,e),t.count>1&&ze(t.encoder,t.count-2)}},cl=class{constructor(){this.encoder=new oc,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ik(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ik(this),$t(this.encoder)}},Um=class{constructor(){this.sarr=[],this.s="",this.lensE=new ac}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){let e=new oc;return this.sarr.push(this.s),this.s="",Bi(e,this.sarr.join("")),Ef(e,this.lensE.toUint8Array()),$t(e)}};g();g();var $n=t=>new Error(t),dn=()=>{throw $n("Method unimplemented")},ln=()=>{throw $n("Unexpected case")};var ak=$n("Unexpected end of array"),ck=$n("Integer out of Range"),dl=class{constructor(e){this.arr=e,this.pos=0}},fn=t=>new dl(t),dk=t=>t.pos!==t.arr.length;var IF=(t,e)=>{let r=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,r},xr=t=>IF(t,Ze(t));var cc=t=>t.arr[t.pos++];var Ze=t=>{let e=0,r=1,s=t.arr.length;for(;t.pos<s;){let n=t.arr[t.pos++];if(e=e+(n&127)*r,r*=128,n<128)return e;if(e>ew)throw ck}throw ak},Vm=t=>{let e=t.arr[t.pos++],r=e&63,s=64,n=(e&64)>0?-1:1;if((e&128)===0)return n*r;let i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],r=r+(e&127)*s,s*=128,e<128)return n*r;if(r>ew)throw ck}throw ak};var RF=t=>{let e=Ze(t);if(e===0)return"";{let r=String.fromCodePoint(cc(t));if(--e<100)for(;e--;)r+=String.fromCodePoint(cc(t));else for(;e>0;){let s=e<1e4?e:1e4,n=t.arr.subarray(t.pos,t.pos+s);t.pos+=s,r+=String.fromCodePoint.apply(null,n),e-=s}return decodeURIComponent(escape(r))}},PF=t=>nl.decode(xr(t)),un=nl?PF:RF;var iw=(t,e)=>{let r=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,r},BF=t=>iw(t,4).getFloat32(0,!1),DF=t=>iw(t,8).getFloat64(0,!1),NF=t=>iw(t,8).getBigInt64(0,!1);var OF=[t=>{},t=>null,Vm,BF,DF,NF,t=>!1,t=>!0,un,t=>{let e=Ze(t),r={};for(let s=0;s<e;s++){let n=un(t);r[n]=ll(t)}return r},t=>{let e=Ze(t),r=[];for(let s=0;s<e;s++)r.push(ll(t));return r},xr],ll=t=>OF[127-cc(t)](t),Cf=class extends dl{constructor(e,r){super(e),this.reader=r,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),dk(this)?this.count=Ze(this)+1:this.count=-1),this.count--,this.s}};var dc=class extends dl{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vm(this);let e=Om(this.s);this.count=1,e&&(this.s=-this.s,this.count=Ze(this)+2)}return this.count--,this.s}};var ul=class extends dl{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Vm(this),r=e&1;this.diff=as(e/2),this.count=1,r&&(this.count=Ze(this)+2)}return this.s+=this.diff,this.count--,this.s}},$m=class{constructor(e){this.decoder=new dc(e),this.str=un(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),r=this.str.slice(this.spos,e);return this.spos=e,r}};g();g();var qm=require("crypto"),fse=qm.webcrypto.subtle,lk=qm.webcrypto.getRandomValues.bind(qm.webcrypto);var ow=()=>lk(new Uint32Array(1))[0];var LF="10000000-1000-4000-8000"+-1e11,uk=()=>LF.replace(/[018]/g,t=>(t^ow()&15>>t/4).toString(16));g();g();var hn=Date.now;var cw=t=>new Promise(t);var xse=Promise.all.bind(Promise);g();g();g();var dw=t=>t===void 0?null:t;g();var lw=class{constructor(){this.map=new Map}setItem(e,r){this.map.set(e,r)}getItem(e){return this.map.get(e)}},fk=new lw,uw=!0;try{typeof localStorage<"u"&&localStorage&&(fk=localStorage,uw=!1)}catch{}var zm=fk,hk=t=>uw||addEventListener("storage",t),pk=t=>uw||removeEventListener("storage",t);g();g();g();var Km=Symbol("Equality"),gk=(t,e)=>t===e||!!t?.[Km]?.(e)||!1;var xk=Object.assign,FF=Object.keys;var bk=(t,e)=>{for(let r in t)e(t[r],r)},wk=(t,e)=>{let r=[];for(let s in t)r.push(e(t[s],s));return r};var Af=t=>FF(t).length;var vk=t=>{for(let e in t)return!1;return!0},HF=(t,e)=>{for(let r in t)if(!e(t[r],r))return!1;return!0},fw=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),hw=(t,e)=>t===e||Af(t)===Af(e)&&HF(t,(r,s)=>(r!==void 0||fw(e,s))&&gk(e[s],r)),$F=Object.freeze,pw=t=>{for(let e in t){let r=t[e];(typeof r=="object"||typeof r=="function")&&pw(t[e])}return $F(t)};var kf=(t,e,r=0)=>{try{for(;r<t.length;r++)t[r](...e)}finally{r<t.length&&kf(t,e,r+1)}};var _k=t=>t;var fl=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[Km]!=null)return t[Km](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;break}case Set:{if(t.size!==e.size)return!1;for(let r of t)if(!e.has(r))return!1;break}case Map:{if(t.size!==e.size)return!1;for(let r of t.keys())if(!e.has(r)||!fl(t.get(r),e.get(r)))return!1;break}case void 0:case Object:if(Af(t)!==Af(e))return!1;for(let r in t)if(!fw(t,r)||!fl(t[r],e[r]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!fl(t[r],e[r]))return!1;break;default:return!1}return!0},Sk=(t,e)=>e.includes(t);var Di=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",xw=typeof window<"u"&&typeof document<"u"&&!Di,Cse=typeof navigator<"u"?/Mac/.test(navigator.platform):!1,Vn,VF=[],qF=()=>{if(Vn===void 0)if(Di){Vn=Kr();let t=process.argv,e=null;for(let r=0;r<t.length;r++){let s=t[r];s[0]==="-"?(e!==null&&Vn.set(e,""),e=s):e!==null?(Vn.set(e,s),e=null):VF.push(s)}e!==null&&Vn.set(e,"")}else typeof location=="object"?(Vn=Kr(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){let[e,r]=t.split("=");Vn.set(`--${rw(e,"-")}`,r),Vn.set(`-${rw(e,"-")}`,r)}})):Vn=Kr();return Vn},yw=t=>qF().has(t);var If=t=>Di?dw(process.env[t.toUpperCase().replaceAll("-","_")]):dw(zm.getItem(t));var Ek=t=>yw("--"+t)||If(t)!==null,Tse=Ek("production"),zF=Di&&Sk(process.env.FORCE_COLOR,["true","1","2"]),Ck=zF||!yw("--no-colors")&&!Ek("no-color")&&(!Di||process.stdout.isTTY)&&(!Di||yw("--color")||If("COLORTERM")!==null||(If("TERM")||"").includes("color"));var Tk=t=>new Uint8Array(t),KF=(t,e,r)=>new Uint8Array(t,e,r),Ak=t=>new Uint8Array(t),WF=t=>{let e="";for(let r=0;r<t.byteLength;r++)e+=tw(t[r]);return btoa(e)},GF=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),XF=t=>{let e=atob(t),r=Tk(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r},YF=t=>{let e=Buffer.from(t,"base64");return KF(e.buffer,e.byteOffset,e.byteLength)},kk=xw?WF:GF,Ik=xw?XF:YF;var Rk=t=>{let e=Tk(t.byteLength);return e.set(t),e};g();g();g();var qn=Symbol;var Rf=qn(),Pf=qn(),bw=qn(),ww=qn(),vw=qn(),Bf=qn(),_w=qn(),Df=qn(),Sw=qn(),Bk=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());let e=[],r=[],s=0;for(;s<t.length;s++){let n=t[s];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)e.push(n);else if(n.constructor===Object)break}for(s>0&&r.push(e.join(""));s<t.length;s++){let n=t[s];n instanceof Symbol||r.push(n)}return r};var Rse=hn();var ZF={[Rf]:"\x1B[1m",[Pf]:"\x1B[2m",[bw]:"\x1B[34m",[vw]:"\x1B[32m",[ww]:"\x1B[37m",[Bf]:"\x1B[31m",[_w]:"\x1B[35m",[Df]:"\x1B[38;5;208m",[Sw]:"\x1B[0m"},eH=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());let e=[],r=[],s=0;for(;s<t.length;s++){let n=t[s],i=ZF[n];if(i!==void 0)e.push(i);else{if(n===void 0)break;if(n.constructor===String||n.constructor===Number)e.push(n);else break}}for(s>0&&(e.push("\x1B[0m"),r.push(e.join("")));s<t.length;s++){let n=t[s];n instanceof Symbol||r.push(n)}return r},Dk=Ck?eH:Bk,Nk=(...t)=>{console.log(...Dk(t))},Ok=(...t)=>{console.warn(...Dk(t))};g();var Lk=t=>({[Symbol.iterator](){return this},next:t}),Uk=(t,e)=>Lk(()=>{let r;do r=t.next();while(!r.done&&!e(r.value));return r}),Gm=(t,e)=>Lk(()=>{let{done:r,value:s}=t.next();return{done:r,value:r?void 0:e(s)}});var pl=class{constructor(e,r){this.clock=e,this.len=r}},lc=class{constructor(){this.clients=new Map}},Jk=(t,e,r)=>e.clients.forEach((s,n)=>{let i=t.doc.store.clients.get(n);if(i!=null){let o=i[i.length-1],a=o.id.clock+o.length;for(let c=0,d=s[c];c<s.length&&d.clock<a;d=s[++c])d6(t,i,d.clock,d.len,r)}}),iH=(t,e)=>{let r=0,s=t.length-1;for(;r<=s;){let n=as((r+s)/2),i=t[n],o=i.clock;if(o<=e){if(e<o+i.len)return n;r=n+1}else s=n-1}return null},Qk=(t,e)=>{let r=t.clients.get(e.client);return r!==void 0&&iH(r,e.clock)!==null},Hw=t=>{t.clients.forEach(e=>{e.sort((n,i)=>n.clock-i.clock);let r,s;for(r=1,s=1;r<e.length;r++){let n=e[s-1],i=e[r];n.clock+n.len>=i.clock?e[s-1]=new pl(n.clock,Pi(n.len,i.clock+i.len-n.clock)):(s<r&&(e[s]=i),s++)}e.length=s})},oH=t=>{let e=new lc;for(let r=0;r<t.length;r++)t[r].clients.forEach((s,n)=>{if(!e.clients.has(n)){let i=s.slice();for(let o=r+1;o<t.length;o++)JA(i,t[o].clients.get(n)||[]);e.clients.set(n,i)}});return Hw(e),e},eg=(t,e,r,s)=>{As(t.clients,e,()=>[]).push(new pl(r,s))},Zk=()=>new lc,aH=t=>{let e=Zk();return t.clients.forEach((r,s)=>{let n=[];for(let i=0;i<r.length;i++){let o=r[i];if(o.deleted){let a=o.id.clock,c=o.length;if(i+1<r.length)for(let d=r[i+1];i+1<r.length&&d.deleted;d=r[++i+1])c+=d.length;n.push(new pl(a,c))}}n.length>0&&e.clients.set(s,n)}),e},xl=(t,e)=>{ze(t.restEncoder,e.clients.size),cn(e.clients.entries()).sort((r,s)=>s[0]-r[0]).forEach(([r,s])=>{t.resetDsCurVal(),ze(t.restEncoder,r);let n=s.length;ze(t.restEncoder,n);for(let i=0;i<n;i++){let o=s[i];t.writeDsClock(o.clock),t.writeDsLen(o.len)}})},$w=t=>{let e=new lc,r=Ze(t.restDecoder);for(let s=0;s<r;s++){t.resetDsCurVal();let n=Ze(t.restDecoder),i=Ze(t.restDecoder);if(i>0){let o=As(e.clients,n,()=>[]);for(let a=0;a<i;a++)o.push(new pl(t.readDsClock(),t.readDsLen()))}}return e},Fk=(t,e,r)=>{let s=new lc,n=Ze(t.restDecoder);for(let i=0;i<n;i++){t.resetDsCurVal();let o=Ze(t.restDecoder),a=Ze(t.restDecoder),c=r.clients.get(o)||[],d=Tr(r,o);for(let u=0;u<a;u++){let l=t.readDsClock(),f=l+t.readDsLen();if(l<d){d<f&&eg(s,o,d,f-d);let h=zn(c,l),m=c[h];for(!m.deleted&&m.id.clock<l&&(c.splice(h+1,0,ug(e,m,l-m.id.clock)),h++);h<c.length&&(m=c[h++],m.id.clock<f);)m.deleted||(f<m.id.clock+m.length&&c.splice(h,0,ug(e,m,f-m.id.clock)),m.delete(e))}else eg(s,o,l,f-l)}}if(s.clients.size>0){let i=new Ni;return ze(i.restEncoder,0),xl(i,s),i.toUint8Array()}return null};var e6=ow,uc=class t extends el{constructor({guid:e=uk(),collectionid:r=null,gc:s=!0,gcFilter:n=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=s,this.gcFilter=n,this.clientID=e6(),this.guid=e,this.collectionid=r,this.share=new Map,this.store=new ig,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=cw(d=>{this.on("load",()=>{this.isLoaded=!0,d(this)})});let c=()=>cw(d=>{let u=l=>{(l===void 0||l===!0)&&(this.off("sync",u),d())};this.on("sync",u)});this.on("sync",d=>{d===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=d===void 0||d===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Vt(e.parent.doc,r=>{r.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(cn(this.subdocs).map(e=>e.guid))}transact(e,r=null){return Vt(this,e,r)}get(e,r=br){let s=As(this.share,e,()=>{let i=new r;return i._integrate(this,null),i}),n=s.constructor;if(r!==br&&n!==r)if(n===br){let i=new r;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=""){return this.get(e,dg)}getText(e=""){return this.get(e,Ff)}getMap(e=""){return this.get(e,qo)}getXmlElement(e=""){return this.get(e,Hf)}getXmlFragment(e=""){return this.get(e,gl)}toJSON(){let e={};return this.share.forEach((r,s)=>{e[s]=r.toJSON()}),e}destroy(){this.isDestroyed=!0,cn(this.subdocs).forEach(r=>r.destroy());let e=this._item;if(e!==null){this._item=null;let r=e.content;r.doc=new t({guid:this.guid,...r.opts,shouldLoad:!1}),r.doc._item=e,Vt(e.parent.doc,s=>{let n=r.doc;e.deleted||s.subdocsAdded.add(n),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},tg=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Ze(this.restDecoder)}readDsLen(){return Ze(this.restDecoder)}},rg=class extends tg{readLeftID(){return Et(Ze(this.restDecoder),Ze(this.restDecoder))}readRightID(){return Et(Ze(this.restDecoder),Ze(this.restDecoder))}readClient(){return Ze(this.restDecoder)}readInfo(){return cc(this.restDecoder)}readString(){return un(this.restDecoder)}readParentInfo(){return Ze(this.restDecoder)===1}readTypeRef(){return Ze(this.restDecoder)}readLen(){return Ze(this.restDecoder)}readAny(){return ll(this.restDecoder)}readBuf(){return Rk(xr(this.restDecoder))}readJSON(){return JSON.parse(un(this.restDecoder))}readKey(){return un(this.restDecoder)}},Tw=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ze(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Ze(this.restDecoder)+1;return this.dsCurrVal+=e,e}},$o=class extends Tw{constructor(e){super(e),this.keys=[],Ze(e),this.keyClockDecoder=new ul(xr(e)),this.clientDecoder=new dc(xr(e)),this.leftClockDecoder=new ul(xr(e)),this.rightClockDecoder=new ul(xr(e)),this.infoDecoder=new Cf(xr(e),cc),this.stringDecoder=new $m(xr(e)),this.parentInfoDecoder=new Cf(xr(e),cc),this.typeRefDecoder=new dc(xr(e)),this.lenDecoder=new dc(xr(e))}readLeftID(){return new Ho(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Ho(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ll(this.restDecoder)}readBuf(){return xr(this.restDecoder)}readJSON(){return ll(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let r=this.stringDecoder.read();return this.keys.push(r),r}}},sg=class{constructor(){this.restEncoder=yr()}toUint8Array(){return $t(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ze(this.restEncoder,e)}writeDsLen(e){ze(this.restEncoder,e)}},fc=class extends sg{writeLeftID(e){ze(this.restEncoder,e.client),ze(this.restEncoder,e.clock)}writeRightID(e){ze(this.restEncoder,e.client),ze(this.restEncoder,e.clock)}writeClient(e){ze(this.restEncoder,e)}writeInfo(e){jm(this.restEncoder,e)}writeString(e){Bi(this.restEncoder,e)}writeParentInfo(e){ze(this.restEncoder,e?1:0)}writeTypeRef(e){ze(this.restEncoder,e)}writeLen(e){ze(this.restEncoder,e)}writeAny(e){al(this.restEncoder,e)}writeBuf(e){Jt(this.restEncoder,e)}writeJSON(e){Bi(this.restEncoder,JSON.stringify(e))}writeKey(e){Bi(this.restEncoder,e)}},ng=class{constructor(){this.restEncoder=yr(),this.dsCurrVal=0}toUint8Array(){return $t(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let r=e-this.dsCurrVal;this.dsCurrVal=e,ze(this.restEncoder,r)}writeDsLen(e){e===0&&ln(),ze(this.restEncoder,e-1),this.dsCurrVal+=e}},Ni=class extends ng{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new cl,this.clientEncoder=new ac,this.leftClockEncoder=new cl,this.rightClockEncoder=new cl,this.infoEncoder=new Sf(jm),this.stringEncoder=new Um,this.parentInfoEncoder=new Sf(jm),this.typeRefEncoder=new ac,this.lenEncoder=new ac}toUint8Array(){let e=yr();return ze(e,0),Jt(e,this.keyClockEncoder.toUint8Array()),Jt(e,this.clientEncoder.toUint8Array()),Jt(e,this.leftClockEncoder.toUint8Array()),Jt(e,this.rightClockEncoder.toUint8Array()),Jt(e,$t(this.infoEncoder)),Jt(e,this.stringEncoder.toUint8Array()),Jt(e,$t(this.parentInfoEncoder)),Jt(e,this.typeRefEncoder.toUint8Array()),Jt(e,this.lenEncoder.toUint8Array()),Ef(e,$t(this.restEncoder)),$t(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){al(this.restEncoder,e)}writeBuf(e){Jt(this.restEncoder,e)}writeJSON(e){al(this.restEncoder,e)}writeKey(e){let r=this.keyMap.get(e);r===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(r)}},cH=(t,e,r,s)=>{s=Pi(s,e[0].id.clock);let n=zn(e,s);ze(t.restEncoder,e.length-n),t.writeClient(r),ze(t.restEncoder,s);let i=e[n];i.write(t,s-i.id.clock);for(let o=n+1;o<e.length;o++)e[o].write(t,0)},Vw=(t,e,r)=>{let s=new Map;r.forEach((n,i)=>{Tr(e,i)>n&&s.set(i,n)}),fg(e).forEach((n,i)=>{r.has(i)||s.set(i,0)}),ze(t.restEncoder,s.size),cn(s.entries()).sort((n,i)=>i[0]-n[0]).forEach(([n,i])=>{cH(t,e.clients.get(n),n,i)})},dH=(t,e)=>{let r=Kr(),s=Ze(t.restDecoder);for(let n=0;n<s;n++){let i=Ze(t.restDecoder),o=new Array(i),a=t.readClient(),c=Ze(t.restDecoder);r.set(a,{i:0,refs:o});for(let d=0;d<i;d++){let u=t.readInfo();switch(31&u){case 0:{let l=t.readLen();o[d]=new cs(Et(a,c),l),c+=l;break}case 10:{let l=Ze(t.restDecoder);o[d]=new ds(Et(a,c),l),c+=l;break}default:{let l=(u&192)===0,f=new Ar(Et(a,c),null,(u&128)===128?t.readLeftID():null,null,(u&64)===64?t.readRightID():null,l?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,l&&(u&32)===32?t.readString():null,k6(t,u));o[d]=f,c+=f.length}}}}return r},lH=(t,e,r)=>{let s=[],n=cn(r.keys()).sort((h,m)=>h-m);if(n.length===0)return null;let i=()=>{if(n.length===0)return null;let h=r.get(n[n.length-1]);for(;h.refs.length===h.i;)if(n.pop(),n.length>0)h=r.get(n[n.length-1]);else return null;return h},o=i();if(o===null)return null;let a=new ig,c=new Map,d=(h,m)=>{let v=c.get(h);(v==null||v>m)&&c.set(h,m)},u=o.refs[o.i++],l=new Map,f=()=>{for(let h of s){let m=h.id.client,v=r.get(m);v?(v.i--,a.clients.set(m,v.refs.slice(v.i)),r.delete(m),v.i=0,v.refs=[]):a.clients.set(m,[h]),n=n.filter(p=>p!==m)}s.length=0};for(;;){if(u.constructor!==ds){let m=As(l,u.id.client,()=>Tr(e,u.id.client))-u.id.clock;if(m<0)s.push(u),d(u.id.client,u.id.clock-1),f();else{let v=u.getMissing(t,e);if(v!==null){s.push(u);let p=r.get(v)||{refs:[],i:0};if(p.refs.length===p.i)d(v,Tr(e,v)),f();else{u=p.refs[p.i++];continue}}else(m===0||m<u.length)&&(u.integrate(t,m),l.set(u.id.client,u.id.clock+u.length))}}if(s.length>0)u=s.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=i(),o===null)break;u=o.refs[o.i++]}}if(a.clients.size>0){let h=new Ni;return Vw(h,a,new Map),ze(h.restEncoder,0),{missing:c,update:h.toUint8Array()}}return null},uH=(t,e)=>Vw(t,e.doc.store,e.beforeState),fH=(t,e,r,s=new $o(t))=>Vt(e,n=>{n.local=!1;let i=!1,o=n.doc,a=o.store,c=dH(s,o),d=lH(n,a,c),u=a.pendingStructs;if(u){for(let[f,h]of u.missing)if(h<Tr(a,f)){i=!0;break}if(d){for(let[f,h]of d.missing){let m=u.missing.get(f);(m==null||m>h)&&u.missing.set(f,h)}u.update=og([u.update,d.update])}}else a.pendingStructs=d;let l=Fk(s,n,a);if(a.pendingDs){let f=new $o(fn(a.pendingDs));Ze(f.restDecoder);let h=Fk(f,n,a);l&&h?a.pendingDs=og([l,h]):a.pendingDs=l||h}else a.pendingDs=l;if(i){let f=a.pendingStructs.update;a.pendingStructs=null,t6(n.doc,f)}},r,!1);var t6=(t,e,r,s=$o)=>{let n=fn(e);fH(n,t,r,new s(n))},r6=(t,e,r)=>t6(t,e,r,rg),hH=(t,e,r=new Map)=>{Vw(t,e.store,r),xl(t,aH(e.store))},pH=(t,e=new Uint8Array([0]),r=new Ni)=>{let s=n6(e);hH(r,t,s);let n=[r.toUint8Array()];if(t.store.pendingDs&&n.push(t.store.pendingDs),t.store.pendingStructs&&n.push(AH(t.store.pendingStructs.update,e)),n.length>1){if(r.constructor===fc)return CH(n.map((i,o)=>o===0?i:IH(i)));if(r.constructor===Ni)return og(n)}return n[0]},s6=(t,e)=>pH(t,e,new fc),mH=t=>{let e=new Map,r=Ze(t.restDecoder);for(let s=0;s<r;s++){let n=Ze(t.restDecoder),i=Ze(t.restDecoder);e.set(n,i)}return e},n6=t=>mH(new tg(fn(t))),i6=(t,e)=>(ze(t.restEncoder,e.size),cn(e.entries()).sort((r,s)=>s[0]-r[0]).forEach(([r,s])=>{ze(t.restEncoder,r),ze(t.restEncoder,s)}),t),gH=(t,e)=>i6(t,fg(e.store)),yH=(t,e=new ng)=>(t instanceof Map?i6(e,t):gH(e,t),e.toUint8Array()),o6=t=>yH(t,new sg),Aw=class{constructor(){this.l=[]}},Hk=()=>new Aw,$k=(t,e)=>t.l.push(e),Vk=(t,e)=>{let r=t.l,s=r.length;t.l=r.filter(n=>e!==n),s===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},a6=(t,e,r)=>kf(t.l,[e,r]),Ho=class{constructor(e,r){this.client=e,this.clock=r}},Xm=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Et=(t,e)=>new Ho(t,e);var xH=t=>{for(let[e,r]of t.doc.share.entries())if(r===t)return e;throw ln()};var kw=class{constructor(e,r){this.ds=e,this.sv=r}};var bH=(t,e)=>new kw(t,e),Fse=bH(Zk(),new Map);var hl=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Qk(e.ds,t.id),Iw=(t,e)=>{let r=As(t.meta,Iw,Hn),s=t.doc.store;r.has(e)||(e.sv.forEach((n,i)=>{n<Tr(s,i)&&Vo(t,Et(i,n))}),Jk(t,e.ds,n=>{}),r.add(e))};var ig=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},fg=t=>{let e=new Map;return t.clients.forEach((r,s)=>{let n=r[r.length-1];e.set(s,n.id.clock+n.length)}),e},Tr=(t,e)=>{let r=t.clients.get(e);if(r===void 0)return 0;let s=r[r.length-1];return s.id.clock+s.length},c6=(t,e)=>{let r=t.clients.get(e.id.client);if(r===void 0)r=[],t.clients.set(e.id.client,r);else{let s=r[r.length-1];if(s.id.clock+s.length!==e.id.clock)throw ln()}r.push(e)},zn=(t,e)=>{let r=0,s=t.length-1,n=t[s],i=n.id.clock;if(i===e)return s;let o=as(e/(i+n.length-1)*s);for(;r<=s;){if(n=t[o],i=n.id.clock,i<=e){if(e<i+n.length)return o;r=o+1}else s=o-1;o=as((r+s)/2)}throw ln()},wH=(t,e)=>{let r=t.clients.get(e.client);return r[zn(r,e.clock)]},Ew=wH,Rw=(t,e,r)=>{let s=zn(e,r),n=e[s];return n.id.clock<r&&n instanceof Ar?(e.splice(s+1,0,ug(t,n,r-n.id.clock)),s+1):s},Vo=(t,e)=>{let r=t.doc.store.clients.get(e.client);return r[Rw(t,r,e.clock)]},qk=(t,e,r)=>{let s=e.clients.get(r.client),n=zn(s,r.clock),i=s[n];return r.clock!==i.id.clock+i.length-1&&i.constructor!==cs&&s.splice(n+1,0,ug(t,i,r.clock-i.id.clock+1)),i},vH=(t,e,r)=>{let s=t.clients.get(e.id.client);s[zn(s,e.id.clock)]=r},d6=(t,e,r,s,n)=>{if(s===0)return;let i=r+s,o=Rw(t,e,r),a;do a=e[o++],i<a.id.clock+a.length&&Rw(t,e,i),n(a);while(o<e.length&&e[o].id.clock<i)},Pw=class{constructor(e,r,s){this.doc=e,this.deleteSet=new lc,this.beforeState=fg(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=r,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},zk=(t,e)=>e.deleteSet.clients.size===0&&!YA(e.afterState,(r,s)=>e.beforeState.get(s)!==r)?!1:(Hw(e.deleteSet),uH(t,e),xl(t,e.deleteSet),!0),Kk=(t,e,r)=>{let s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&As(t.changed,e,Hn).add(r)},Qm=(t,e)=>{let r=t[e],s=t[e-1],n=e;for(;n>0;r=s,s=t[--n-1]){if(s.deleted===r.deleted&&s.constructor===r.constructor&&s.mergeWith(r)){r instanceof Ar&&r.parentSub!==null&&r.parent._map.get(r.parentSub)===r&&r.parent._map.set(r.parentSub,s);continue}break}let i=e-n;return i&&t.splice(e+1-i,i),i},_H=(t,e,r)=>{for(let[s,n]of t.clients.entries()){let i=e.clients.get(s);for(let o=n.length-1;o>=0;o--){let a=n[o],c=a.clock+a.len;for(let d=zn(i,a.clock),u=i[d];d<i.length&&u.id.clock<c;u=i[++d]){let l=i[d];if(a.clock+a.len<=l.id.clock)break;l instanceof Ar&&l.deleted&&!l.keep&&r(l)&&l.gc(e,!1)}}}},SH=(t,e)=>{t.clients.forEach((r,s)=>{let n=e.clients.get(s);for(let i=r.length-1;i>=0;i--){let o=r[i],a=rl(n.length-1,1+zn(n,o.clock+o.len-1));for(let c=a,d=n[c];c>0&&d.id.clock>=o.clock;d=n[c])c-=1+Qm(n,c)}})};var l6=(t,e)=>{if(e<t.length){let r=t[e],s=r.doc,n=s.store,i=r.deleteSet,o=r._mergeStructs;try{Hw(i),r.afterState=fg(r.doc.store),s.emit("beforeObserverCalls",[r,s]);let a=[];r.changed.forEach((c,d)=>a.push(()=>{(d._item===null||!d._item.deleted)&&d._callObserver(r,c)})),a.push(()=>{r.changedParentTypes.forEach((c,d)=>{d._dEH.l.length>0&&(d._item===null||!d._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=d,u._path=null}),c.sort((u,l)=>u.path.length-l.path.length),a.push(()=>{a6(d._dEH,c,r)}))}),a.push(()=>s.emit("afterTransaction",[r,s])),a.push(()=>{r._needFormattingCleanup&&FH(r)})}),kf(a,[])}finally{s.gc&&_H(i,n,s.gcFilter),SH(i,n),r.afterState.forEach((u,l)=>{let f=r.beforeState.get(l)||0;if(f!==u){let h=n.clients.get(l),m=Pi(zn(h,f),1);for(let v=h.length-1;v>=m;)v-=1+Qm(h,v)}});for(let u=o.length-1;u>=0;u--){let{client:l,clock:f}=o[u].id,h=n.clients.get(l),m=zn(h,f);m+1<h.length&&Qm(h,m+1)>1||m>0&&Qm(h,m)}if(!r.local&&r.afterState.get(s.clientID)!==r.beforeState.get(s.clientID)&&(Nk(Df,Rf,"[yjs] ",Pf,Bf,"Changed the client-id because another client seems to be using it."),s.clientID=e6()),s.emit("afterTransactionCleanup",[r,s]),s._observers.has("update")){let u=new fc;zk(u,r)&&s.emit("update",[u.toUint8Array(),r.origin,s,r])}if(s._observers.has("updateV2")){let u=new Ni;zk(u,r)&&s.emit("updateV2",[u.toUint8Array(),r.origin,s,r])}let{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:d}=r;(a.size>0||d.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),d.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:a,removed:d},s,r]),d.forEach(u=>u.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):l6(t,e+1)}}},Vt=(t,e,r=null,s=!0)=>{let n=t._transactionCleanups,i=!1,o=null;t._transaction===null&&(i=!0,t._transaction=new Pw(t,r,s),n.push(t._transaction),n.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(i){let a=t._transaction===n[0];t._transaction=null,a&&l6(n,0)}}return o};function*EH(t){let e=Ze(t.restDecoder);for(let r=0;r<e;r++){let s=Ze(t.restDecoder),n=t.readClient(),i=Ze(t.restDecoder);for(let o=0;o<s;o++){let a=t.readInfo();if(a===10){let c=Ze(t.restDecoder);yield new ds(Et(n,i),c),i+=c}else if((31&a)!==0){let c=(a&192)===0,d=new Ar(Et(n,i),null,(a&128)===128?t.readLeftID():null,null,(a&64)===64?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&32)===32?t.readString():null,k6(t,a));yield d,i+=d.length}else{let c=t.readLen();yield new cs(Et(n,i),c),i+=c}}}}var Of=class{constructor(e,r){this.gen=EH(e),this.curr=null,this.done=!1,this.filterSkips=r,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===ds);return this.curr}};var Lf=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},CH=t=>og(t,rg,fc);var TH=(t,e)=>{if(t.constructor===cs){let{client:r,clock:s}=t.id;return new cs(Et(r,s+e),t.length-e)}else if(t.constructor===ds){let{client:r,clock:s}=t.id;return new ds(Et(r,s+e),t.length-e)}else{let r=t,{client:s,clock:n}=r.id;return new Ar(Et(s,n+e),null,Et(s,n+e-1),null,r.rightOrigin,r.parent,r.parentSub,r.content.splice(e))}},og=(t,e=$o,r=Ni)=>{if(t.length===1)return t[0];let s=t.map(u=>new e(fn(u))),n=s.map(u=>new Of(u,!0)),i=null,o=new r,a=new Lf(o);for(;n=n.filter(f=>f.curr!==null),n.sort((f,h)=>{if(f.curr.id.client===h.curr.id.client){let m=f.curr.id.clock-h.curr.id.clock;return m===0?f.curr.constructor===h.curr.constructor?0:f.curr.constructor===ds?1:-1:m}else return h.curr.id.client-f.curr.id.client}),n.length!==0;){let u=n[0],l=u.curr.id.client;if(i!==null){let f=u.curr,h=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=u.next(),h=!0;if(f===null||f.id.client!==l||h&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(l!==i.struct.id.client)jo(a,i.struct,i.offset),i={struct:f,offset:0},u.next();else if(i.struct.id.clock+i.struct.length<f.id.clock)if(i.struct.constructor===ds)i.struct.length=f.id.clock+f.length-i.struct.id.clock;else{jo(a,i.struct,i.offset);let m=f.id.clock-i.struct.id.clock-i.struct.length;i={struct:new ds(Et(l,i.struct.id.clock+i.struct.length),m),offset:0}}else{let m=i.struct.id.clock+i.struct.length-f.id.clock;m>0&&(i.struct.constructor===ds?i.struct.length-=m:f=TH(f,m)),i.struct.mergeWith(f)||(jo(a,i.struct,i.offset),i={struct:f,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let f=u.curr;f!==null&&f.id.client===l&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==ds;f=u.next())jo(a,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(jo(a,i.struct,i.offset),i=null),qw(a);let c=s.map(u=>$w(u)),d=oH(c);return xl(o,d),o.toUint8Array()},AH=(t,e,r=$o,s=Ni)=>{let n=n6(e),i=new s,o=new Lf(i),a=new r(fn(t)),c=new Of(a,!1);for(;c.curr;){let u=c.curr,l=u.id.client,f=n.get(l)||0;if(c.curr.constructor===ds){c.next();continue}if(u.id.clock+u.length>f)for(jo(o,u,Pi(f-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===l;)jo(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===l&&c.curr.id.clock+c.curr.length<=f;)c.next()}qw(o);let d=$w(a);return xl(i,d),i.toUint8Array()};var u6=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:$t(t.encoder.restEncoder)}),t.encoder.restEncoder=yr(),t.written=0)},jo=(t,e,r)=>{t.written>0&&t.currClient!==e.id.client&&u6(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ze(t.encoder.restEncoder,e.id.clock+r)),e.write(t.encoder,r),t.written++},qw=t=>{u6(t);let e=t.encoder.restEncoder;ze(e,t.clientStructs.length);for(let r=0;r<t.clientStructs.length;r++){let s=t.clientStructs[r];ze(e,s.written),Ef(e,s.restEncoder)}},kH=(t,e,r,s)=>{let n=new r(fn(t)),i=new Of(n,!1),o=new s,a=new Lf(o);for(let d=i.curr;d!==null;d=i.next())jo(a,e(d),0);qw(a);let c=$w(n);return xl(o,c),o.toUint8Array()};var IH=t=>kH(t,_k,$o,fc),Wk="You must not compute changes after the event-handler fired.",ml=class{constructor(e,r){this.target=e,this.currentTarget=e,this.transaction=r,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=RH(this.currentTarget,this.target))}deletes(e){return Qk(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw $n(Wk);let e=new Map,r=this.target;this.transaction.changed.get(r).forEach(n=>{if(n!==null){let i=r._map.get(n),o,a;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",a=Dm(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=Dm(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(i))o="delete",a=Dm(i.content.getContent());else return;e.set(n,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw $n(Wk);let r=this.target,s=Hn(),n=Hn(),i=[];if(e={added:s,deleted:n,delta:i,keys:this.keys},this.transaction.changed.get(r).has(null)){let a=null,c=()=>{a&&i.push(a)};for(let d=r._start;d!==null;d=d.right)d.deleted?this.deletes(d)&&!this.adds(d)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=d.length,n.add(d)):this.adds(d)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(d.content.getContent()),s.add(d)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=d.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}},RH=(t,e)=>{let r=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)r.unshift(e._item.parentSub);else{let s=0,n=e._item.parent._start;for(;n!==e._item&&n!==null;)!n.deleted&&n.countable&&(s+=n.length),n=n.right;r.unshift(s)}e=e._item.parent}return r},Wr=()=>{Ok("Invalid access: Add Yjs type to a document before reading data.")},f6=80,zw=0,Bw=class{constructor(e,r){e.marker=!0,this.p=e,this.index=r,this.timestamp=zw++}},PH=t=>{t.timestamp=zw++},h6=(t,e,r)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=r,t.timestamp=zw++},BH=(t,e,r)=>{if(t.length>=f6){let s=t.reduce((n,i)=>n.timestamp<i.timestamp?n:i);return h6(s,e,r),s}else{let s=new Bw(e,r);return t.push(s),s}},hg=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;let r=t._searchMarker.length===0?null:t._searchMarker.reduce((i,o)=>tl(e-i.index)<tl(e-o.index)?i:o),s=t._start,n=0;for(r!==null&&(s=r.p,n=r.index,PH(r));s.right!==null&&n<e;){if(!s.deleted&&s.countable){if(e<n+s.length)break;n+=s.length}s=s.right}for(;s.left!==null&&n>e;)s=s.left,!s.deleted&&s.countable&&(n-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(n-=s.length);return r!==null&&tl(r.index-n)<s.parent.length/f6?(h6(r,s,n),r):BH(t._searchMarker,s,n)},Uf=(t,e,r)=>{for(let s=t.length-1;s>=0;s--){let n=t[s];if(r>0){let i=n.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(n.index-=i.length);if(i===null||i.marker===!0){t.splice(s,1);continue}n.p=i,i.marker=!0}(e<n.index||r>0&&e===n.index)&&(n.index=Pi(e,n.index+r))}};var pg=(t,e,r)=>{let s=t,n=e.changedParentTypes;for(;As(n,t,()=>[]).push(r),t._item!==null;)t=t._item.parent;a6(s._eH,r,e)},br=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Hk(),this._dEH=Hk(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,r){this.doc=e,this._item=r}_copy(){throw dn()}clone(){throw dn()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,r){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){$k(this._eH,e)}observeDeep(e){$k(this._dEH,e)}unobserve(e){Vk(this._eH,e)}unobserveDeep(e){Vk(this._dEH,e)}toJSON(){}},p6=(t,e,r)=>{t.doc??Wr(),e<0&&(e=t._length+e),r<0&&(r=t._length+r);let s=r-e,n=[],i=t._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){let o=i.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a<o.length&&s>0;a++)n.push(o[a]),s--;e=0}}i=i.right}return n},m6=t=>{t.doc??Wr();let e=[],r=t._start;for(;r!==null;){if(r.countable&&!r.deleted){let s=r.content.getContent();for(let n=0;n<s.length;n++)e.push(s[n])}r=r.right}return e};var Mf=(t,e)=>{let r=0,s=t._start;for(t.doc??Wr();s!==null;){if(s.countable&&!s.deleted){let n=s.content.getContent();for(let i=0;i<n.length;i++)e(n[i],r++,t)}s=s.right}},g6=(t,e)=>{let r=[];return Mf(t,(s,n)=>{r.push(e(s,n,t))}),r},DH=t=>{let e=t._start,r=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(r===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};r=e.content.getContent(),s=0,e=e.right}let n=r[s++];return r.length<=s&&(r=null),{done:!1,value:n}}}},y6=(t,e)=>{t.doc??Wr();let r=hg(t,e),s=t._start;for(r!==null&&(s=r.p,e-=r.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(e<s.length)return s.content.getContent()[e];e-=s.length}},ag=(t,e,r,s)=>{let n=r,i=t.doc,o=i.clientID,a=i.store,c=r===null?e._start:r.right,d=[],u=()=>{d.length>0&&(n=new Ar(Et(o,Tr(a,o)),n,n&&n.lastId,c,c&&c.id,e,null,new yl(d)),n.integrate(t,0),d=[])};s.forEach(l=>{if(l===null)d.push(l);else switch(l.constructor){case Number:case Object:case Boolean:case Array:case String:d.push(l);break;default:switch(u(),l.constructor){case Uint8Array:case ArrayBuffer:n=new Ar(Et(o,Tr(a,o)),n,n&&n.lastId,c,c&&c.id,e,null,new Vf(new Uint8Array(l))),n.integrate(t,0);break;case uc:n=new Ar(Et(o,Tr(a,o)),n,n&&n.lastId,c,c&&c.id,e,null,new qf(l)),n.integrate(t,0);break;default:if(l instanceof br)n=new Ar(Et(o,Tr(a,o)),n,n&&n.lastId,c,c&&c.id,e,null,new Li(l)),n.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},x6=()=>$n("Length exceeded!"),b6=(t,e,r,s)=>{if(r>e._length)throw x6();if(r===0)return e._searchMarker&&Uf(e._searchMarker,r,s.length),ag(t,e,null,s);let n=r,i=hg(e,r),o=e._start;for(i!==null&&(o=i.p,r-=i.index,r===0&&(o=o.prev,r+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(r<=o.length){r<o.length&&Vo(t,Et(o.id.client,o.id.clock+r));break}r-=o.length}return e._searchMarker&&Uf(e._searchMarker,n,s.length),ag(t,e,o,s)},NH=(t,e,r)=>{let n=(e._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:e._start}).p;if(n)for(;n.right;)n=n.right;return ag(t,e,n,r)},w6=(t,e,r,s)=>{if(s===0)return;let n=r,i=s,o=hg(e,r),a=e._start;for(o!==null&&(a=o.p,r-=o.index);a!==null&&r>0;a=a.right)!a.deleted&&a.countable&&(r<a.length&&Vo(t,Et(a.id.client,a.id.clock+r)),r-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&Vo(t,Et(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw x6();e._searchMarker&&Uf(e._searchMarker,n,-i+s)},cg=(t,e,r)=>{let s=e._map.get(r);s!==void 0&&s.delete(t)},Kw=(t,e,r,s)=>{let n=e._map.get(r)||null,i=t.doc,o=i.clientID,a;if(s==null)a=new yl([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new yl([s]);break;case Uint8Array:a=new Vf(s);break;case uc:a=new qf(s);break;default:if(s instanceof br)a=new Li(s);else throw new Error("Unexpected content type")}new Ar(Et(o,Tr(i.store,o)),n,n&&n.lastId,null,null,e,r,a).integrate(t,0)},Ww=(t,e)=>{t.doc??Wr();let r=t._map.get(e);return r!==void 0&&!r.deleted?r.content.getContent()[r.length-1]:void 0},v6=t=>{let e={};return t.doc??Wr(),t._map.forEach((r,s)=>{r.deleted||(e[s]=r.content.getContent()[r.length-1])}),e},_6=(t,e)=>{t.doc??Wr();let r=t._map.get(e);return r!==void 0&&!r.deleted};var OH=(t,e)=>{let r={};return t._map.forEach((s,n)=>{let i=s;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&hl(i,e)&&(r[n]=i.content.getContent()[i.length-1])}),r},Ym=t=>(t.doc??Wr(),Uk(t._map.entries(),e=>!e[1].deleted)),Dw=class extends ml{},dg=class t extends br{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){let r=new t;return r.push(e),r}_integrate(e,r){super._integrate(e,r),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new t}clone(){let e=new t;return e.insert(0,this.toArray().map(r=>r instanceof br?r.clone():r)),e}get length(){return this.doc??Wr(),this._length}_callObserver(e,r){super._callObserver(e,r),pg(this,e,new Dw(this,e))}insert(e,r){this.doc!==null?Vt(this.doc,s=>{b6(s,this,e,r)}):this._prelimContent.splice(e,0,...r)}push(e){this.doc!==null?Vt(this.doc,r=>{NH(r,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,r=1){this.doc!==null?Vt(this.doc,s=>{w6(s,this,e,r)}):this._prelimContent.splice(e,r)}get(e){return y6(this,e)}toArray(){return m6(this)}slice(e=0,r=this.length){return p6(this,e,r)}toJSON(){return this.map(e=>e instanceof br?e.toJSON():e)}map(e){return g6(this,e)}forEach(e){Mf(this,e)}[Symbol.iterator](){return DH(this)}_write(e){e.writeTypeRef(s$)}},LH=t=>new dg,Nw=class extends ml{constructor(e,r,s){super(e,r),this.keysChanged=s}},qo=class t extends br{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,r){super._integrate(e,r),this._prelimContent.forEach((s,n)=>{this.set(n,s)}),this._prelimContent=null}_copy(){return new t}clone(){let e=new t;return this.forEach((r,s)=>{e.set(s,r instanceof br?r.clone():r)}),e}_callObserver(e,r){pg(this,e,new Nw(this,e,r))}toJSON(){this.doc??Wr();let e={};return this._map.forEach((r,s)=>{if(!r.deleted){let n=r.content.getContent()[r.length-1];e[s]=n instanceof br?n.toJSON():n}}),e}get size(){return[...Ym(this)].length}keys(){return Gm(Ym(this),e=>e[0])}values(){return Gm(Ym(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Gm(Ym(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Wr(),this._map.forEach((r,s)=>{r.deleted||e(r.content.getContent()[r.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Vt(this.doc,r=>{cg(r,this,e)}):this._prelimContent.delete(e)}set(e,r){return this.doc!==null?Vt(this.doc,s=>{Kw(s,this,e,r)}):this._prelimContent.set(e,r),r}get(e){return Ww(this,e)}has(e){return _6(this,e)}clear(){this.doc!==null?Vt(this.doc,e=>{this.forEach(function(r,s,n){cg(e,n,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(n$)}},UH=t=>new qo,Fo=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&hw(t,e),jf=class{constructor(e,r,s,n){this.left=e,this.right=r,this.index=s,this.currentAttributes=n}forward(){this.right===null&&ln(),this.right.content.constructor===wr?this.right.deleted||bl(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}},Gk=(t,e,r)=>{for(;e.right!==null&&r>0;)e.right.content.constructor===wr?e.right.deleted||bl(e.currentAttributes,e.right.content):e.right.deleted||(r<e.right.length&&Vo(t,Et(e.right.id.client,e.right.id.clock+r)),e.index+=e.right.length,r-=e.right.length),e.left=e.right,e.right=e.right.right;return e},Jm=(t,e,r,s)=>{let n=new Map,i=s?hg(e,r):null;if(i){let o=new jf(i.p.left,i.p,i.index,n);return Gk(t,o,r-i.index)}else{let o=new jf(null,e._start,0,n);return Gk(t,o,r)}},S6=(t,e,r,s)=>{for(;r.right!==null&&(r.right.deleted===!0||r.right.content.constructor===wr&&Fo(s.get(r.right.content.key),r.right.content.value));)r.right.deleted||s.delete(r.right.content.key),r.forward();let n=t.doc,i=n.clientID;s.forEach((o,a)=>{let c=r.left,d=r.right,u=new Ar(Et(i,Tr(n.store,i)),c,c&&c.lastId,d,d&&d.id,e,null,new wr(a,o));u.integrate(t,0),r.right=u,r.forward()})},bl=(t,e)=>{let{key:r,value:s}=e;s===null?t.delete(r):t.set(r,s)},E6=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===wr&&Fo(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},C6=(t,e,r,s)=>{let n=t.doc,i=n.clientID,o=new Map;for(let a in s){let c=s[a],d=r.currentAttributes.get(a)??null;if(!Fo(d,c)){o.set(a,d);let{left:u,right:l}=r;r.right=new Ar(Et(i,Tr(n.store,i)),u,u&&u.lastId,l,l&&l.id,e,null,new wr(a,c)),r.right.integrate(t,0),r.forward()}}return o},Cw=(t,e,r,s,n)=>{r.currentAttributes.forEach((f,h)=>{n[h]===void 0&&(n[h]=null)});let i=t.doc,o=i.clientID;E6(r,n);let a=C6(t,e,r,n),c=s.constructor===String?new Oi(s):s instanceof br?new Li(s):new hc(s),{left:d,right:u,index:l}=r;e._searchMarker&&Uf(e._searchMarker,r.index,c.getLength()),u=new Ar(Et(o,Tr(i.store,o)),d,d&&d.lastId,u,u&&u.id,e,null,c),u.integrate(t,0),r.right=u,r.index=l,r.forward(),S6(t,e,r,a)},Xk=(t,e,r,s,n)=>{let i=t.doc,o=i.clientID;E6(r,n);let a=C6(t,e,r,n);e:for(;r.right!==null&&(s>0||a.size>0&&(r.right.deleted||r.right.content.constructor===wr));){if(!r.right.deleted)switch(r.right.content.constructor){case wr:{let{key:c,value:d}=r.right.content,u=n[c];if(u!==void 0){if(Fo(u,d))a.delete(c);else{if(s===0)break e;a.set(c,d)}r.right.delete(t)}else r.currentAttributes.set(c,d);break}default:s<r.right.length&&Vo(t,Et(r.right.id.client,r.right.id.clock+s)),s-=r.right.length;break}r.forward()}if(s>0){let c="";for(;s>0;s--)c+=`
137
+ `;r.right=new Ar(Et(o,Tr(i.store,o)),r.left,r.left&&r.left.lastId,r.right,r.right&&r.right.id,e,null,new Oi(c)),r.right.integrate(t,0),r.forward()}S6(t,e,r,a)},T6=(t,e,r,s,n)=>{let i=e,o=Kr();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===wr){let d=i.content;o.set(d.key,d)}i=i.right}let a=0,c=!1;for(;e!==i;){if(r===e&&(c=!0),!e.deleted){let d=e.content;if(d.constructor===wr){let{key:u,value:l}=d,f=s.get(u)??null;(o.get(u)!==d||f===l)&&(e.delete(t),a++,!c&&(n.get(u)??null)===l&&f!==l&&(f===null?n.delete(u):n.set(u,f))),!c&&!e.deleted&&bl(n,d)}}e=e.right}return a},MH=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;let r=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===wr){let s=e.content.key;r.has(s)?e.delete(t):r.add(s)}e=e.left}},jH=t=>{let e=0;return Vt(t.doc,r=>{let s=t._start,n=t._start,i=Kr(),o=Pm(i);for(;n;)n.deleted===!1&&(n.content.constructor===wr?bl(o,n.content):(e+=T6(r,s,n,i,o),i=Pm(o),s=n)),n=n.right}),e},FH=t=>{let e=new Set,r=t.doc;for(let[s,n]of t.afterState.entries()){let i=t.beforeState.get(s)||0;n!==i&&d6(t,r.store.clients.get(s),i,n,o=>{!o.deleted&&o.content.constructor===wr&&o.constructor!==cs&&e.add(o.parent)})}Vt(r,s=>{Jk(t,t.deleteSet,n=>{if(n instanceof cs||!n.parent._hasFormatting||e.has(n.parent))return;let i=n.parent;n.content.constructor===wr?e.add(i):MH(s,n)});for(let n of e)jH(n)})},Yk=(t,e,r)=>{let s=r,n=Pm(e.currentAttributes),i=e.right;for(;r>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Li:case hc:case Oi:r<e.right.length&&Vo(t,Et(e.right.id.client,e.right.id.clock+r)),r-=e.right.length,e.right.delete(t);break}e.forward()}i&&T6(t,i,e.right,n,e.currentAttributes);let o=(e.left||e.right).parent;return o._searchMarker&&Uf(o._searchMarker,e.index,-s+r),e},Ow=class extends ml{constructor(e,r,s){super(e,r),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(n=>{n===null?this.childListChanged=!0:this.keysChanged.add(n)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,r=[];Vt(e,s=>{let n=new Map,i=new Map,o=this.target._start,a=null,c={},d="",u=0,l=0,f=()=>{if(a!==null){let h=null;switch(a){case"delete":l>0&&(h={delete:l}),l=0;break;case"insert":(typeof d=="object"||d.length>0)&&(h={insert:d},n.size>0&&(h.attributes={},n.forEach((m,v)=>{m!==null&&(h.attributes[v]=m)}))),d="";break;case"retain":u>0&&(h={retain:u},vk(c)||(h.attributes=xk({},c))),u=0;break}h&&r.push(h),a=null}};for(;o!==null;){switch(o.content.constructor){case Li:case hc:this.adds(o)?this.deletes(o)||(f(),a="insert",d=o.content.getContent()[0],f()):this.deletes(o)?(a!=="delete"&&(f(),a="delete"),l+=1):o.deleted||(a!=="retain"&&(f(),a="retain"),u+=1);break;case Oi:this.adds(o)?this.deletes(o)||(a!=="insert"&&(f(),a="insert"),d+=o.content.str):this.deletes(o)?(a!=="delete"&&(f(),a="delete"),l+=o.length):o.deleted||(a!=="retain"&&(f(),a="retain"),u+=o.length);break;case wr:{let{key:h,value:m}=o.content;if(this.adds(o)){if(!this.deletes(o)){let v=n.get(h)??null;Fo(v,m)?m!==null&&o.delete(s):(a==="retain"&&f(),Fo(m,i.get(h)??null)?delete c[h]:c[h]=m)}}else if(this.deletes(o)){i.set(h,m);let v=n.get(h)??null;Fo(v,m)||(a==="retain"&&f(),c[h]=v)}else if(!o.deleted){i.set(h,m);let v=c[h];v!==void 0&&(Fo(v,m)?v!==null&&o.delete(s):(a==="retain"&&f(),m===null?delete c[h]:c[h]=m))}o.deleted||(a==="insert"&&f(),bl(n,o.content));break}}o=o.right}for(f();r.length>0;){let h=r[r.length-1];if(h.retain!==void 0&&h.attributes===void 0)r.pop();else break}}),this._delta=r}return this._delta}},Ff=class t extends br{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Wr(),this._length}_integrate(e,r){super._integrate(e,r);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new t}clone(){let e=new t;return e.applyDelta(this.toDelta()),e}_callObserver(e,r){super._callObserver(e,r);let s=new Ow(this,e,r);pg(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Wr();let e="",r=this._start;for(;r!==null;)!r.deleted&&r.countable&&r.content.constructor===Oi&&(e+=r.content.str),r=r.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:r=!0}={}){this.doc!==null?Vt(this.doc,s=>{let n=new jf(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let o=e[i];if(o.insert!==void 0){let a=!r&&typeof o.insert=="string"&&i===e.length-1&&n.right===null&&o.insert.slice(-1)===`
138
+ `?o.insert.slice(0,-1):o.insert;(typeof a!="string"||a.length>0)&&Cw(s,this,n,a,o.attributes||{})}else o.retain!==void 0?Xk(s,this,n,o.retain,o.attributes||{}):o.delete!==void 0&&Yk(s,n,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,r,s){this.doc??Wr();let n=[],i=new Map,o=this.doc,a="",c=this._start;function d(){if(a.length>0){let l={},f=!1;i.forEach((m,v)=>{f=!0,l[v]=m});let h={insert:a};f&&(h.attributes=l),n.push(h),a=""}}let u=()=>{for(;c!==null;){if(hl(c,e)||r!==void 0&&hl(c,r))switch(c.content.constructor){case Oi:{let l=i.get("ychange");e!==void 0&&!hl(c,e)?(l===void 0||l.user!==c.id.client||l.type!=="removed")&&(d(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):r!==void 0&&!hl(c,r)?(l===void 0||l.user!==c.id.client||l.type!=="added")&&(d(),i.set("ychange",s?s("added",c.id):{type:"added"})):l!==void 0&&(d(),i.delete("ychange")),a+=c.content.str;break}case Li:case hc:{d();let l={insert:c.content.getContent()[0]};if(i.size>0){let f={};l.attributes=f,i.forEach((h,m)=>{f[m]=h})}n.push(l);break}case wr:hl(c,e)&&(d(),bl(i,c.content));break}c=c.right}d()};return e||r?Vt(o,l=>{e&&Iw(l,e),r&&Iw(l,r),u()},"cleanup"):u(),n}insert(e,r,s){if(r.length<=0)return;let n=this.doc;n!==null?Vt(n,i=>{let o=Jm(i,this,e,!s);s||(s={},o.currentAttributes.forEach((a,c)=>{s[c]=a})),Cw(i,this,o,r,s)}):this._pending.push(()=>this.insert(e,r,s))}insertEmbed(e,r,s){let n=this.doc;n!==null?Vt(n,i=>{let o=Jm(i,this,e,!s);Cw(i,this,o,r,s||{})}):this._pending.push(()=>this.insertEmbed(e,r,s||{}))}delete(e,r){if(r===0)return;let s=this.doc;s!==null?Vt(s,n=>{Yk(n,Jm(n,this,e,!0),r)}):this._pending.push(()=>this.delete(e,r))}format(e,r,s){if(r===0)return;let n=this.doc;n!==null?Vt(n,i=>{let o=Jm(i,this,e,!1);o.right!==null&&Xk(i,this,o,r,s)}):this._pending.push(()=>this.format(e,r,s))}removeAttribute(e){this.doc!==null?Vt(this.doc,r=>{cg(r,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,r){this.doc!==null?Vt(this.doc,s=>{Kw(s,this,e,r)}):this._pending.push(()=>this.setAttribute(e,r))}getAttribute(e){return Ww(this,e)}getAttributes(){return v6(this)}_write(e){e.writeTypeRef(i$)}},HH=t=>new Ff,Nf=class{constructor(e,r=()=>!0){this._filter=r,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Wr()}[Symbol.iterator](){return this}next(){let e=this._currentNode,r=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(r)))do if(r=e.content.type,!e.deleted&&(r.constructor===Hf||r.constructor===gl)&&r._start!==null)e=r._start;else for(;e!==null;){let s=e.next;if(s!==null){e=s;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},gl=class t extends br{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,r){super._integrate(e,r),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new t}clone(){let e=new t;return e.insert(0,this.toArray().map(r=>r instanceof br?r.clone():r)),e}get length(){return this.doc??Wr(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Nf(this,e)}querySelector(e){e=e.toUpperCase();let s=new Nf(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),cn(new Nf(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e))}_callObserver(e,r){pg(this,e,new Lw(this,r,e))}toString(){return g6(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,r={},s){let n=e.createDocumentFragment();return s!==void 0&&s._createAssociation(n,this),Mf(this,i=>{n.insertBefore(i.toDOM(e,r,s),null)}),n}insert(e,r){this.doc!==null?Vt(this.doc,s=>{b6(s,this,e,r)}):this._prelimContent.splice(e,0,...r)}insertAfter(e,r){if(this.doc!==null)Vt(this.doc,s=>{let n=e&&e instanceof br?e._item:e;ag(s,this,n,r)});else{let s=this._prelimContent,n=e===null?0:s.findIndex(i=>i===e)+1;if(n===0&&e!==null)throw $n("Reference item not found");s.splice(n,0,...r)}}delete(e,r=1){this.doc!==null?Vt(this.doc,s=>{w6(s,this,e,r)}):this._prelimContent.splice(e,r)}toArray(){return m6(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return y6(this,e)}slice(e=0,r=this.length){return p6(this,e,r)}forEach(e){Mf(this,e)}_write(e){e.writeTypeRef(a$)}},$H=t=>new gl,Hf=class t extends gl{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,r){super._integrate(e,r),this._prelimAttrs.forEach((s,n)=>{this.setAttribute(n,s)}),this._prelimAttrs=null}_copy(){return new t(this.nodeName)}clone(){let e=new t(this.nodeName),r=this.getAttributes();return bk(r,(s,n)=>{e.setAttribute(n,s)}),e.insert(0,this.toArray().map(s=>s instanceof br?s.clone():s)),e}toString(){let e=this.getAttributes(),r=[],s=[];for(let a in e)s.push(a);s.sort();let n=s.length;for(let a=0;a<n;a++){let c=s[a];r.push(c+'="'+e[c]+'"')}let i=this.nodeName.toLocaleLowerCase(),o=r.length>0?" "+r.join(" "):"";return`<${i}${o}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?Vt(this.doc,r=>{cg(r,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,r){this.doc!==null?Vt(this.doc,s=>{Kw(s,this,e,r)}):this._prelimAttrs.set(e,r)}getAttribute(e){return Ww(this,e)}hasAttribute(e){return _6(this,e)}getAttributes(e){return e?OH(this,e):v6(this)}toDOM(e=document,r={},s){let n=e.createElement(this.nodeName),i=this.getAttributes();for(let o in i){let a=i[o];typeof a=="string"&&n.setAttribute(o,a)}return Mf(this,o=>{n.appendChild(o.toDOM(e,r,s))}),s!==void 0&&s._createAssociation(n,this),n}_write(e){e.writeTypeRef(o$),e.writeKey(this.nodeName)}},VH=t=>new Hf(t.readKey()),Lw=class extends ml{constructor(e,r,s){super(e,s),this.childListChanged=!1,this.attributesChanged=new Set,r.forEach(n=>{n===null?this.childListChanged=!0:this.attributesChanged.add(n)})}},Uw=class t extends qo{constructor(e){super(),this.hookName=e}_copy(){return new t(this.hookName)}clone(){let e=new t(this.hookName);return this.forEach((r,s)=>{e.set(s,r)}),e}toDOM(e=document,r={},s){let n=r[this.hookName],i;return n!==void 0?i=n.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(e){e.writeTypeRef(c$),e.writeKey(this.hookName)}},qH=t=>new Uw(t.readKey()),Mw=class t extends Ff{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new t}clone(){let e=new t;return e.applyDelta(this.toDelta()),e}toDOM(e=document,r,s){let n=e.createTextNode(this.toString());return s!==void 0&&s._createAssociation(n,this),n}toString(){return this.toDelta().map(e=>{let r=[];for(let n in e.attributes){let i=[];for(let o in e.attributes[n])i.push({key:o,value:e.attributes[n][o]});i.sort((o,a)=>o.key<a.key?-1:1),r.push({nodeName:n,attrs:i})}r.sort((n,i)=>n.nodeName<i.nodeName?-1:1);let s="";for(let n=0;n<r.length;n++){let i=r[n];s+=`<${i.nodeName}`;for(let o=0;o<i.attrs.length;o++){let a=i.attrs[o];s+=` ${a.key}="${a.value}"`}s+=">"}s+=e.insert;for(let n=r.length-1;n>=0;n--)s+=`</${r[n].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(d$)}},zH=t=>new Mw,$f=class{constructor(e,r){this.id=e,this.length=r}get deleted(){throw dn()}mergeWith(e){return!1}write(e,r,s){throw dn()}integrate(e,r){throw dn()}},KH=0,cs=class extends $f{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,r){r>0&&(this.id.clock+=r,this.length-=r),c6(e.doc.store,this)}write(e,r){e.writeInfo(KH),e.writeLen(this.length-r)}getMissing(e,r){return null}},Vf=class t{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new t(this.content)}splice(e){throw dn()}mergeWith(e){return!1}integrate(e,r){}delete(e){}gc(e){}write(e,r){e.writeBuf(this.content)}getRef(){return 3}},WH=t=>new Vf(t.readBuf()),lg=class t{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new t(this.len)}splice(e){let r=new t(this.len-e);return this.len=e,r}mergeWith(e){return this.len+=e.len,!0}integrate(e,r){eg(e.deleteSet,r.id.client,r.id.clock,this.len),r.markDeleted()}delete(e){}gc(e){}write(e,r){e.writeLen(this.len-r)}getRef(){return 1}},GH=t=>new lg(t.readLen()),A6=(t,e)=>new uc({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),qf=class t{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;let r={};this.opts=r,e.gc||(r.gc=!1),e.autoLoad&&(r.autoLoad=!0),e.meta!==null&&(r.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new t(A6(this.doc.guid,this.opts))}splice(e){throw dn()}mergeWith(e){return!1}integrate(e,r){this.doc._item=r,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,r){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},XH=t=>new qf(A6(t.readString(),t.readAny())),hc=class t{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new t(this.embed)}splice(e){throw dn()}mergeWith(e){return!1}integrate(e,r){}delete(e){}gc(e){}write(e,r){e.writeJSON(this.embed)}getRef(){return 5}},YH=t=>new hc(t.readJSON()),wr=class t{constructor(e,r){this.key=e,this.value=r}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new t(this.key,this.value)}splice(e){throw dn()}mergeWith(e){return!1}integrate(e,r){let s=r.parent;s._searchMarker=null,s._hasFormatting=!0}delete(e){}gc(e){}write(e,r){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},JH=t=>new wr(t.readKey(),t.readJSON()),jw=class t{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new t(this.arr)}splice(e){let r=new t(this.arr.slice(e));return this.arr=this.arr.slice(0,e),r}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,r){}delete(e){}gc(e){}write(e,r){let s=this.arr.length;e.writeLen(s-r);for(let n=r;n<s;n++){let i=this.arr[n];e.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}},QH=t=>{let e=t.readLen(),r=[];for(let s=0;s<e;s++){let n=t.readString();n==="undefined"?r.push(void 0):r.push(JSON.parse(n))}return new jw(r)},ZH=If("node_env")==="development",yl=class t{constructor(e){this.arr=e,ZH&&pw(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new t(this.arr)}splice(e){let r=new t(this.arr.slice(e));return this.arr=this.arr.slice(0,e),r}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,r){}delete(e){}gc(e){}write(e,r){let s=this.arr.length;e.writeLen(s-r);for(let n=r;n<s;n++){let i=this.arr[n];e.writeAny(i)}}getRef(){return 8}},e$=t=>{let e=t.readLen(),r=[];for(let s=0;s<e;s++)r.push(t.readAny());return new yl(r)},Oi=class t{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new t(this.str)}splice(e){let r=new t(this.str.slice(e));this.str=this.str.slice(0,e);let s=this.str.charCodeAt(e-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",r.str="\uFFFD"+r.str.slice(1)),r}mergeWith(e){return this.str+=e.str,!0}integrate(e,r){}delete(e){}gc(e){}write(e,r){e.writeString(r===0?this.str:this.str.slice(r))}getRef(){return 4}},t$=t=>new Oi(t.readString()),r$=[LH,UH,HH,VH,$H,qH,zH],s$=0,n$=1,i$=2,o$=3,a$=4,c$=5,d$=6,Li=class t{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new t(this.type._copy())}splice(e){throw dn()}mergeWith(e){return!1}integrate(e,r){this.type._integrate(e.doc,r)}delete(e){let r=this.type._start;for(;r!==null;)r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e),r=r.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e)}),e.changed.delete(this.type)}gc(e){let r=this.type._start;for(;r!==null;)r.gc(e,!0),r=r.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(e,!0),s=s.left}),this.type._map=new Map}write(e,r){this.type._write(e)}getRef(){return 7}},l$=t=>new Li(r$[t.readTypeRef()](t));var ug=(t,e,r)=>{let{client:s,clock:n}=e.id,i=new Ar(Et(s,n+r),e,Et(s,n+r-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(r));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=Et(e.redone.client,e.redone.clock+r)),e.right=i,i.right!==null&&(i.right.left=i),t._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=r,i};var Ar=class t extends $f{constructor(e,r,s,n,i,o,a,c){super(e,c.getLength()),this.origin=s,this.left=r,this.right=n,this.rightOrigin=i,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,r){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Tr(r,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Tr(r,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Ho&&this.id.client!==this.parent.client&&this.parent.clock>=Tr(r,this.parent.client))return this.parent.client;if(this.origin&&(this.left=qk(e,r,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Vo(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===cs||this.right&&this.right.constructor===cs)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===t?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===t&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Ho){let s=Ew(r,this.parent);s.constructor===cs?this.parent=null:this.parent=s.content.type}return null}integrate(e,r){if(r>0&&(this.id.clock+=r,this.left=qk(e,e.doc.store,Et(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(r),this.length-=r),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,n;if(s!==null)n=s.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let i=new Set,o=new Set;for(;n!==null&&n!==this.right;){if(o.add(n),i.add(n),Xm(this.origin,n.origin)){if(n.id.client<this.id.client)s=n,i.clear();else if(Xm(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&o.has(Ew(e.doc.store,n.origin)))i.has(Ew(e.doc.store,n.origin))||(s=n,i.clear());else break;n=n.right}this.left=s}if(this.left!==null){let s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),c6(e.doc.store,this),this.content.integrate(e,this),Kk(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new cs(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:Et(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Xm(e.origin,this.lastId)&&this.right===e&&Xm(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let r=this.parent._searchMarker;return r&&r.forEach(s=>{s.p===e&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let r=this.parent;this.countable&&this.parentSub===null&&(r._length-=this.length),this.markDeleted(),eg(e.deleteSet,this.id.client,this.id.clock,this.length),Kk(e,r,this.parentSub),this.content.delete(e)}}gc(e,r){if(!this.deleted)throw ln();this.content.gc(e),r?vH(e,this,new cs(this.id,this.length)):this.content=new lg(this.length)}write(e,r){let s=r>0?Et(this.id.client,this.id.clock+r-1):this.origin,n=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&31|(s===null?0:128)|(n===null?0:64)|(i===null?0:32);if(e.writeInfo(o),s!==null&&e.writeLeftID(s),n!==null&&e.writeRightID(n),s===null&&n===null){let a=this.parent;if(a._item!==void 0){let c=a._item;if(c===null){let d=xH(a);e.writeParentInfo(!0),e.writeString(d)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Ho?(e.writeParentInfo(!1),e.writeLeftID(a)):ln();i!==null&&e.writeString(i)}this.content.write(e,r)}},k6=(t,e)=>u$[e&31](t),u$=[()=>{ln()},GH,QH,WH,t$,YH,JH,l$,e$,XH,()=>{ln()}],f$=10,ds=class extends $f{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,r){ln()}write(e,r){e.writeInfo(f$),ze(e.restEncoder,this.length-r)}getMissing(e,r){return null}},I6=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},R6="__ $YJS$ __";I6[R6]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");I6[R6]=!0;g();var B6=new Map,Gw=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=r=>r.key===e&&this.onmessage!==null&&this.onmessage({data:Ik(r.newValue||"")}),hk(this._onChange)}postMessage(e){zm.setItem(this.room,kk(Ak(e)))}close(){pk(this._onChange)}},h$=typeof BroadcastChannel>"u"?Gw:BroadcastChannel,Xw=t=>As(B6,t,()=>{let e=Hn(),r=new h$(t);return r.onmessage=s=>e.forEach(n=>n(s.data,"broadcastchannel")),{bc:r,subs:e}}),D6=(t,e)=>(Xw(t).subs.add(e),e),N6=(t,e)=>{let r=Xw(t),s=r.subs.delete(e);return s&&r.subs.size===0&&(r.bc.close(),B6.delete(t)),s},pc=(t,e,r=null)=>{let s=Xw(t);s.bc.postMessage(e),s.subs.forEach(n=>n(e,r))};g();var O6=0,mg=1,L6=2,gg=(t,e)=>{ze(t,O6);let r=o6(e);Jt(t,r)},Yw=(t,e,r)=>{ze(t,mg),Jt(t,s6(e,r))},m$=(t,e,r)=>Yw(e,r,xr(t)),U6=(t,e,r,s)=>{try{r6(e,xr(t),r)}catch(n){s?.(n),console.error("Caught error while handling a Yjs update",n)}},M6=(t,e)=>{ze(t,L6),Jt(t,e)},g$=U6,j6=(t,e,r,s,n)=>{let i=Ze(t);switch(i){case O6:m$(t,e,r);break;case mg:U6(t,r,s,n);break;case L6:g$(t,r,s,n);break;default:throw new Error("Unknown message type")}return i};g();var x$=0;var F6=(t,e,r)=>{Ze(t)===x$&&r(e,un(t))};g();var Jw=3e4,wl=class extends Nm{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let r=hn();this.getLocalState()!==null&&Jw/2<=r-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let s=[];this.meta.forEach((n,i)=>{i!==this.clientID&&Jw<=r-n.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&yg(this,s,"timeout")},as(Jw/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let r=this.clientID,s=this.meta.get(r),n=s===void 0?0:s.clock+1,i=this.states.get(r);e===null?this.states.delete(r):this.states.set(r,e),this.meta.set(r,{clock:n,lastUpdated:hn()});let o=[],a=[],c=[],d=[];e===null?d.push(r):i==null?e!=null&&o.push(r):(a.push(r),fl(i,e)||c.push(r)),(o.length>0||c.length>0||d.length>0)&&this.emit("change",[{added:o,updated:c,removed:d},"local"]),this.emit("update",[{added:o,updated:a,removed:d},"local"])}setLocalStateField(e,r){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:r})}getStates(){return this.states}},yg=(t,e,r)=>{let s=[];for(let n=0;n<e.length;n++){let i=e[n];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){let o=t.meta.get(i);t.meta.set(i,{clock:o.clock+1,lastUpdated:hn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},r]),t.emit("update",[{added:[],updated:[],removed:s},r]))},vl=(t,e,r=t.states)=>{let s=e.length,n=yr();ze(n,s);for(let i=0;i<s;i++){let o=e[i],a=r.get(o)||null,c=t.meta.get(o).clock;ze(n,o),ze(n,c),Bi(n,JSON.stringify(a))}return $t(n)};var H6=(t,e,r)=>{let s=fn(e),n=hn(),i=[],o=[],a=[],c=[],d=Ze(s);for(let u=0;u<d;u++){let l=Ze(s),f=Ze(s),h=JSON.parse(un(s)),m=t.meta.get(l),v=t.states.get(l),p=m===void 0?0:m.clock;(p<f||p===f&&h===null&&t.states.has(l))&&(h===null?l===t.clientID&&t.getLocalState()!=null?f++:t.states.delete(l):t.states.set(l,h),t.meta.set(l,{clock:f,lastUpdated:n}),m===void 0&&h!==null?i.push(l):m!==void 0&&h===null?c.push(l):h!==null&&(fl(h,v)||a.push(l),o.push(l)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},r]),(i.length>0||o.length>0||c.length>0)&&t.emit("update",[{added:i,updated:o,removed:c},r])};g();var $6=t=>wk(t,(e,r)=>`${encodeURIComponent(r)}=${encodeURIComponent(e)}`).join("&");var mc=0,q6=3,_l=1,_$=2,zf=[];zf[mc]=(t,e,r,s,n)=>{ze(t,mc);let i=j6(e,t,r.doc,r);s&&i===mg&&!r.synced&&(r.synced=!0)};zf[q6]=(t,e,r,s,n)=>{ze(t,_l),Jt(t,vl(r.awareness,Array.from(r.awareness.getStates().keys())))};zf[_l]=(t,e,r,s,n)=>{H6(r.awareness,xr(e),r)};zf[_$]=(t,e,r,s,n)=>{F6(e,r.doc,(i,o)=>S$(r,o))};var V6=3e4,S$=(t,e)=>console.warn(`Permission denied to access ${t.url}.
139
+ ${e}`),z6=(t,e,r)=>{let s=fn(e),n=yr(),i=Ze(s),o=t.messageHandlers[i];return o?o(n,s,t,r,i):console.error("Unable to compute message"),n},Zw=(t,e,r)=>{e===t.ws&&(t.emit("connection-close",[r,t]),t.ws=null,e.close(),t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,yg(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(K6,rl(QA(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},K6=t=>{if(t.shouldConnect&&t.ws===null){let e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=r=>{t.wsLastMessageReceived=hn();let s=z6(t,new Uint8Array(r.data),!0);Mm(s)>1&&e.send($t(s))},e.onerror=r=>{t.emit("connection-error",[r,t])},e.onclose=r=>{Zw(t,e,r)},e.onopen=()=>{t.wsLastMessageReceived=hn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);let r=yr();if(ze(r,mc),gg(r,t.doc),e.send($t(r)),t.awareness.getLocalState()!==null){let s=yr();ze(s,_l),Jt(s,vl(t.awareness,[t.doc.clientID])),e.send($t(s))}},t.emit("status",[{status:"connecting"}])}},Qw=(t,e)=>{let r=t.ws;t.wsconnected&&r&&r.readyState===r.OPEN&&r.send(e),t.bcconnected&&pc(t.bcChannel,e,t)},xg=class extends el{constructor(e,r,s,{connect:n=!0,awareness:i=new wl(s),params:o={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:d=-1,maxBackoffTime:u=2500,disableBc:l=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+r,this.maxBackoffTime=u,this.params=o,this.protocols=a,this.roomname=r,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=l,this.wsUnsuccessfulReconnects=0,this.messageHandlers=zf.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=n,this._resyncInterval=0,d>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let f=yr();ze(f,mc),gg(f,s),this.ws.send($t(f))}},d)),this._bcSubscriber=(f,h)=>{if(h!==this){let m=z6(this,new Uint8Array(f),!1);Mm(m)>1&&pc(this.bcChannel,$t(m),this)}},this._updateHandler=(f,h)=>{if(h!==this){let m=yr();ze(m,mc),M6(m,f),Qw(this,$t(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:h,removed:m},v)=>{let p=f.concat(h).concat(m),x=yr();ze(x,_l),Jt(x,vl(i,p)),Qw(this,$t(x))},this._exitHandler=()=>{yg(this.awareness,[s.clientID],"app closed")},Di&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&V6<hn()-this.wsLastMessageReceived&&Zw(this,this.ws,null)},V6/10),n&&this.connect()}get url(){let e=$6(this.params);return this.serverUrl+"/"+this.roomname+(e.length===0?"":"?"+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,this.emit("synced",[e]),this.emit("sync",[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Di&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(D6(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);let e=yr();ze(e,mc),gg(e,this.doc),pc(this.bcChannel,$t(e),this);let r=yr();ze(r,mc),Yw(r,this.doc),pc(this.bcChannel,$t(r),this);let s=yr();ze(s,q6),pc(this.bcChannel,$t(s),this);let n=yr();ze(n,_l),Jt(n,vl(this.awareness,[this.doc.clientID])),pc(this.bcChannel,$t(n),this)}disconnectBc(){let e=yr();ze(e,_l),Jt(e,vl(this.awareness,[this.doc.clientID],new Map)),Qw(this,$t(e)),this.bcconnected&&(N6(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Zw(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(K6(this),this.connectBc())}};var cf=globalThis.require??(0,oM.createRequire)(N),NQ=Object.create,v1=Object.defineProperty,OQ=Object.getOwnPropertyDescriptor,LQ=Object.getOwnPropertyNames,UQ=Object.getPrototypeOf,MQ=Object.prototype.hasOwnProperty,MU=(t=>typeof cf<"u"?cf:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof cf<"u"?cf:e)[r]}):t)(function(t){if(typeof cf<"u")return cf.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),jQ=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}},et=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},FQ=(t,e)=>{for(var r in e)v1(t,r,{get:e[r],enumerable:!0})},aM=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of LQ(e))!MQ.call(t,n)&&n!==r&&v1(t,n,{get:()=>e[n],enumerable:!(s=OQ(e,n))||s.enumerable});return t},cM=(t,e,r)=>(r=t!=null?NQ(UQ(t)):{},aM(e||!t||!t.__esModule?v1(r,"default",{value:t,enumerable:!0}):r,t)),HQ=t=>aM(v1({},"__esModule",{value:!0}),t),$Q=et((t,e)=>{"use strict";var r=1e3,s=r*60,n=s*60,i=n*24,o=i*7,a=i*365.25;e.exports=function(f,h){h=h||{};var m=typeof f;if(m==="string"&&f.length>0)return c(f);if(m==="number"&&isFinite(f))return h.long?u(f):d(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var h=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(h){var m=parseFloat(h[1]),v=(h[2]||"ms").toLowerCase();switch(v){case"years":case"year":case"yrs":case"yr":case"y":return m*a;case"weeks":case"week":case"w":return m*o;case"days":case"day":case"d":return m*i;case"hours":case"hour":case"hrs":case"hr":case"h":return m*n;case"minutes":case"minute":case"mins":case"min":case"m":return m*s;case"seconds":case"second":case"secs":case"sec":case"s":return m*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function d(f){var h=Math.abs(f);return h>=i?Math.round(f/i)+"d":h>=n?Math.round(f/n)+"h":h>=s?Math.round(f/s)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function u(f){var h=Math.abs(f);return h>=i?l(f,h,i,"day"):h>=n?l(f,h,n,"hour"):h>=s?l(f,h,s,"minute"):h>=r?l(f,h,r,"second"):f+" ms"}function l(f,h,m,v){var p=h>=m*1.5;return Math.round(f/m)+" "+v+(p?"s":"")}}),dM=et((t,e)=>{"use strict";function r(s){i.debug=i,i.default=i,i.coerce=l,i.disable=d,i.enable=a,i.enabled=u,i.humanize=$Q(),i.destroy=f,Object.keys(s).forEach(h=>{i[h]=s[h]}),i.names=[],i.skips=[],i.formatters={};function n(h){let m=0;for(let v=0;v<h.length;v++)m=(m<<5)-m+h.charCodeAt(v),m|=0;return i.colors[Math.abs(m)%i.colors.length]}i.selectColor=n;function i(h){let m,v=null,p,x;function w(...E){if(!w.enabled)return;let P=w,j=Number(new Date),T=j-(m||j);P.diff=T,P.prev=m,P.curr=j,m=j,E[0]=i.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let k=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(_,A)=>{if(_==="%%")return"%";k++;let M=i.formatters[A];if(typeof M=="function"){let V=E[k];_=M.call(P,V),E.splice(k,1),k--}return _}),i.formatArgs.call(P,E),(P.log||i.log).apply(P,E)}return w.namespace=h,w.useColors=i.useColors(),w.color=i.selectColor(h),w.extend=o,w.destroy=i.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(p!==i.namespaces&&(p=i.namespaces,x=i.enabled(h)),x),set:E=>{v=E}}),typeof i.init=="function"&&i.init(w),w}function o(h,m){let v=i(this.namespace+(typeof m>"u"?":":m)+h);return v.log=this.log,v}function a(h){i.save(h),i.namespaces=h,i.names=[],i.skips=[];let m=(typeof h=="string"?h:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let v of m)v[0]==="-"?i.skips.push(v.slice(1)):i.names.push(v)}function c(h,m){let v=0,p=0,x=-1,w=0;for(;v<h.length;)if(p<m.length&&(m[p]===h[v]||m[p]==="*"))m[p]==="*"?(x=p,w=v,p++):(v++,p++);else if(x!==-1)p=x+1,w++,v=w;else return!1;for(;p<m.length&&m[p]==="*";)p++;return p===m.length}function d(){let h=[...i.names,...i.skips.map(m=>"-"+m)].join(",");return i.enable(""),h}function u(h){for(let m of i.skips)if(c(h,m))return!1;for(let m of i.names)if(c(h,m))return!0;return!1}function l(h){return h instanceof Error?h.stack||h.message:h}function f(){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 i.enable(i.load()),i}e.exports=r}),VQ=et((t,e)=>{"use strict";t.formatArgs=s,t.save=n,t.load=i,t.useColors=r,t.storage=o(),t.destroy=(()=>{let c=!1;return()=>{c||(c=!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`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){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 c;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&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function s(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let d="color: "+this.color;c.splice(1,0,d,"color: inherit");let u=0,l=0;c[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(u++,f==="%c"&&(l=u))}),c.splice(l,0,d)}t.log=console.debug||console.log||(()=>{});function n(c){try{c?t.storage.setItem("debug",c):t.storage.removeItem("debug")}catch{}}function i(){let c;try{c=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function o(){try{return localStorage}catch{}}e.exports=dM()(t);var{formatters:a}=e.exports;a.j=function(c){try{return JSON.stringify(c)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}),lM={};FQ(lM,{createSupportsColor:()=>sA,default:()=>fM});function on(t,e=globalThis.Deno?globalThis.Deno.args:_1.default.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",s=e.indexOf(r+t),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}function qQ(){if(!("FORCE_COLOR"in Yt))return;if(Yt.FORCE_COLOR==="true")return 1;if(Yt.FORCE_COLOR==="false")return 0;if(Yt.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(Yt.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function zQ(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function KQ(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let s=qQ();s!==void 0&&(y1=s);let n=r?y1:s;if(n===0)return 0;if(r){if(on("color=16m")||on("color=full")||on("color=truecolor"))return 3;if(on("color=256"))return 2}if("TF_BUILD"in Yt&&"AGENT_NAME"in Yt)return 1;if(t&&!e&&n===void 0)return 0;let i=n||0;if(Yt.TERM==="dumb")return i;if(_1.default.platform==="win32"){let o=uM.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Yt)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Yt)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Yt)||Yt.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Yt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Yt.TEAMCITY_VERSION)?1:0;if(Yt.COLORTERM==="truecolor"||Yt.TERM==="xterm-kitty"||Yt.TERM==="xterm-ghostty"||Yt.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Yt){let o=Number.parseInt((Yt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Yt.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Yt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Yt.TERM)||"COLORTERM"in Yt?1:i}function sA(t,e={}){let r=KQ(t,{streamIsTTY:t&&t.isTTY,...e});return zQ(r)}var Yt,y1,jU,fM,WQ=jQ(()=>{"use strict";({env:Yt}=_1.default),on("no-color")||on("no-colors")||on("color=false")||on("color=never")?y1=0:(on("color")||on("colors")||on("color=true")||on("color=always"))&&(y1=1),jU={stdout:sA({isTTY:rA.default.isatty(1)}),stderr:sA({isTTY:rA.default.isatty(2)})},fM=jU}),GQ=et((t,e)=>{"use strict";var r=MU("tty"),s=MU("util");t.init=u,t.log=a,t.formatArgs=i,t.save=c,t.load=d,t.useColors=n,t.destroy=s.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let f=(WQ(),HQ(lM));f&&(f.stderr||f).level>=2&&(t.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{}t.inspectOpts=Object.keys(process.env).filter(f=>/^debug_/i.test(f)).reduce((f,h)=>{let m=h.substring(6).toLowerCase().replace(/_([a-z])/g,(p,x)=>x.toUpperCase()),v=process.env[h];return/^(yes|on|true|enabled)$/i.test(v)?v=!0:/^(no|off|false|disabled)$/i.test(v)?v=!1:v==="null"?v=null:v=Number(v),f[m]=v,f},{});function n(){return"colors"in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function i(f){let{namespace:h,useColors:m}=this;if(m){let v=this.color,p="\x1B[3"+(v<8?v:"8;5;"+v),x=` ${p};1m${h} \x1B[0m`;f[0]=x+f[0].split(`
140
+ `).join(`
141
+ `+x),f.push(p+"m+"+e.exports.humanize(this.diff)+"\x1B[0m")}else f[0]=o()+h+" "+f[0]}function o(){return t.inspectOpts.hideDate?"":new Date().toISOString()+" "}function a(...f){return process.stderr.write(s.formatWithOptions(t.inspectOpts,...f)+`
142
+ `)}function c(f){f?process.env.DEBUG=f:delete process.env.DEBUG}function d(){return process.env.DEBUG}function u(f){f.inspectOpts={};let h=Object.keys(t.inspectOpts);for(let m=0;m<h.length;m++)f.inspectOpts[h[m]]=t.inspectOpts[h[m]]}e.exports=dM()(t);var{formatters:l}=e.exports;l.o=function(f){return this.inspectOpts.colors=this.useColors,s.inspect(f,this.inspectOpts).split(`
143
+ `).map(h=>h.trim()).join(" ")},l.O=function(f){return this.inspectOpts.colors=this.useColors,s.inspect(f,this.inspectOpts)}}),S1=et((t,e)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?e.exports=VQ():e.exports=GQ()}),XQ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})}),Es=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=S1(),r="media-client",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=(0,e.default)(`${r}:${n}`),this._warn=(0,e.default)(`${r}:WARN:${n}`),this._error=(0,e.default)(`${r}:ERROR:${n}`)):(this._debug=(0,e.default)(r),this._warn=(0,e.default)(`${r}:WARN`),this._error=(0,e.default)(`${r}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),YQ=et((t,e)=>{"use strict";var r=typeof Reflect=="object"?Reflect:null,s=r&&typeof r.apply=="function"?r.apply:function(T,k,_){return Function.prototype.apply.call(T,k,_)},n;r&&typeof r.ownKeys=="function"?n=r.ownKeys:Object.getOwnPropertySymbols?n=function(T){return Object.getOwnPropertyNames(T).concat(Object.getOwnPropertySymbols(T))}:n=function(T){return Object.getOwnPropertyNames(T)};function i(T){console&&console.warn&&console.warn(T)}var o=Number.isNaN||function(T){return T!==T};function a(){a.init.call(this)}e.exports=a,e.exports.once=E,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function d(T){if(typeof T!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof T)}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(T){if(typeof T!="number"||T<0||o(T))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+T+".");c=T}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(T){if(typeof T!="number"||T<0||o(T))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+T+".");return this._maxListeners=T,this};function u(T){return T._maxListeners===void 0?a.defaultMaxListeners:T._maxListeners}a.prototype.getMaxListeners=function(){return u(this)},a.prototype.emit=function(T){for(var k=[],_=1;_<arguments.length;_++)k.push(arguments[_]);var A=T==="error",M=this._events;if(M!==void 0)A=A&&M.error===void 0;else if(!A)return!1;if(A){var V;if(k.length>0&&(V=k[0]),V instanceof Error)throw V;var Y=new Error("Unhandled error."+(V?" ("+V.message+")":""));throw Y.context=V,Y}var H=M[T];if(H===void 0)return!1;if(typeof H=="function")s(H,this,k);else for(var F=H.length,K=p(H,F),_=0;_<F;++_)s(K[_],this,k);return!0};function l(T,k,_,A){var M,V,Y;if(d(_),V=T._events,V===void 0?(V=T._events=Object.create(null),T._eventsCount=0):(V.newListener!==void 0&&(T.emit("newListener",k,_.listener?_.listener:_),V=T._events),Y=V[k]),Y===void 0)Y=V[k]=_,++T._eventsCount;else if(typeof Y=="function"?Y=V[k]=A?[_,Y]:[Y,_]:A?Y.unshift(_):Y.push(_),M=u(T),M>0&&Y.length>M&&!Y.warned){Y.warned=!0;var H=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(k)+" listeners added. Use emitter.setMaxListeners() to increase limit");H.name="MaxListenersExceededWarning",H.emitter=T,H.type=k,H.count=Y.length,i(H)}return T}a.prototype.addListener=function(T,k){return l(this,T,k,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(T,k){return l(this,T,k,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(T,k,_){var A={fired:!1,wrapFn:void 0,target:T,type:k,listener:_},M=f.bind(A);return M.listener=_,A.wrapFn=M,M}a.prototype.once=function(T,k){return d(k),this.on(T,h(this,T,k)),this},a.prototype.prependOnceListener=function(T,k){return d(k),this.prependListener(T,h(this,T,k)),this},a.prototype.removeListener=function(T,k){var _,A,M,V,Y;if(d(k),A=this._events,A===void 0)return this;if(_=A[T],_===void 0)return this;if(_===k||_.listener===k)--this._eventsCount===0?this._events=Object.create(null):(delete A[T],A.removeListener&&this.emit("removeListener",T,_.listener||k));else if(typeof _!="function"){for(M=-1,V=_.length-1;V>=0;V--)if(_[V]===k||_[V].listener===k){Y=_[V].listener,M=V;break}if(M<0)return this;M===0?_.shift():x(_,M),_.length===1&&(A[T]=_[0]),A.removeListener!==void 0&&this.emit("removeListener",T,Y||k)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(T){var k,_,A;if(_=this._events,_===void 0)return this;if(_.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_[T]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _[T]),this;if(arguments.length===0){var M=Object.keys(_),V;for(A=0;A<M.length;++A)V=M[A],V!=="removeListener"&&this.removeAllListeners(V);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(k=_[T],typeof k=="function")this.removeListener(T,k);else if(k!==void 0)for(A=k.length-1;A>=0;A--)this.removeListener(T,k[A]);return this};function m(T,k,_){var A=T._events;if(A===void 0)return[];var M=A[k];return M===void 0?[]:typeof M=="function"?_?[M.listener||M]:[M]:_?w(M):p(M,M.length)}a.prototype.listeners=function(T){return m(this,T,!0)},a.prototype.rawListeners=function(T){return m(this,T,!1)},a.listenerCount=function(T,k){return typeof T.listenerCount=="function"?T.listenerCount(k):v.call(T,k)},a.prototype.listenerCount=v;function v(T){var k=this._events;if(k!==void 0){var _=k[T];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function p(T,k){for(var _=new Array(k),A=0;A<k;++A)_[A]=T[A];return _}function x(T,k){for(;k+1<T.length;k++)T[k]=T[k+1];T.pop()}function w(T){for(var k=new Array(T.length),_=0;_<k.length;++_)k[_]=T[_].listener||T[_];return k}function E(T,k){return new Promise(function(_,A){function M(Y){T.removeListener(k,V),A(Y)}function V(){typeof T.removeListener=="function"&&T.removeListener("error",M),_([].slice.call(arguments))}j(T,k,V,{once:!0}),k!=="error"&&P(T,M,{once:!0})})}function P(T,k,_){typeof T.on=="function"&&j(T,"error",k,_)}function j(T,k,_,A){if(typeof T.on=="function")A.once?T.once(k,_):T.on(k,_);else if(typeof T.addEventListener=="function")T.addEventListener(k,function M(V){A.once&&T.removeEventListener(k,M),_(V)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof T)}}),Us=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnhancedEventEmitter=void 0;var e=YQ(),r=Es(),s=new r.Logger("EnhancedEventEmitter"),n=class extends e.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(i,...o){return super.emit(i,...o)}safeEmit(i,...o){try{return super.emit(i,...o)}catch(a){s.error("safeEmit() | event listener threw an error [eventName:%s]:%o",i,a);try{super.emit("listenererror",i,a)}catch{}return!!super.listenerCount(i)}}on(i,o){return super.on(i,o),this}off(i,o){return super.off(i,o),this}addListener(i,o){return super.on(i,o),this}prependListener(i,o){return super.prependListener(i,o),this}once(i,o){return super.once(i,o),this}prependOnceListener(i,o){return super.prependOnceListener(i,o),this}removeListener(i,o){return super.off(i,o),this}removeAllListeners(i){return super.removeAllListeners(i),this}listenerCount(i){return super.listenerCount(i)}listeners(i){return super.listeners(i)}rawListeners(i){return super.rawListeners(i)}};t.EnhancedEventEmitter=n}),jn=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidStateError=t.UnsupportedError=void 0;var e=class hM extends Error{constructor(n){super(n),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,hM):this.stack=new Error(n).stack}};t.UnsupportedError=e;var r=class pM extends Error{constructor(n){super(n),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,pM):this.stack=new Error(n).stack}};t.InvalidStateError=r}),uf=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=e,t.generateRandomNumber=r,t.deepFreeze=s;function e(n){if(n!==void 0)return Number.isNaN(n)?NaN:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}function r(){return Math.round(Math.random()*1e7)}function s(n){let i=Reflect.ownKeys(n);for(let o of i){let a=n[o];(a&&typeof a=="object"||typeof a=="function")&&s(a)}return Object.freeze(n)}}),JQ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=S1(),r="h264-profile-level-id",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=(0,e.default)(`${r}:${n}`),this._warn=(0,e.default)(`${r}:WARN:${n}`),this._error=(0,e.default)(`${r}:ERROR:${n}`)):(this._debug=(0,e.default)(r),this._warn=(0,e.default)(`${r}:WARN`),this._error=(0,e.default)(`${r}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),QQ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProfileLevelId=t.Level=t.Profile=void 0,t.parseProfileLevelId=l,t.profileLevelIdToString=f,t.profileToString=h,t.levelToString=m,t.parseSdpProfileLevelId=v,t.isSameProfile=p,t.isSameProfileAndLevel=x,t.generateProfileLevelIdStringForAnswer=w,t.supportedLevel=E;var e=JQ(),r=new e.Logger,s;(function(_){_[_.ConstrainedBaseline=1]="ConstrainedBaseline",_[_.Baseline=2]="Baseline",_[_.Main=3]="Main",_[_.ConstrainedHigh=4]="ConstrainedHigh",_[_.High=5]="High",_[_.PredictiveHigh444=6]="PredictiveHigh444"})(s||(t.Profile=s={}));var n;(function(_){_[_.L1_b=0]="L1_b",_[_.L1=10]="L1",_[_.L1_1=11]="L1_1",_[_.L1_2=12]="L1_2",_[_.L1_3=13]="L1_3",_[_.L2=20]="L2",_[_.L2_1=21]="L2_1",_[_.L2_2=22]="L2_2",_[_.L3=30]="L3",_[_.L3_1=31]="L3_1",_[_.L3_2=32]="L3_2",_[_.L4=40]="L4",_[_.L4_1=41]="L4_1",_[_.L4_2=42]="L4_2",_[_.L5=50]="L5",_[_.L5_1=51]="L5_1",_[_.L5_2=52]="L5_2"})(n||(t.Level=n={}));var i=class{profile;level;constructor(_,A){this.profile=_,this.level=A}};t.ProfileLevelId=i;var o=new i(s.ConstrainedBaseline,n.L3_1),a=class{mask;masked_value;constructor(_){this.mask=~P("x",_),this.masked_value=P("1",_)}isMatch(_){return this.masked_value===(_&this.mask)}},c=class{profile_idc;profile_iop;profile;constructor(_,A,M){this.profile_idc=_,this.profile_iop=A,this.profile=M}},d=[new c(66,new a("x1xx0000"),s.ConstrainedBaseline),new c(77,new a("1xxx0000"),s.ConstrainedBaseline),new c(88,new a("11xx0000"),s.ConstrainedBaseline),new c(66,new a("x0xx0000"),s.Baseline),new c(88,new a("10xx0000"),s.Baseline),new c(77,new a("0x0x0000"),s.Main),new c(100,new a("00000000"),s.High),new c(100,new a("00001100"),s.ConstrainedHigh),new c(244,new a("00000000"),s.PredictiveHigh444)],u=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:n.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:n.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:n.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:n.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:n.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:n.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:n.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:n.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:n.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:n.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:n.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:n.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:n.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:n.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:n.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:n.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:n.L5_2}];function l(_){if(typeof _!="string"||_.length!==6)return;let A=parseInt(_,16);if(A===0)return;let M=A&255,V=A>>8&255,Y=A>>16&255,H;switch(M){case n.L1_1:{H=(V&16)!==0?n.L1_b:n.L1_1;break}case n.L1:case n.L1_2:case n.L1_3:case n.L2:case n.L2_1:case n.L2_2:case n.L3:case n.L3_1:case n.L3_2:case n.L4:case n.L4_1:case n.L4_2:case n.L5:case n.L5_1:case n.L5_2:{H=M;break}default:{r.warn(`parseProfileLevelId() | unrecognized level_idc [str:${_}, level_idc:${M}]`);return}}for(let F of d)if(Y===F.profile_idc&&F.profile_iop.isMatch(V))return r.debug(`parseProfileLevelId() | result [str:${_}, profile:${F.profile}, level:${H}]`),new i(F.profile,H);r.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${_}, profile_idc:${Y}, profile_iop:${V}]`)}function f(_){if(_.level==n.L1_b)switch(_.profile){case s.ConstrainedBaseline:return"42f00b";case s.Baseline:return"42100b";case s.Main:return"4d100b";default:{r.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${_.profile}`);return}}let A;switch(_.profile){case s.ConstrainedBaseline:{A="42e0";break}case s.Baseline:{A="4200";break}case s.Main:{A="4d00";break}case s.ConstrainedHigh:{A="640c";break}case s.High:{A="6400";break}case s.PredictiveHigh444:{A="f400";break}default:{r.warn(`profileLevelIdToString() | unrecognized profile ${_.profile}`);return}}let M=_.level.toString(16);return M.length===1&&(M=`0${M}`),`${A}${M}`}function h(_){switch(_){case s.ConstrainedBaseline:return"ConstrainedBaseline";case s.Baseline:return"Baseline";case s.Main:return"Main";case s.ConstrainedHigh:return"ConstrainedHigh";case s.High:return"High";case s.PredictiveHigh444:return"PredictiveHigh444";default:{r.warn(`profileToString() | unrecognized profile ${_}`);return}}}function m(_){switch(_){case n.L1_b:return"1b";case n.L1:return"1";case n.L1_1:return"1.1";case n.L1_2:return"1.2";case n.L1_3:return"1.3";case n.L2:return"2";case n.L2_1:return"2.1";case n.L2_2:return"2.2";case n.L3:return"3";case n.L3_1:return"3.1";case n.L3_2:return"3.2";case n.L4:return"4";case n.L4_1:return"4.1";case n.L4_2:return"4.2";case n.L5:return"5";case n.L5_1:return"5.1";case n.L5_2:return"5.2";default:{r.warn(`levelToString() | unrecognized level ${_}`);return}}}function v(_={}){let A=_["profile-level-id"];return A?l(A):o}function p(_={},A={}){let M=v(_),V=v(A);return!!(M&&V&&M.profile===V.profile)}function x(_={},A={}){let M=v(_),V=v(A);return!!(M&&V&&M.profile===V.profile&&M.level==V.level)}function w(_={},A={}){if(!_["profile-level-id"]&&!A["profile-level-id"]){r.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let M=v(_),V=v(A);if(!M)throw new TypeError("invalid local_profile_level_id");if(!V)throw new TypeError("invalid remote_profile_level_id");if(M.profile!==V.profile)throw new TypeError("H264 Profile mismatch");let Y=k(_)&&k(A),H=M.level,F=V.level,K=T(H,F),I=Y?H:K;return r.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${M.profile}, level:${I}]`),f(new i(M.profile,I))}function E(_,A){for(let M=u.length-1;M>=0;--M){let V=u[M];if(V.max_macroblock_frame_size*256<=_&&V.max_macroblocks_per_second<=A*V.max_macroblock_frame_size)return r.debug(`supportedLevel() | result [max_frame_pixel_count:${_}, max_fps:${A}, level:${V.level}]`),V.level}r.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${_}, max_fps:${A}]`)}function P(_,A){return+(A[0]===_)<<7|+(A[1]===_)<<6|+(A[2]===_)<<5|+(A[3]===_)<<4|+(A[4]===_)<<3|+(A[5]===_)<<2|+(A[6]===_)<<1|+(A[7]===_)<<0}function j(_,A){return _===n.L1_b?A!==n.L1&&A!==n.L1_b:A===n.L1_b?_!==n.L1:_<A}function T(_,A){return j(_,A)?_:A}function k(_={}){let A=_["level-asymmetry-allowed"];return A===!0||A===1||A==="1"}}),Oo=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAndNormalizeRtpCapabilities=o,t.validateAndNormalizeRtpParameters=a,t.validateAndNormalizeSctpStreamParameters=c,t.validateSctpCapabilities=d,t.getExtendedRtpCapabilities=u,t.getRecvRtpCapabilities=l,t.getSendRtpCapabilities=f,t.getSendingRtpParameters=h,t.getSendingRemoteRtpParameters=m,t.reduceCodecs=v,t.generateProbatorRtpParameters=p,t.canSend=x,t.canReceive=w;var e=QQ(),r=uf(),s="probator",n=1234,i=127;function o(I){if(typeof I!="object")throw new TypeError("caps is not an object");if(I.codecs&&!Array.isArray(I.codecs))throw new TypeError("caps.codecs is not an array");I.codecs||(I.codecs=[]);for(let G of I.codecs)E(G);if(I.headerExtensions&&!Array.isArray(I.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");I.headerExtensions||(I.headerExtensions=[]);for(let G of I.headerExtensions)j(G)}function a(I){if(typeof I!="object")throw new TypeError("params is not an object");if(I.mid&&typeof I.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(I.codecs))throw new TypeError("missing params.codecs");for(let G of I.codecs)T(G);if(I.headerExtensions&&!Array.isArray(I.headerExtensions))throw new TypeError("params.headerExtensions is not an array");I.headerExtensions||(I.headerExtensions=[]);for(let G of I.headerExtensions)k(G);if(I.encodings&&!Array.isArray(I.encodings))throw new TypeError("params.encodings is not an array");I.encodings||(I.encodings=[]);for(let G of I.encodings)_(G);if(I.rtcp&&typeof I.rtcp!="object")throw new TypeError("params.rtcp is not an object");I.rtcp||(I.rtcp={}),A(I.rtcp)}function c(I){if(typeof I!="object")throw new TypeError("params is not an object");if(typeof I.streamId!="number")throw new TypeError("missing params.streamId");let G=!1;if(typeof I.ordered=="boolean"?G=!0:I.ordered=!0,I.maxPacketLifeTime&&typeof I.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(I.maxRetransmits&&typeof I.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(I.maxPacketLifeTime&&I.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(G&&I.ordered&&(I.maxPacketLifeTime||I.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!G&&(I.maxPacketLifeTime||I.maxRetransmits)&&(I.ordered=!1),I.label&&typeof I.label!="string")throw new TypeError("invalid params.label");if(I.protocol&&typeof I.protocol!="string")throw new TypeError("invalid params.protocol")}function d(I){if(typeof I!="object")throw new TypeError("caps is not an object");if(!I.numStreams||typeof I.numStreams!="object")throw new TypeError("missing caps.numStreams");M(I.numStreams)}function u(I,G,se){let D={codecs:[],headerExtensions:[]};if(se)for(let O of I.codecs??[]){if(Y(O))continue;let W=(G.codecs??[]).find(Q=>H(Q,O,{strict:!0,modify:!0}));if(!W)continue;let q={kind:O.kind,mimeType:O.mimeType,clockRate:O.clockRate,channels:O.channels,localPayloadType:O.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:W.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:O.parameters??{},remoteParameters:W.parameters??{},rtcpFeedback:K(O,W)};D.codecs.push(q)}else for(let O of G.codecs??[]){if(Y(O))continue;let W=(I.codecs??[]).find(Q=>H(Q,O,{strict:!0,modify:!0}));if(!W)continue;let q={kind:W.kind,mimeType:W.mimeType,clockRate:W.clockRate,channels:W.channels,localPayloadType:W.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:O.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:W.parameters??{},remoteParameters:O.parameters??{},rtcpFeedback:K(W,O)};D.codecs.push(q)}for(let O of D.codecs){let W=I.codecs.find(Q=>Y(Q)&&Q.parameters?.apt===O.localPayloadType),q=G.codecs.find(Q=>Y(Q)&&Q.parameters?.apt===O.remotePayloadType);W&&q&&(O.localRtxPayloadType=W.preferredPayloadType,O.remoteRtxPayloadType=q.preferredPayloadType)}for(let O of G.headerExtensions){let W=I.headerExtensions.find(Q=>F(Q,O));if(!W)continue;let q={kind:O.kind,uri:O.uri,sendId:W.preferredId,recvId:O.preferredId,encrypt:W.preferredEncrypt??!1,direction:"sendrecv"};switch(O.direction){case"sendrecv":{q.direction="sendrecv";break}case"recvonly":{q.direction="sendonly";break}case"sendonly":{q.direction="recvonly";break}case"inactive":{q.direction="inactive";break}}D.headerExtensions.push(q)}return D}function l(I){return V({direction:"recvonly",extendedRtpCapabilities:I})}function f(I){return V({direction:"sendonly",extendedRtpCapabilities:I})}function h(I,G){let se={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let D of G.codecs){if(D.kind!==I)continue;let O={mimeType:D.mimeType,payloadType:D.localPayloadType,clockRate:D.clockRate,channels:D.channels,parameters:D.localParameters,rtcpFeedback:D.rtcpFeedback};if(se.codecs.push(O),D.localRtxPayloadType){let W={mimeType:`${D.kind}/rtx`,payloadType:D.localRtxPayloadType,clockRate:D.clockRate,parameters:{apt:D.localPayloadType},rtcpFeedback:[]};se.codecs.push(W)}}for(let D of G.headerExtensions){if(D.kind&&D.kind!==I||D.direction!=="sendrecv"&&D.direction!=="sendonly")continue;let O={uri:D.uri,id:D.sendId,encrypt:D.encrypt,parameters:{}};se.headerExtensions.push(O)}return se}function m(I,G){let se={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let D of G.codecs){if(D.kind!==I)continue;let O={mimeType:D.mimeType,payloadType:D.localPayloadType,clockRate:D.clockRate,channels:D.channels,parameters:D.remoteParameters,rtcpFeedback:D.rtcpFeedback};if(se.codecs.push(O),D.localRtxPayloadType){let W={mimeType:`${D.kind}/rtx`,payloadType:D.localRtxPayloadType,clockRate:D.clockRate,parameters:{apt:D.localPayloadType},rtcpFeedback:[]};se.codecs.push(W)}}for(let D of G.headerExtensions){if(D.kind&&D.kind!==I||D.direction!=="sendrecv"&&D.direction!=="sendonly")continue;let O={uri:D.uri,id:D.sendId,encrypt:D.encrypt,parameters:{}};se.headerExtensions.push(O)}if(se.headerExtensions.some(D=>D.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let D of se.codecs)D.rtcpFeedback=(D.rtcpFeedback??[]).filter(O=>O.type!=="goog-remb");else if(se.headerExtensions.some(D=>D.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let D of se.codecs)D.rtcpFeedback=(D.rtcpFeedback??[]).filter(O=>O.type!=="transport-cc");else for(let D of se.codecs)D.rtcpFeedback=(D.rtcpFeedback??[]).filter(O=>O.type!=="transport-cc"&&O.type!=="goog-remb");return se}function v(I,G){let se=[];if(!G)se.push(I[0]),Y(I[1])&&se.push(I[1]);else{for(let D=0;D<I.length;++D)if(H(I[D],G,{strict:!0})){se.push(I[D]),Y(I[D+1])&&se.push(I[D+1]);break}if(se.length===0)throw new TypeError("no matching codec found")}return se}function p(I){I=r.clone(I),a(I);let G={mid:s,codecs:[],headerExtensions:[],encodings:[{ssrc:n}],rtcp:{cname:"probator"}};return G.codecs.push(I.codecs[0]),G.codecs[0].payloadType=i,G.headerExtensions=I.headerExtensions,G}function x(I,G){return(G.codecs??[]).some(se=>se.kind===I)}function w(I,G){if(a(I),I.codecs.length===0)return!1;let se=I.codecs[0];return(G.codecs??[]).some(D=>D.preferredPayloadType===se.payloadType)}function E(I){let G=new RegExp("^(audio|video)/(.+)","i");if(typeof I!="object")throw new TypeError("codec is not an object");if(!I.mimeType||typeof I.mimeType!="string")throw new TypeError("missing codec.mimeType");let se=G.exec(I.mimeType);if(!se)throw new TypeError("invalid codec.mimeType");if(I.kind=se[1].toLowerCase(),typeof I.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof I.clockRate!="number")throw new TypeError("missing codec.clockRate");I.kind==="audio"?typeof I.channels!="number"&&(I.channels=1):delete I.channels,(!I.parameters||typeof I.parameters!="object")&&(I.parameters={});for(let D of Object.keys(I.parameters)){let O=I.parameters[D];if(O===void 0&&(I.parameters[D]="",O=""),typeof O!="string"&&typeof O!="number")throw new TypeError(`invalid codec parameter [key:${D}s, value:${O}]`);if(D==="apt"&&typeof O!="number")throw new TypeError("invalid codec apt parameter")}(!I.rtcpFeedback||!Array.isArray(I.rtcpFeedback))&&(I.rtcpFeedback=[]);for(let D of I.rtcpFeedback)P(D)}function P(I){if(typeof I!="object")throw new TypeError("fb is not an object");if(!I.type||typeof I.type!="string")throw new TypeError("missing fb.type");(!I.parameter||typeof I.parameter!="string")&&(I.parameter="")}function j(I){if(typeof I!="object")throw new TypeError("ext is not an object");if(I.kind!=="audio"&&I.kind!=="video")throw new TypeError("invalid ext.kind");if(!I.uri||typeof I.uri!="string")throw new TypeError("missing ext.uri");if(typeof I.preferredId!="number")throw new TypeError("missing ext.preferredId");if(I.preferredEncrypt&&typeof I.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(I.preferredEncrypt||(I.preferredEncrypt=!1),I.direction&&typeof I.direction!="string")throw new TypeError("invalid ext.direction");I.direction||(I.direction="sendrecv")}function T(I){let G=new RegExp("^(audio|video)/(.+)","i");if(typeof I!="object")throw new TypeError("codec is not an object");if(!I.mimeType||typeof I.mimeType!="string")throw new TypeError("missing codec.mimeType");let se=G.exec(I.mimeType);if(!se)throw new TypeError("invalid codec.mimeType");if(typeof I.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof I.clockRate!="number")throw new TypeError("missing codec.clockRate");se[1].toLowerCase()==="audio"?typeof I.channels!="number"&&(I.channels=1):delete I.channels,(!I.parameters||typeof I.parameters!="object")&&(I.parameters={});for(let D of Object.keys(I.parameters)){let O=I.parameters[D];if(O===void 0&&(I.parameters[D]="",O=""),typeof O!="string"&&typeof O!="number")throw new TypeError(`invalid codec parameter [key:${D}s, value:${O}]`);if(D==="apt"&&typeof O!="number")throw new TypeError("invalid codec apt parameter")}(!I.rtcpFeedback||!Array.isArray(I.rtcpFeedback))&&(I.rtcpFeedback=[]);for(let D of I.rtcpFeedback)P(D)}function k(I){if(typeof I!="object")throw new TypeError("ext is not an object");if(!I.uri||typeof I.uri!="string")throw new TypeError("missing ext.uri");if(typeof I.id!="number")throw new TypeError("missing ext.id");if(I.encrypt&&typeof I.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");I.encrypt||(I.encrypt=!1),(!I.parameters||typeof I.parameters!="object")&&(I.parameters={});for(let G of Object.keys(I.parameters)){let se=I.parameters[G];if(se===void 0&&(I.parameters[G]="",se=""),typeof se!="string"&&typeof se!="number")throw new TypeError("invalid header extension parameter")}}function _(I){if(typeof I!="object")throw new TypeError("encoding is not an object");if(I.ssrc&&typeof I.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(I.rid&&typeof I.rid!="string")throw new TypeError("invalid encoding.rid");if(I.rtx&&typeof I.rtx!="object")throw new TypeError("invalid encoding.rtx");if(I.rtx&&typeof I.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!I.dtx||typeof I.dtx!="boolean")&&(I.dtx=!1),I.scalabilityMode&&typeof I.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function A(I){if(typeof I!="object")throw new TypeError("rtcp is not an object");if(I.cname&&typeof I.cname!="string")throw new TypeError("invalid rtcp.cname");(!I.reducedSize||typeof I.reducedSize!="boolean")&&(I.reducedSize=!0)}function M(I){if(typeof I!="object")throw new TypeError("numStreams is not an object");if(typeof I.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof I.MIS!="number")throw new TypeError("missing numStreams.MIS")}function V({direction:I,extendedRtpCapabilities:G}){let se={codecs:[],headerExtensions:[]};for(let D of G.codecs){let O={kind:D.kind,mimeType:D.mimeType,preferredPayloadType:D.remotePayloadType,clockRate:D.clockRate,channels:D.channels,parameters:D.localParameters,rtcpFeedback:D.rtcpFeedback};if(se.codecs.push(O),!D.remoteRtxPayloadType)continue;let W={kind:D.kind,mimeType:`${D.kind}/rtx`,preferredPayloadType:D.remoteRtxPayloadType,clockRate:D.clockRate,parameters:{apt:D.remotePayloadType},rtcpFeedback:[]};se.codecs.push(W)}for(let D of G.headerExtensions){if(D.direction!=="sendrecv"&&D.direction!==I)continue;let O={kind:D.kind,uri:D.uri,preferredId:D.recvId,preferredEncrypt:D.encrypt??!1,direction:D.direction};se.headerExtensions.push(O)}return se}function Y(I){return I?/.+\/rtx$/i.test(I.mimeType):!1}function H(I,G,{strict:se=!1,modify:D=!1}={}){let O=I.mimeType.toLowerCase(),W=G.mimeType.toLowerCase();if(O!==W||I.clockRate!==G.clockRate||I.channels!==G.channels)return!1;switch(O){case"video/h264":{if(se){let q=I.parameters["packetization-mode"]??0,Q=G.parameters["packetization-mode"]??0;if(q!==Q||!e.isSameProfile(I.parameters,G.parameters))return!1;let pe;try{pe=e.generateProfileLevelIdStringForAnswer(I.parameters,G.parameters)}catch{return!1}D&&(pe?(I.parameters["profile-level-id"]=pe,G.parameters["profile-level-id"]=pe):(delete I.parameters["profile-level-id"],delete G.parameters["profile-level-id"]))}break}case"video/vp9":{if(se){let q=I.parameters["profile-id"]??0,Q=G.parameters["profile-id"]??0;if(q!==Q)return!1}break}}return!0}function F(I,G){return!(I.kind&&G.kind&&I.kind!==G.kind||I.uri!==G.uri)}function K(I,G){let se=[];for(let D of I.rtcpFeedback??[]){let O=(G.rtcpFeedback??[]).find(W=>W.type===D.type&&(W.parameter===D.parameter||!W.parameter&&!D.parameter));O&&se.push(O)}return se}}),ZQ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=S1(),r="awaitqueue",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=e(`${r}:${n}`),this._warn=e(`${r}:WARN:${n}`),this._error=e(`${r}:ERROR:${n}`)):(this._debug=e(r),this._warn=e(`${r}:WARN`),this._error=e(`${r}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),mM=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueueRemovedTaskError=t.AwaitQueueStoppedError=void 0;var e=class gM extends Error{constructor(n){super(n??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,gM)}};t.AwaitQueueStoppedError=e;var r=class yM extends Error{constructor(n){super(n??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,yM)}};t.AwaitQueueRemovedTaskError=r}),eZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueue=void 0;var e=ZQ(),r=mM(),s=new e.Logger("AwaitQueue"),n=class{pendingTasks=new Map;nextTaskId=0;constructor(){s.debug("constructor()")}get size(){return this.pendingTasks.size}async push(i,o,a){if(o=o??i.name,s.debug(`push() [name:${o}, options:%o]`,a),typeof i!="function")throw new TypeError("given task is not a function");if(o)try{Object.defineProperty(i,"name",{value:o})}catch{}return new Promise((c,d)=>{if(o&&a?.removeOngoingTasksWithSameName)for(let l of this.pendingTasks.values())l.name===o&&l.reject(new r.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let u={id:this.nextTaskId++,task:i,name:o,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:l=>{if(u.completed)return;u.completed=!0,this.pendingTasks.delete(u.id),s.debug(`resolving task [name:${u.name}]`),c(l);let[f]=this.pendingTasks.values();f&&!f.executedAt&&this.execute(f)},reject:(l,{canExecuteNextTask:f})=>{if(!u.completed&&(u.completed=!0,this.pendingTasks.delete(u.id),s.debug(`rejecting task [name:${u.name}]: %s`,String(l)),d(l),f)){let[h]=this.pendingTasks.values();h&&!h.executedAt&&this.execute(h)}}};this.pendingTasks.set(u.id,u),this.pendingTasks.size===1&&this.execute(u)})}stop(){s.debug("stop()");for(let i of this.pendingTasks.values())s.debug(`stop() | stopping task [name:${i.name}]`),i.reject(new r.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(i){s.debug(`remove() [taskIdx:${i}]`);let o=Array.from(this.pendingTasks.values())[i];if(!o){s.debug(`stop() | no task with given idx [taskIdx:${i}]`);return}o.reject(new r.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let i=Date.now(),o=0;return Array.from(this.pendingTasks.values()).map(a=>({idx:o++,task:a.task,name:a.name,enqueuedTime:a.executedAt?a.executedAt-a.enqueuedAt:i-a.enqueuedAt,executionTime:a.executedAt?i-a.executedAt:0}))}async execute(i){if(s.debug(`execute() [name:${i.name}]`),i.executedAt)throw new Error("task already being executed");i.executedAt=Date.now();try{let o=await i.task();i.resolve(o)}catch(o){i.reject(o,{canExecuteNextTask:!0})}}};t.AwaitQueue=n}),tZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueueRemovedTaskError=t.AwaitQueueStoppedError=t.AwaitQueue=void 0;var e=eZ();Object.defineProperty(t,"AwaitQueue",{enumerable:!0,get:function(){return e.AwaitQueue}});var r=mM();Object.defineProperty(t,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(t,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}),rZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Producer=void 0;var e=Es(),r=Us(),s=jn(),n=new e.Logger("Producer"),i=class extends r.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,localId:a,rtpSender:c,track:d,rtpParameters:u,stopTracks:l,disableTrackOnPause:f,zeroRtpOnPause:h,appData:m}){super(),n.debug("constructor()"),this._id=o,this._localId=a,this._rtpSender=c,this._track=d,this._kind=d.kind,this._rtpParameters=u,this._paused=f?!d.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=l,this._disableTrackOnPause=f,this._zeroRtpOnPause=h,this._appData=m??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new s.InvalidStateError("closed");return new Promise((o,a)=>{this.safeEmit("@getstats",o,a)})}pause(){if(n.debug("pause()"),this._closed){n.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((o,a)=>{this.safeEmit("@pause",o,a)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(n.debug("resume()"),this._closed){n.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((o,a)=>{this.safeEmit("@resume",o,a)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:o}){if(n.debug("replaceTrack() [track:%o]",o),this._closed){if(o&&this._stopTracks)try{o.stop()}catch{}throw new s.InvalidStateError("closed")}else if(o?.readyState==="ended")throw new s.InvalidStateError("track ended");if(o===this._track){n.debug("replaceTrack() | same track, ignored");return}await new Promise((a,c)=>{this.safeEmit("@replacetrack",o,a,c)}),this.destroyTrack(),this._track=o,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(o){if(this._closed)throw new s.InvalidStateError("closed");if(this._kind!=="video")throw new s.UnsupportedError("not a video Producer");if(typeof o!="number")throw new TypeError("invalid spatialLayer");o!==this._maxSpatialLayer&&(await new Promise((a,c)=>{this.safeEmit("@setmaxspatiallayer",o,a,c)}).catch(()=>{}),this._maxSpatialLayer=o)}async setRtpEncodingParameters(o){if(this._closed)throw new s.InvalidStateError("closed");if(typeof o!="object")throw new TypeError("invalid params");await new Promise((a,c)=>{this.safeEmit("@setrtpencodingparameters",o,a,c)})}onTrackEnded(){n.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};t.Producer=i}),sZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Consumer=void 0;var e=Es(),r=Us(),s=jn(),n=new e.Logger("Consumer"),i=class extends r.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,localId:a,producerId:c,rtpReceiver:d,track:u,rtpParameters:l,appData:f}){super(),n.debug("constructor()"),this._id=o,this._localId=a,this._producerId=c,this._rtpReceiver=d,this._track=u,this._rtpParameters=l,this._paused=!u.enabled,this._appData=f??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new s.InvalidStateError("closed");return new Promise((o,a)=>{this.safeEmit("@getstats",o,a)})}pause(){if(n.debug("pause()"),this._closed){n.error("pause() | Consumer closed");return}if(this._paused){n.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(n.debug("resume()"),this._closed){n.error("resume() | Consumer closed");return}if(!this._paused){n.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){n.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};t.Consumer=i}),nZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataProducer=void 0;var e=Es(),r=Us(),s=jn(),n=new e.Logger("DataProducer"),i=class extends r.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,dataChannel:a,sctpStreamParameters:c,appData:d}){super(),n.debug("constructor()"),this._id=o,this._dataChannel=a,this._sctpStreamParameters=c,this._appData=d??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(o){this._dataChannel.bufferedAmountLowThreshold=o}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(o){if(n.debug("send()"),this._closed)throw new s.InvalidStateError("closed");this._dataChannel.send(o)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(n.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",o=>{if(this._closed)return;let a=o.error??new Error("unknown DataChannel error");o.error?.errorDetail==="sctp-failure"?n.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",o.error?.sctpCauseCode,o.error.message):n.error('DataChannel "error" event: %o',a),this.safeEmit("error",a)}),this._dataChannel.addEventListener("close",()=>{this._closed||(n.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||n.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};t.DataProducer=i}),iZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataConsumer=void 0;var e=Es(),r=Us(),s=new e.Logger("DataConsumer"),n=class extends r.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:i,dataProducerId:o,dataChannel:a,sctpStreamParameters:c,appData:d}){super(),s.debug("constructor()"),this._id=i,this._dataProducerId=o,this._dataChannel=a,this._sctpStreamParameters=c,this._appData=d??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(i){this._dataChannel.binaryType=i}get appData(){return this._appData}set appData(i){this._appData=i}get observer(){return this._observer}close(){this._closed||(s.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(s.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(s.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",i=>{if(this._closed)return;let o=i.error??new Error("unknown DataChannel error");i.error?.errorDetail==="sctp-failure"?s.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",i.error?.sctpCauseCode,i.error.message):s.error('DataChannel "error" event: %o',o),this.safeEmit("error",o)}),this._dataChannel.addEventListener("close",()=>{this._closed||(s.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",i=>{this._closed||this.safeEmit("message",i.data)})}};t.DataConsumer=n}),oZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=void 0;var e=tZ(),r=Es(),s=Us(),n=jn(),i=uf(),o=Oo(),a=rZ(),c=sZ(),d=nZ(),u=iZ(),l=new r.Logger("Transport"),f=class{consumerOptions;promise;resolve;reject;constructor(m){this.consumerOptions=m,this.promise=new Promise((v,p)=>{this.resolve=v,this.reject=p})}},h=class extends s.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new e.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new s.EnhancedEventEmitter;constructor({direction:m,id:v,iceParameters:p,iceCandidates:x,dtlsParameters:w,sctpParameters:E,iceServers:P,iceTransportPolicy:j,additionalSettings:T,appData:k,handlerFactory:_,getSendExtendedRtpCapabilities:A,recvRtpCapabilities:M,canProduceByKind:V}){super(),l.debug("constructor() [id:%s, direction:%s]",v,m),this._id=v,this._direction=m,this._getSendExtendedRtpCapabilities=A,this._recvRtpCapabilities=M,this._canProduceByKind=V,this._maxSctpMessageSize=E?.maxMessageSize;let Y=i.clone(T)??{};delete Y.iceServers,delete Y.iceTransportPolicy,delete Y.bundlePolicy,delete Y.rtcpMuxPolicy,this._handler=_.factory({direction:m,iceParameters:p,iceCandidates:x,dtlsParameters:w,sctpParameters:E,iceServers:P,iceTransportPolicy:j,additionalSettings:Y,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=k??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(m){this._appData=m}get observer(){return this._observer}close(){if(!this._closed){l.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let m of this._producers.values())m.transportClosed();this._producers.clear();for(let m of this._consumers.values())m.transportClosed();this._consumers.clear();for(let m of this._dataProducers.values())m.transportClosed();this._dataProducers.clear();for(let m of this._dataConsumers.values())m.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new n.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:m}){if(l.debug("restartIce()"),this._closed)throw new n.InvalidStateError("closed");if(!m)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(m),"transport.restartIce()")}async updateIceServers({iceServers:m}={}){if(l.debug("updateIceServers()"),this._closed)throw new n.InvalidStateError("closed");if(!Array.isArray(m))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(m),"transport.updateIceServers()")}async produce({track:m,streamId:v,encodings:p,codecOptions:x,headerExtensionOptions:w,codec:E,stopTracks:P=!0,disableTrackOnPause:j=!0,zeroRtpOnPause:T=!1,onRtpSender:k,appData:_={}}={}){if(l.debug("produce() [track:%o]",m),this._closed)throw new n.InvalidStateError("closed");if(m){if(this._direction!=="send")throw new n.UnsupportedError("not a sending Transport");if(this._canProduceByKind[m.kind]){if(m.readyState==="ended")throw new n.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(_&&typeof _!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError(`cannot produce ${m.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let A;if(p&&!Array.isArray(p))throw TypeError("encodings must be an array");p?.length===0?A=void 0:p&&(A=p.map(H=>{let F={active:!0};return H.active===!1&&(F.active=!1),typeof H.dtx=="boolean"&&(F.dtx=H.dtx),typeof H.scalabilityMode=="string"&&(F.scalabilityMode=H.scalabilityMode),typeof H.scaleResolutionDownBy=="number"&&(F.scaleResolutionDownBy=H.scaleResolutionDownBy),typeof H.maxBitrate=="number"&&(F.maxBitrate=H.maxBitrate),typeof H.maxFramerate=="number"&&(F.maxFramerate=H.maxFramerate),typeof H.adaptivePtime=="boolean"&&(F.adaptivePtime=H.adaptivePtime),typeof H.priority=="string"&&(F.priority=H.priority),typeof H.networkPriority=="string"&&(F.networkPriority=H.networkPriority),F}));let{localId:M,rtpParameters:V,rtpSender:Y}=await this._handler.send({track:m,streamId:v,encodings:A,codecOptions:x,headerExtensionOptions:w,codec:E,onRtpSender:k});try{o.validateAndNormalizeRtpParameters(V);let{id:H}=await new Promise((K,I)=>{this.safeEmit("produce",{kind:m.kind,rtpParameters:V,appData:_},K,I)}),F=new a.Producer({id:H,localId:M,rtpSender:Y,track:m,rtpParameters:V,stopTracks:P,disableTrackOnPause:j,zeroRtpOnPause:T,appData:_});return this._producers.set(F.id,F),this.handleProducer(F),this._observer.safeEmit("newproducer",F),F}catch(H){throw this._handler.stopSending(M).catch(()=>{}),H}},"transport.produce()").catch(A=>{if(P)try{m.stop()}catch{}throw A})}async consume({id:m,producerId:v,kind:p,rtpParameters:x,streamId:w,onRtpReceiver:E,appData:P={}}){if(l.debug("consume()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="recv")throw new n.UnsupportedError("not a receiving Transport");if(typeof m!="string")throw new TypeError("missing id");if(typeof v!="string")throw new TypeError("missing producerId");if(p!=="audio"&&p!=="video")throw new TypeError(`invalid kind '${p}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(P&&typeof P!="object")throw new TypeError("if given, appData must be an object");let j=i.clone(x);if(!o.canReceive(j,this._recvRtpCapabilities))throw new n.UnsupportedError("cannot consume this Producer");let T=new f({id:m,producerId:v,kind:p,rtpParameters:j,streamId:w,onRtpReceiver:E,appData:P});return this._pendingConsumerTasks.push(T),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),T.promise}async produceData({ordered:m=!0,maxPacketLifeTime:v,maxRetransmits:p,label:x="",protocol:w="",appData:E={}}={}){if(l.debug("produceData()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="send")throw new n.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(E&&typeof E!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError("SCTP not enabled by remote Transport");return(v||p)&&(m=!1),this._awaitQueue.push(async()=>{let{dataChannel:P,sctpStreamParameters:j}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:m,maxPacketLifeTime:v,maxRetransmits:p,label:x,protocol:w}});o.validateAndNormalizeSctpStreamParameters(j);let{id:T}=await new Promise((_,A)=>{this.safeEmit("producedata",{sctpStreamParameters:j,label:x,protocol:w,appData:E},_,A)}),k=new d.DataProducer({id:T,dataChannel:P,sctpStreamParameters:j,appData:E});return this._dataProducers.set(k.id,k),this.handleDataProducer(k),this._observer.safeEmit("newdataproducer",k),k},"transport.produceData()")}async consumeData({id:m,dataProducerId:v,sctpStreamParameters:p,label:x="",protocol:w="",appData:E={}}){if(l.debug("consumeData()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="recv")throw new n.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof m!="string")throw new TypeError("missing id");if(typeof v!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(E&&typeof E!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError("SCTP not enabled by remote Transport");let P=i.clone(p);return o.validateAndNormalizeSctpStreamParameters(P),this._awaitQueue.push(async()=>{let{dataChannel:j}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:P,label:x,protocol:w}),T=new u.DataConsumer({id:m,dataProducerId:v,dataChannel:j,sctpStreamParameters:P,appData:E});return this._dataConsumers.set(T.id,T),this.handleDataConsumer(T),this._observer.safeEmit("newdataconsumer",T),T},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){l.debug("createPendingConsumers() | there is no Consumer to be created");return}let m=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let v,p=[];for(let x of m){let{id:w,kind:E,rtpParameters:P,streamId:j,onRtpReceiver:T}=x.consumerOptions;p.push({trackId:w,kind:E,rtpParameters:P,streamId:j,onRtpReceiver:T})}try{let x=await this._handler.receive(p);for(let w=0;w<x.length;++w){let E=m[w],P=x[w],{id:j,producerId:T,kind:k,rtpParameters:_,appData:A}=E.consumerOptions,{localId:M,rtpReceiver:V,track:Y}=P,H=new c.Consumer({id:j,localId:M,producerId:T,rtpReceiver:V,track:Y,rtpParameters:_,appData:A});this._consumers.set(H.id,H),this.handleConsumer(H),!this._probatorConsumerCreated&&!v&&k==="video"&&(v=H),this._observer.safeEmit("newconsumer",H),E.resolve(H)}}catch(x){for(let w of m)w.reject(x)}if(v)try{let x=o.generateProbatorRtpParameters(v.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:x}]),l.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(x){l.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",x)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){l.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let m=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let v=m.map(p=>p.localId);await this._handler.pauseReceiving(v)}catch(v){l.error("pausePendingConsumers() | failed to pause Consumers:",v)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){l.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let m=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let v=m.map(p=>p.localId);await this._handler.resumeReceiving(v)}catch(v){l.error("resumePendingConsumers() | failed to resume Consumers:",v)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){l.debug("closePendingConsumers() | there is no Consumer to be closed");return}let m=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(m.map(v=>v.localId))}catch(v){l.error("closePendingConsumers() | failed to close Consumers:",v)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let m=this._handler;m.on("@connect",({dtlsParameters:v},p,x)=>{if(this._closed){x(new n.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:v},p,x)}),m.on("@icegatheringstatechange",v=>{v!==this._iceGatheringState&&(l.debug("ICE gathering state changed to %s",v),this._iceGatheringState=v,this._closed||this.safeEmit("icegatheringstatechange",v))}),m.on("@icecandidateerror",v=>{l.warn(`ICE candidate error [url:${v.url}, localAddress:${v.address}, localPort:${v.port}]: ${v.errorCode} "${v.errorText}"`),this.safeEmit("icecandidateerror",v)}),m.on("@connectionstatechange",v=>{v!==this._connectionState&&(l.debug("connection state changed to %s",v),this._connectionState=v,this._closed||this.safeEmit("connectionstatechange",v))})}handleProducer(m){m.on("@close",()=>{this._producers.delete(m.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(m.localId),"producer @close event").catch(v=>l.warn("producer.close() failed:%o",v))}),m.on("@pause",(v,p)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(m.localId),"producer @pause event").then(v).catch(p)}),m.on("@resume",(v,p)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(m.localId),"producer @resume event").then(v).catch(p)}),m.on("@replacetrack",(v,p,x)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(m.localId,v),"producer @replacetrack event").then(p).catch(x)}),m.on("@setmaxspatiallayer",(v,p,x)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(m.localId,v),"producer @setmaxspatiallayer event").then(p).catch(x)}),m.on("@setrtpencodingparameters",(v,p,x)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(m.localId,v),"producer @setrtpencodingparameters event").then(p).catch(x)}),m.on("@getstats",(v,p)=>{if(this._closed)return p(new n.InvalidStateError("closed"));this._handler.getSenderStats(m.localId).then(v).catch(p)})}handleConsumer(m){m.on("@close",()=>{this._consumers.delete(m.id),this._pendingPauseConsumers.delete(m.id),this._pendingResumeConsumers.delete(m.id),!this._closed&&(this._pendingCloseConsumers.set(m.id,m),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),m.on("@pause",()=>{this._pendingResumeConsumers.has(m.id)&&this._pendingResumeConsumers.delete(m.id),this._pendingPauseConsumers.set(m.id,m),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),m.on("@resume",()=>{this._pendingPauseConsumers.has(m.id)&&this._pendingPauseConsumers.delete(m.id),this._pendingResumeConsumers.set(m.id,m),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),m.on("@getstats",(v,p)=>{if(this._closed)return p(new n.InvalidStateError("closed"));this._handler.getReceiverStats(m.localId).then(v).catch(p)})}handleDataProducer(m){m.on("@close",()=>{this._dataProducers.delete(m.id)})}handleDataConsumer(m){m.on("@close",()=>{this._dataConsumers.delete(m.id)})}};t.Transport=h}),aA=et((t,e)=>{"use strict";var r=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var n="candidate:%s %d %s %d %s %d typ %s";return n+=s.raddr!=null?" raddr %s rport %d":"%v%v",n+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(n+=" generation %d"),n+=s["network-id"]!=null?" network-id %d":"%v",n+=s["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var n="ssrc:%d";return s.attribute!=null&&(n+=" %s",s.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var n="mediaclk:";return n+=s.id!=null?"id=%s %s":"%v%s",n+=s.mediaClockValue!=null?"=%s":"",n+=s.rateNumerator!=null?" rate=%s":"",n+=s.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(r).forEach(function(s){var n=r[s];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})})}),aZ=et(t=>{"use strict";var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,c,d,u){if(u&&!d)c[u]=e(a[1]);else for(var l=0;l<d.length;l+=1)a[l+1]!=null&&(c[d[l]]=e(a[l+1]))},s=function(a,c,d){var u=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:u&&!c[a.name]&&(c[a.name]={});var l=a.push?{}:u?c[a.name]:c;r(d.match(a.reg),l,a.names,a.name),a.push&&c[a.push].push(l)},n=aA(),i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},d=[],u=c;return a.split(/(\r\n|\r|\n)/).filter(i).forEach(function(l){var f=l[0],h=l.slice(2);f==="m"&&(d.push({rtp:[],fmtp:[]}),u=d[d.length-1]);for(var m=0;m<(n[f]||[]).length;m+=1){var v=n[f][m];if(v.reg.test(h))return s(v,u,h)}}),c.media=d,c};var o=function(a,c){var d=c.split(/=(.+)/,2);return d.length===2?a[d[0]]=e(d[1]):d.length===1&&c.length>1&&(a[d[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],d=a.split(" ").map(e),u=0;u<d.length;u+=3)c.push({component:d[u],ip:d[u+1],port:d[u+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(d){var u,l=!1;return d[0]!=="~"?u=e(d):(u=e(d.substring(1,d.length)),l=!0),{scid:u,paused:l}})})}}),cZ=et((t,e)=>{"use strict";var r=aA(),s=/%[sdv%]/g,n=function(c){var d=1,u=arguments,l=u.length;return c.replace(s,function(f){if(d>=l)return f;var h=u[d];switch(d+=1,f){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(c,d,u){var l=d.format instanceof Function?d.format(d.push?u:u[d.name]):d.format,f=[c+"="+l];if(d.names)for(var h=0;h<d.names.length;h+=1){var m=d.names[h];d.name?f.push(u[d.name][m]):f.push(u[d.names[h]])}else f.push(u[d.name]);return n.apply(null,f)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];e.exports=function(c,d){d=d||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var u=d.outerOrder||o,l=d.innerOrder||a,f=[];return u.forEach(function(h){r[h].forEach(function(m){m.name in c&&c[m.name]!=null?f.push(i(h,m,c)):m.push in c&&c[m.push]!=null&&c[m.push].forEach(function(v){f.push(i(h,m,v))})})}),c.media.forEach(function(h){f.push(i("m",r.m[0],h)),l.forEach(function(m){r[m].forEach(function(v){v.name in h&&h[v.name]!=null?f.push(i(m,v,h)):v.push in h&&h[v.push]!=null&&h[v.push].forEach(function(p){f.push(i(m,v,p))})})})}),f.join(`\r
144
+ `)+`\r
145
+ `}}),Za=et(t=>{"use strict";var e=aZ(),r=cZ(),s=aA();t.grammar=s,t.write=r,t.parse=e.parse,t.parseParams=e.parseParams,t.parseFmtpConfig=e.parseFmtpConfig,t.parsePayloads=e.parsePayloads,t.parseRemoteCandidates=e.parseRemoteCandidates,t.parseImageAttributes=e.parseImageAttributes,t.parseSimulcastStreamList=e.parseSimulcastStreamList}),ff=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parse=r;var e=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function r(s){let n=e.exec(s??"");return n?{spatialLayers:Number(n[1]),temporalLayers:Number(n[2])}:{spatialLayers:1,temporalLayers:1}}}),dZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OfferMediaSection=t.AnswerMediaSection=t.MediaSection=void 0;var e=Za(),r=uf(),s=class{_mediaObject;constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},a&&this.setIceParameters(a),c){this._mediaObject.candidates=[];for(let u of c){let l={foundation:u.foundation,component:1,ip:u.address??u.ip,port:u.port,priority:u.priority,transport:u.protocol,type:u.type};u.tcpType&&(l.tcptype=u.tcpType),this._mediaObject.candidates.push(l)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}d&&this.setDtlsRole(d.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(a){this._mediaObject.iceUfrag=a.usernameFragment,this._mediaObject.icePwd=a.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};t.MediaSection=s;var n=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,offerMediaObject:f,offerRtpParameters:h,answerRtpParameters:m,codecOptions:v}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(f.mid),this._mediaObject.type=f.type,this._mediaObject.protocol=f.protocol,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),f.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let p of m.codecs){let x={payload:p.payloadType,codec:o(p),rate:p.clockRate};p.channels>1&&(x.encoding=p.channels),this._mediaObject.rtp.push(x);let w=r.clone(p.parameters)??{},E=r.clone(p.rtcpFeedback)??[];if(v){let{opusStereo:j,opusFec:T,opusDtx:k,opusMaxPlaybackRate:_,opusMaxAverageBitrate:A,opusPtime:M,opusNack:V,videoGoogleStartBitrate:Y,videoGoogleMaxBitrate:H,videoGoogleMinBitrate:F}=v,K=h.codecs.find(I=>I.payloadType===p.payloadType);switch(p.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{j!==void 0&&(K.parameters["sprop-stereo"]=j?1:0,w.stereo=j?1:0),T!==void 0&&(K.parameters.useinbandfec=T?1:0,w.useinbandfec=T?1:0),k!==void 0&&(K.parameters.usedtx=k?1:0,w.usedtx=k?1:0),_!==void 0&&(w.maxplaybackrate=_),A!==void 0&&(w.maxaveragebitrate=A),M!==void 0&&(K.parameters.ptime=M,w.ptime=M),V||(K.rtcpFeedback=K.rtcpFeedback.filter(I=>I.type!=="nack"||I.parameter),E=E.filter(I=>I.type!=="nack"||I.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{Y!==void 0&&(w["x-google-start-bitrate"]=Y),H!==void 0&&(w["x-google-max-bitrate"]=H),F!==void 0&&(w["x-google-min-bitrate"]=F);break}}}let P={payload:p.payloadType,config:""};for(let j of Object.keys(w))P.config&&(P.config+=";"),P.config+=`${j}=${w[j]}`;P.config&&this._mediaObject.fmtp.push(P);for(let j of E)this._mediaObject.rtcpFb.push({payload:p.payloadType,type:j.type,subtype:j.parameter})}this._mediaObject.payloads=m.codecs.map(p=>p.payloadType).join(" "),this._mediaObject.ext=[];for(let p of m.headerExtensions)(f.ext??[]).some(x=>x.uri===p.uri)&&this._mediaObject.ext.push({uri:p.uri,value:p.id});if(f.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),f.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:f.simulcast.list1},this._mediaObject.rids=[];for(let p of f.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}else if(f.simulcast_03){this._mediaObject.simulcast_03={value:f.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let p of f.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof f.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize):f.sctpmap&&(this._mediaObject.payloads=String(u.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:u.port,maxMessageSize:u.maxMessageSize});break}}}setDtlsRole(a){switch(a){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(a){if(!this._mediaObject.simulcast?.list1)return;let c={};for(let l of a)l.rid&&(c[l.rid]=l);let d=this._mediaObject.simulcast.list1,u=e.parseSimulcastStreamList(d);for(let l of u)for(let f of l)f.paused=!c[f.scid]?.active;this._mediaObject.simulcast.list1=u.map(l=>l.map(f=>`${f.paused?"~":""}${f.scid}`).join(",")).join(";")}};t.AnswerMediaSection=n;var i=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,mid:f,kind:h,offerRtpParameters:m,streamId:v,trackId:p}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(f),this._mediaObject.type=h,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},u?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",h){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:v,appdata:p}];for(let P of m.codecs){let j={payload:P.payloadType,codec:o(P),rate:P.clockRate};P.channels>1&&(j.encoding=P.channels),this._mediaObject.rtp.push(j);let T={payload:P.payloadType,config:""};for(let k of Object.keys(P.parameters??{}))T.config&&(T.config+=";"),T.config+=`${k}=${P.parameters[k]}`;T.config&&this._mediaObject.fmtp.push(T);for(let k of P.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:P.payloadType,type:k.type,subtype:k.parameter})}this._mediaObject.payloads=m.codecs.map(P=>P.payloadType).join(" "),this._mediaObject.ext=[];for(let P of m.headerExtensions)this._mediaObject.ext.push({uri:P.uri,value:P.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let x=m.encodings[0],w=x.ssrc,E=x.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],w&&m.rtcp.cname&&this._mediaObject.ssrcs.push({id:w,attribute:"cname",value:m.rtcp.cname}),E&&(m.rtcp.cname&&this._mediaObject.ssrcs.push({id:E,attribute:"cname",value:m.rtcp.cname}),w&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${w} ${E}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize;break}}}setDtlsRole(a){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};t.OfferMediaSection=i;function o(a){let c=new RegExp("^(audio|video)/(.+)","i").exec(a.mimeType);if(!c)throw new TypeError("invalid codec.mimeType");return c[2]}}),xm=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteSdp=void 0;var e=Za(),r=Es(),s=dZ(),n=wM(),i=["av1","h264"],o=new r.Logger("RemoteSdp"),a=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:c,iceCandidates:d,dtlsParameters:u,sctpParameters:l,plainRtpParameters:f}){if(this._iceParameters=c,this._iceCandidates=d,this._dtlsParameters=u,this._sctpParameters=l,this._plainRtpParameters=f,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${n.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",c?.iceLite&&(this._sdpObject.icelite="ice-lite"),u){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let h=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:u.fingerprints[h-1].algorithm,hash:u.fingerprints[h-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}f&&(this._sdpObject.origin.address=f.ip,this._sdpObject.origin.ipVer=f.ipVersion)}updateIceParameters(c){o.debug("updateIceParameters() [iceParameters:%o]",c),this._iceParameters=c,this._sdpObject.icelite=c.iceLite?"ice-lite":void 0;for(let d of this._mediaSections)d.setIceParameters(c)}updateDtlsRole(c){o.debug("updateDtlsRole() [role:%s]",c),this._dtlsParameters.role=c;for(let d of this._mediaSections)d.setDtlsRole(c)}setSessionExtmapAllowMixed(){o.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let c=0;c<this._mediaSections.length;++c){let d=this._mediaSections[c];if(d.closed)return{idx:c,reuseMid:d.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:c,reuseMid:d,offerRtpParameters:u,answerRtpParameters:l,codecOptions:f}){let h=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c,offerRtpParameters:u,answerRtpParameters:l,codecOptions:f}),m=h.getObject();m.rtp.find(v=>i.includes(v.codec.toLowerCase()))||(m.ext=m.ext?.filter(v=>v.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),d?this.replaceMediaSection(h,d):this._midToIndex.has(h.mid)?this.replaceMediaSection(h):this.addMediaSection(h)}receive({mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:f}){this.setSessionExtmapAllowMixed();let h=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:f}),m=this._mediaSections.find(v=>v.closed&&v.getObject().type===d);m?this.replaceMediaSection(h,m.mid):this.addMediaSection(h)}pauseMediaSection(c){this.findMediaSection(c).pause()}resumeSendingMediaSection(c){this.findMediaSection(c).resume()}resumeReceivingMediaSection(c){this.findMediaSection(c).resume()}disableMediaSection(c){this.findMediaSection(c).disable()}closeMediaSection(c){let d=this.findMediaSection(c);return c===this._firstMid?(o.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",c),this.disableMediaSection(c),!1):(d.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(c,d){let u=this.findMediaSection(c);u.muxSimulcastStreams(d),this.replaceMediaSection(u)}sendSctpAssociation({offerMediaObject:c}){let d=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c});this.addMediaSection(d)}receiveSctpAssociation(){let c=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(c)}getSdp(){return this._sdpObject.origin.sessionVersion++,e.write(this._sdpObject)}addMediaSection(c){this._firstMid||(this._firstMid=c.mid),this._mediaSections.push(c),this._midToIndex.set(c.mid,this._mediaSections.length-1),this._sdpObject.media.push(c.getObject()),this.regenerateBundleMids()}replaceMediaSection(c,d){if(typeof d=="string"){let u=this._midToIndex.get(d);if(u===void 0)throw new Error(`no media section found for reuseMid '${d}'`);let l=this._mediaSections[u];this._mediaSections[u]=c,this._midToIndex.delete(l.mid),this._midToIndex.set(c.mid,u),this._sdpObject.media[u]=c.getObject(),this.regenerateBundleMids()}else{let u=this._midToIndex.get(c.mid);if(u===void 0)throw new Error(`no media section found with mid '${c.mid}'`);this._mediaSections[u]=c,this._sdpObject.media[u]=c.getObject()}}findMediaSection(c){let d=this._midToIndex.get(c);if(d===void 0)throw new Error(`no media section found with mid '${c}'`);return this._mediaSections[d]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(c=>!c.closed).map(c=>c.mid).join(" "))}};t.RemoteSdp=a}),bm=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractRtpCapabilities=r,t.extractDtlsParameters=s,t.getCname=n,t.applyCodecParameters=i,t.addHeaderExtension=o;var e=Za();function r({sdpObject:a}){let c=new Map,d=new Map;for(let u of a.media){let l=u.type;switch(l){case"audio":case"video":break;default:continue}for(let f of u.rtp){let h={kind:l,mimeType:`${l}/${f.codec}`,preferredPayloadType:f.payload,clockRate:f.rate,channels:f.encoding,parameters:{},rtcpFeedback:[]};c.set(h.preferredPayloadType,h)}for(let f of u.fmtp??[]){let h=e.parseParams(f.config),m=c.get(f.payload);m&&(h?.hasOwnProperty("profile-level-id")&&(h["profile-level-id"]=String(h["profile-level-id"])),m.parameters=h)}for(let f of u.rtcpFb??[]){let h={type:f.type,parameter:f.subtype};if(h.parameter||delete h.parameter,f.payload!=="*"){let m=c.get(Number(f.payload));if(!m)continue;m.rtcpFeedback.push(h)}else for(let m of c.values())m.kind===l&&!/.+\/rtx$/i.test(m.mimeType)&&m.rtcpFeedback.push(h)}for(let f of u.ext??[]){if(f["encrypt-uri"])continue;let h={kind:l,uri:f.uri,preferredId:f.value};d.set(h.preferredId,h)}}return{codecs:Array.from(c.values()),headerExtensions:Array.from(d.values())}}function s({sdpObject:a}){let c=a.setup,d=a.fingerprint;if(!c||!d){let l=(a.media??[]).find(f=>f.port!==0);l&&(c=c??l.setup,d=d??l.fingerprint)}if(c){if(!d)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let u;switch(c){case"active":{u="client";break}case"passive":{u="server";break}case"actpass":{u="auto";break}}return{role:u,fingerprints:[{algorithm:d.type,value:d.hash}]}}function n({offerMediaObject:a}){let c=(a.ssrcs??[]).find(d=>d.attribute==="cname");return c?c.value:""}function i({offerRtpParameters:a,answerMediaObject:c}){for(let d of a.codecs){let u=d.mimeType.toLowerCase();if(u!=="audio/opus"||!(c.rtp??[]).find(h=>h.payload===d.payloadType))continue;c.fmtp=c.fmtp??[];let l=c.fmtp.find(h=>h.payload===d.payloadType);l||(l={payload:d.payloadType,config:""},c.fmtp.push(l));let f=e.parseParams(l.config);if(u==="audio/opus"){let h=d.parameters?.["sprop-stereo"];h!==void 0&&(f.stereo=Number(h)?1:0)}l.config="";for(let h of Object.keys(f))l.config&&(l.config+=";"),l.config+=`${h}=${f[h]}`}}function o({offerMediaObject:a,headerExtensionUri:c,headerExtensionId:d}){a.ext||(a.ext=[]),a.ext.push({uri:c,value:d})}}),wm=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRtpEncodings=e,t.addLegacySimulcast=r;function e({offerMediaObject:s,codecs:n}){let i=new Set;for(let c of s.ssrcs??[]){let d=c.id;d&&i.add(d)}if(i.size===0)throw new Error("no a=ssrc lines found");let o=new Map;for(let c of s.ssrcGroups??[]){if(c.semantics!=="FID")continue;let d=c.ssrcs.split(/\s+/),u=Number(d[0]),l=Number(d[1]);i.has(u)&&(i.delete(u),i.delete(l),o.set(u,l))}for(let c of i)o.set(c,void 0);let a=[];for(let[c,d]of o){let u={ssrc:c};d&&n.length>1&&(u.rtx={ssrc:d}),a.push(u)}return a}function r({offerMediaObject:s,numStreams:n}){if(n<=1)throw new TypeError("numStreams must be greater than 1");let i=(s.ssrcs??[]).find(m=>m.attribute==="msid");if(!i)throw new Error("a=ssrc line with msid information not found");let[o,a]=i.value.split(" "),c=Number(i.id),d;(s.ssrcGroups??[]).some(m=>{if(m.semantics!=="FID")return!1;let v=m.ssrcs.split(/\s+/);return Number(v[0])===c?(d=Number(v[1]),!0):!1});let u=(s.ssrcs??[]).find(m=>m.attribute==="cname");if(!u)throw new Error("a=ssrc line with cname information not found");let l=u.value,f=[],h=[];for(let m=0;m<n;++m)f.push(c+m),d&&h.push(d+m);s.ssrcGroups=[],s.ssrcs=[],s.ssrcGroups.push({semantics:"SIM",ssrcs:f.join(" ")});for(let m of f)s.ssrcs.push({id:m,attribute:"cname",value:l}),s.ssrcs.push({id:m,attribute:"msid",value:`${o} ${a}`});for(let m=0;m<h.length;++m){let v=f[m],p=h[m];s.ssrcs.push({id:p,attribute:"cname",value:l}),s.ssrcs.push({id:p,attribute:"msid",value:`${o} ${a}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${v} ${p}`})}}}),vm=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addNackSupportForOpus=e,t.addHeaderExtensionSupport=r,t.getMsidStreamIdAndTrackId=s;function e(n){for(let i of n.codecs??[])(i.mimeType.toLowerCase()==="audio/opus"||i.mimeType.toLowerCase()==="audio/multiopus")&&!i.rtcpFeedback?.some(o=>o.type==="nack"&&!o.parameter)&&(i.rtcpFeedback||(i.rtcpFeedback=[]),i.rtcpFeedback.push({type:"nack"}))}function r(n,i){let o,a=n.headerExtensions?.find(d=>d.uri===i.uri);if(a){if(a.kind===i.kind)return;o=a.preferredId}if(n.headerExtensions||(n.headerExtensions=[]),o===void 0){o=1;let d=new Set(n.headerExtensions.map(u=>u.preferredId));for(;d.has(o);)++o}let c={kind:i.kind,uri:i.uri,preferredId:o,preferredEncrypt:!1,direction:i.direction};n.headerExtensions.push(c)}function s(n){if(!n||typeof n!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[i,o]=n.trim().split(/\s+/);return i?{msidStreamId:i,msidTrackId:o}:{msidStreamId:void 0,msidTrackId:void 0}}}),lZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome111=void 0;var e=Za(),r=Us(),s=Es(),n=Oo(),i=jn(),o=ff(),a=xm(),c=bm(),d=wm(),u=vm(),l=new s.Logger("Chrome111"),f="Chrome111",h={OS:65535,MIS:65535},m=class u1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:f,factory:p=>new u1(p),getNativeRtpCapabilities:async({direction:p})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",p);let x=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{x.addTransceiver("audio",{direction:p}),x.addTransceiver("video",{direction:p,sendEncodings:[{scalabilityMode:"L3T3"}]});let w=await x.createOffer();try{x.close()}catch{}x=void 0;let E=e.parse(w.sdp);return u1.getLocalRtpCapabilities(E)}catch(w){try{x?.close()}catch{}throw x=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:h})}}static getLocalRtpCapabilities(p,x=[]){let w=c.extractRtpCapabilities({sdpObject:p});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let E of x)u.addHeaderExtensionSupport(w,E);return w}constructor({direction:p,iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P,iceServers:j,iceTransportPolicy:T,additionalSettings:k,getSendExtendedRtpCapabilities:_}){super(),l.debug("constructor()"),this._direction=p,this._remoteSdp=new a.RemoteSdp({iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P}),this._getSendExtendedRtpCapabilities=_,E.role&&E.role!=="auto"&&(this._forcedLocalDtlsRole=E.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:T??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return f}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(p){this.assertNotClosed(),l.debug("updateIceServers()");let x=this._pc.getConfiguration();x.iceServers=p,this._pc.setConfiguration(x)}async restartIce(p){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(p),!!this._transportReady)if(this._direction==="send"){let x=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",x),await this._pc.setLocalDescription(x);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:p,streamId:x,encodings:w,codecOptions:E,headerExtensionOptions:P,codec:j,onRtpSender:T}){if(this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",p.kind,p.id,x),w&&w.length>1){let D=1;for(let O of w){let W=O.scalabilityMode?(0,o.parse)(O.scalabilityMode).temporalLayers:3;W>D&&(D=W)}w.forEach((O,W)=>{O.rid=`r${W}`,O.scalabilityMode=`L1T${D}`})}let k=this._remoteSdp.getNextMediaSectionIdx(),_=this._pc.addTransceiver(p,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});T&&T(_.sender);let A=await this._pc.createOffer(),M=e.parse(A.sdp);M.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let V=[];V.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:p.kind,direction:"sendonly"});let Y=u1.getLocalRtpCapabilities(M,V),H=this._getSendExtendedRtpCapabilities(Y),F=n.getSendingRtpParameters(p.kind,H);F.codecs=n.reduceCodecs(F.codecs,j);let K=n.getSendingRemoteRtpParameters(p.kind,H);if(K.codecs=n.reduceCodecs(K.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:M}),P?.absCaptureTime){let D=M.media[k.idx];c.addHeaderExtension({offerMediaObject:D,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:K.headerExtensions.find(O=>O.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),A={type:"offer",sdp:e.write(M)}}l.debug("send() | calling pc.setLocalDescription() [offer:%o]",A),await this._pc.setLocalDescription(A);let I=_.mid;F.mid=I,M=e.parse(this._pc.localDescription.sdp);let G=M.media[k.idx];if(F.rtcp.cname=c.getCname({offerMediaObject:G}),F.msid=`${x??this._sendStream.id} ${p.id}`,!w)F.encodings=d.getRtpEncodings({offerMediaObject:G,codecs:F.codecs});else if(w.length===1){let D=d.getRtpEncodings({offerMediaObject:G,codecs:F.codecs});Object.assign(D[0],w[0]),F.encodings=D}else F.encodings=w;this._remoteSdp.send({offerMediaObject:G,reuseMid:k.reuseMid,offerRtpParameters:F,answerRtpParameters:K,codecOptions:E});let se={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",se),await this._pc.setRemoteDescription(se),this._mapMidTransceiver.set(I,_),{localId:I,rtpParameters:F,rtpSender:_.sender}}async stopSending(p){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",p),this._closed)return;let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");if(x.sender.replaceTrack(null),this._pc.removeTrack(x.sender),this._remoteSdp.closeMediaSection(x.mid))try{x.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E),this._mapMidTransceiver.delete(p)}async pauseSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="inactive",this._remoteSdp.pauseMediaSection(p);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async resumeSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(this._remoteSdp.resumeSendingMediaSection(p),!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async replaceTrack(p,x){this.assertNotClosed(),this.assertSendDirection(),x?l.debug("replaceTrack() [localId:%s, track.id:%s]",p,x.id):l.debug("replaceTrack() [localId:%s, no track]",p);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(x)}async setMaxSpatialLayer(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{k<=x?T.active=!0:T.active=!1}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{E.encodings[k]={...T,...x}}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(p){this.assertNotClosed(),this.assertSendDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.sender.getStats()}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this.assertSendDirection();let x={negotiated:!0,id:this._nextSendSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,protocol:p.protocol};l.debug("sendDataChannel() [options:%o]",x);let w=this._pc.createDataChannel(p.label,x);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%h.MIS,!this._hasDataChannelMediaSection){let P=await this._pc.createOffer(),j=e.parse(P.sdp),T=j.media.find(_=>_.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P),this._remoteSdp.sendSctpAssociation({offerMediaObject:T});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let E={streamId:x.id,ordered:x.ordered,maxPacketLifeTime:x.maxPacketLifeTime,maxRetransmits:x.maxRetransmits};return{dataChannel:w,sctpStreamParameters:E}}async receive(p){this.assertNotClosed(),this.assertRecvDirection();let x=[],w=new Map;for(let T of p){let{trackId:k,kind:_,rtpParameters:A,streamId:M}=T;l.debug("receive() [trackId:%s, kind:%s]",k,_);let V=A.mid??String(this._mapMidTransceiver.size);w.set(k,V);let{msidStreamId:Y}=u.getMsidStreamIdAndTrackId(A.msid);this._remoteSdp.receive({mid:V,kind:_,offerRtpParameters:A,streamId:M??Y??A.rtcp?.cname??"-",trackId:k})}let E={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",E),await this._pc.setRemoteDescription(E);for(let T of p){let{trackId:k,onRtpReceiver:_}=T;if(_){let A=w.get(k),M=this._pc.getTransceivers().find(V=>V.mid===A);if(!M)throw new Error("transceiver not found");_(M.receiver)}}let P=await this._pc.createAnswer(),j=e.parse(P.sdp);for(let T of p){let{trackId:k,rtpParameters:_}=T,A=w.get(k),M=j.media.find(V=>String(V.mid)===A);c.applyCodecParameters({offerRtpParameters:_,answerMediaObject:M})}P={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",P),await this._pc.setLocalDescription(P);for(let T of p){let{trackId:k}=T,_=w.get(k),A=this._pc.getTransceivers().find(M=>M.mid===_);if(A)this._mapMidTransceiver.set(_,A),x.push({localId:_,track:A.receiver.track,rtpReceiver:A.receiver});else throw new Error("new RTCRtpTransceiver not found")}return x}async stopReceiving(p){if(this.assertRecvDirection(),this._closed)return;for(let E of p){l.debug("stopReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(P.mid)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let E of p)this._mapMidTransceiver.delete(E)}async pauseReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("pauseReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="inactive",this._remoteSdp.pauseMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("resumeReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(p){this.assertNotClosed(),this.assertRecvDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.receiver.getStats()}async receiveDataChannel({maxMessageSize:p,sctpStreamParameters:x,label:w,protocol:E}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k}=x,_={negotiated:!0,id:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k,protocol:E};l.debug("receiveDataChannel() [options:%o]",_);let A=this._pc.createDataChannel(w,_);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let M={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",M),await this._pc.setRemoteDescription(M);let V=await this._pc.createAnswer(),Y=e.parse(V.sdp),H=Y.media.find(F=>F.type==="application");H.maxMessageSize=p,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:Y}),V={type:"answer",sdp:e.write(Y)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",V),await this._pc.setLocalDescription(V),this._hasDataChannelMediaSection=!0}return{dataChannel:A}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:p,localSdpObject:x}){x||(x=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:x});w.role=p,this._remoteSdp.updateDtlsRole(p==="client"?"server":"client"),await new Promise((E,P)=>{this.safeEmit("@connect",{dtlsParameters:w},E,P)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=p=>{this.emit("@icecandidateerror",p)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome111=m}),uZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome74=void 0;var e=Za(),r=Es(),s=Us(),n=Oo(),i=jn(),o=ff(),a=xm(),c=bm(),d=wm(),u=vm(),l=new r.Logger("Chrome74"),f="Chrome74",h={OS:1024,MIS:1024},m=class f1 extends s.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:f,factory:p=>new f1(p),getNativeRtpCapabilities:async({direction:p})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",p);let x=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{x.addTransceiver("audio",{direction:p}),x.addTransceiver("video",{direction:p});let w=await x.createOffer();try{x.close()}catch{}x=void 0;let E=e.parse(w.sdp);return f1.getLocalRtpCapabilities(E)}catch(w){try{x?.close()}catch{}throw x=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:h})}}static getLocalRtpCapabilities(p,x=[]){let w=c.extractRtpCapabilities({sdpObject:p});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let E of x)u.addHeaderExtensionSupport(w,E);return w}constructor({direction:p,iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P,iceServers:j,iceTransportPolicy:T,additionalSettings:k,getSendExtendedRtpCapabilities:_}){super(),l.debug("constructor()"),this._direction=p,this._remoteSdp=new a.RemoteSdp({iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P}),this._getSendExtendedRtpCapabilities=_,E.role&&E.role!=="auto"&&(this._forcedLocalDtlsRole=E.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:T??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return f}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(p){this.assertNotClosed(),l.debug("updateIceServers()");let x=this._pc.getConfiguration();x.iceServers=p,this._pc.setConfiguration(x)}async restartIce(p){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(p),!!this._transportReady)if(this._direction==="send"){let x=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",x),await this._pc.setLocalDescription(x);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:p,streamId:x,encodings:w,codecOptions:E,headerExtensionOptions:P,codec:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",p.kind,p.id,x),w&&w.length>1&&w.forEach((O,W)=>{O.rid=`r${W}`});let T=this._remoteSdp.getNextMediaSectionIdx(),k=this._pc.addTransceiver(p,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w}),_=await this._pc.createOffer(),A=e.parse(_.sdp);A.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let M=[];M.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:p.kind,direction:"sendonly"});let V=f1.getLocalRtpCapabilities(A,M),Y=this._getSendExtendedRtpCapabilities(V),H=n.getSendingRtpParameters(p.kind,Y);H.codecs=n.reduceCodecs(H.codecs,j);let F=n.getSendingRemoteRtpParameters(p.kind,Y);F.codecs=n.reduceCodecs(F.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:A});let K=!1,I=(0,o.parse)((w??[{}])[0].scalabilityMode),G;w?.length===1&&I.spatialLayers>1&&H.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),K=!0,A=e.parse(_.sdp),G=A.media[T.idx],d.addLegacySimulcast({offerMediaObject:G,numStreams:I.spatialLayers}),_={type:"offer",sdp:e.write(A)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",_),P?.absCaptureTime&&(G=A.media[T.idx],c.addHeaderExtension({offerMediaObject:G,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:F.headerExtensions.find(O=>O.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),_={type:"offer",sdp:e.write(A)}),await this._pc.setLocalDescription(_);let se=k.mid;if(H.mid=se,A=e.parse(this._pc.localDescription.sdp),G=A.media[T.idx],H.rtcp.cname=c.getCname({offerMediaObject:G}),H.msid=`${x??this._sendStream.id} ${p.id}`,!w)H.encodings=d.getRtpEncodings({offerMediaObject:G,codecs:H.codecs});else if(w.length===1){let O=d.getRtpEncodings({offerMediaObject:G,codecs:H.codecs});Object.assign(O[0],w[0]),K&&(O=[O[0]]),H.encodings=O}else H.encodings=w;if(H.encodings.length>1&&(H.codecs[0].mimeType.toLowerCase()==="video/vp8"||H.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let O of H.encodings)O.scalabilityMode?O.scalabilityMode=`L1T${I.temporalLayers}`:O.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:G,reuseMid:T.reuseMid,offerRtpParameters:H,answerRtpParameters:F,codecOptions:E});let D={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",D),await this._pc.setRemoteDescription(D),this._mapMidTransceiver.set(se,k),{localId:se,rtpParameters:H,rtpSender:k.sender}}async stopSending(p){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",p),this._closed)return;let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");if(x.sender.replaceTrack(null),this._pc.removeTrack(x.sender),this._remoteSdp.closeMediaSection(x.mid))try{x.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E),this._mapMidTransceiver.delete(p)}async pauseSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="inactive",this._remoteSdp.pauseMediaSection(p);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async resumeSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(this._remoteSdp.resumeSendingMediaSection(p),!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async replaceTrack(p,x){this.assertNotClosed(),this.assertSendDirection(),x?l.debug("replaceTrack() [localId:%s, track.id:%s]",p,x.id):l.debug("replaceTrack() [localId:%s, no track]",p);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(x)}async setMaxSpatialLayer(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{k<=x?T.active=!0:T.active=!1}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{E.encodings[k]={...T,...x}}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(p){this.assertNotClosed(),this.assertSendDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.sender.getStats()}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this.assertSendDirection();let x={negotiated:!0,id:this._nextSendSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,protocol:p.protocol};l.debug("sendDataChannel() [options:%o]",x);let w=this._pc.createDataChannel(p.label,x);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%h.MIS,!this._hasDataChannelMediaSection){let P=await this._pc.createOffer(),j=e.parse(P.sdp),T=j.media.find(_=>_.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P),this._remoteSdp.sendSctpAssociation({offerMediaObject:T});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let E={streamId:x.id,ordered:x.ordered,maxPacketLifeTime:x.maxPacketLifeTime,maxRetransmits:x.maxRetransmits};return{dataChannel:w,sctpStreamParameters:E}}async receive(p){this.assertNotClosed(),this.assertRecvDirection();let x=[],w=new Map;for(let T of p){let{trackId:k,kind:_,rtpParameters:A,streamId:M}=T;l.debug("receive() [trackId:%s, kind:%s]",k,_);let V=A.mid??String(this._mapMidTransceiver.size);w.set(k,V);let{msidStreamId:Y}=u.getMsidStreamIdAndTrackId(A.msid);this._remoteSdp.receive({mid:V,kind:_,offerRtpParameters:A,streamId:M??Y??A.rtcp?.cname??"-",trackId:k})}let E={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",E),await this._pc.setRemoteDescription(E);let P=await this._pc.createAnswer(),j=e.parse(P.sdp);for(let T of p){let{trackId:k,rtpParameters:_}=T,A=w.get(k),M=j.media.find(V=>String(V.mid)===A);c.applyCodecParameters({offerRtpParameters:_,answerMediaObject:M})}P={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",P),await this._pc.setLocalDescription(P);for(let T of p){let{trackId:k}=T,_=w.get(k),A=this._pc.getTransceivers().find(M=>M.mid===_);if(A)this._mapMidTransceiver.set(_,A),x.push({localId:_,track:A.receiver.track,rtpReceiver:A.receiver});else throw new Error("new RTCRtpTransceiver not found")}return x}async stopReceiving(p){if(this.assertRecvDirection(),this._closed)return;for(let E of p){l.debug("stopReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(P.mid)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let E of p)this._mapMidTransceiver.delete(E)}async pauseReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("pauseReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="inactive",this._remoteSdp.pauseMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("resumeReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(p){this.assertNotClosed(),this.assertRecvDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.receiver.getStats()}async receiveDataChannel({maxMessageSize:p,sctpStreamParameters:x,label:w,protocol:E}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k}=x,_={negotiated:!0,id:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k,protocol:E};l.debug("receiveDataChannel() [options:%o]",_);let A=this._pc.createDataChannel(w,_);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let M={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",M),await this._pc.setRemoteDescription(M);let V=await this._pc.createAnswer(),Y=e.parse(V.sdp),H=Y.media.find(F=>F.type==="application");H.maxMessageSize=p,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:Y}),V={type:"answer",sdp:e.write(Y)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",V),await this._pc.setLocalDescription(V),this._hasDataChannelMediaSection=!0}return{dataChannel:A}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:p,localSdpObject:x}){x||(x=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:x});w.role=p,this._remoteSdp.updateDtlsRole(p==="client"?"server":"client"),await new Promise((E,P)=>{this.safeEmit("@connect",{dtlsParameters:w},E,P)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=p=>{this.emit("@icecandidateerror",p)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome74=m}),fZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Firefox120=void 0;var e=Za(),r=Us(),s=Es(),n=jn(),i=Oo(),o=ff(),a=xm(),c=bm(),d=wm(),u=vm(),l=new s.Logger("Firefox120"),f="Firefox120",h={OS:16,MIS:2048},m=class h1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:f,factory:p=>new h1(p),getNativeRtpCapabilities:async({direction:p})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",p);let x=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),w=document.createElement("canvas");w.getContext("2d");let E=w.captureStream().getVideoTracks()[0];try{x.addTransceiver("audio",{direction:p}),x.addTransceiver(E,{direction:p,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let P=await x.createOffer();try{w.remove()}catch{}try{E.stop()}catch{}try{x.close()}catch{}x=void 0;let j=e.parse(P.sdp);return h1.getLocalRtpCapabilities(j)}catch(P){try{w.remove()}catch{}try{E.stop()}catch{}try{x?.close()}catch{}throw x=void 0,P}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:h})}}static getLocalRtpCapabilities(p){let x=c.extractRtpCapabilities({sdpObject:p});return i.validateAndNormalizeRtpCapabilities(x),x}constructor({direction:p,iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P,iceServers:j,iceTransportPolicy:T,additionalSettings:k,getSendExtendedRtpCapabilities:_}){super(),l.debug("constructor()"),this._direction=p,this._remoteSdp=new a.RemoteSdp({iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P}),this._getSendExtendedRtpCapabilities=_,this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:T??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return f}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(p){throw this.assertNotClosed(),new n.UnsupportedError("not supported")}async restartIce(p){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(p),!!this._transportReady)if(this._direction==="send"){let x=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",x),await this._pc.setLocalDescription(x);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:p,streamId:x,encodings:w,codecOptions:E,codec:P,onRtpSender:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",p.kind,p.id,x),w&&w.length>1&&w.forEach((G,se)=>{G.rid=`r${se}`});let T=this._pc.addTransceiver(p,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});j&&j(T.sender);let k=await this._pc.createOffer(),_=e.parse(k.sdp);_.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let A=h1.getLocalRtpCapabilities(_),M=this._getSendExtendedRtpCapabilities(A),V=i.getSendingRtpParameters(p.kind,M);V.codecs=i.reduceCodecs(V.codecs,P);let Y=i.getSendingRemoteRtpParameters(p.kind,M);Y.codecs=i.reduceCodecs(Y.codecs,P),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:_});let H=(0,o.parse)((w??[{}])[0].scalabilityMode);l.debug("send() | calling pc.setLocalDescription() [offer:%o]",k),await this._pc.setLocalDescription(k);let F=T.mid;V.mid=F,_=e.parse(this._pc.localDescription.sdp);let K=_.media[_.media.length-1];if(V.rtcp.cname=c.getCname({offerMediaObject:K}),V.msid=`${x??this._sendStream.id} ${p.id}`,!w)V.encodings=d.getRtpEncodings({offerMediaObject:K,codecs:V.codecs});else if(w.length===1){let G=d.getRtpEncodings({offerMediaObject:K,codecs:V.codecs});Object.assign(G[0],w[0]),V.encodings=G}else V.encodings=w;if(V.encodings.length>1&&(V.codecs[0].mimeType.toLowerCase()==="video/vp8"||V.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let G of V.encodings)G.scalabilityMode?G.scalabilityMode=`L1T${H.temporalLayers}`:G.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:K,offerRtpParameters:V,answerRtpParameters:Y,codecOptions:E});let I={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",I),await this._pc.setRemoteDescription(I),this._mapMidTransceiver.set(F,T),{localId:F,rtpParameters:V,rtpSender:T.sender}}async stopSending(p){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",p),this._closed)return;let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated transceiver not found");x.sender.replaceTrack(null),this._pc.removeTrack(x.sender),this._remoteSdp.disableMediaSection(x.mid);let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E),this._mapMidTransceiver.delete(p)}async pauseSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="inactive",this._remoteSdp.pauseMediaSection(p);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async resumeSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(p);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async replaceTrack(p,x){this.assertNotClosed(),this.assertSendDirection(),x?l.debug("replaceTrack() [localId:%s, track.id:%s]",p,x.id):l.debug("replaceTrack() [localId:%s, no track]",p);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(x)}async setMaxSpatialLayer(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated transceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{k<=x?T.active=!0:T.active=!1}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{E.encodings[k]={...T,...x}}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(p){this.assertNotClosed(),this.assertSendDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.sender.getStats()}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this.assertSendDirection();let x={negotiated:!0,id:this._nextSendSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,protocol:p.protocol};l.debug("sendDataChannel() [options:%o]",x);let w=this._pc.createDataChannel(p.label,x);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%h.MIS,!this._hasDataChannelMediaSection){let P=await this._pc.createOffer(),j=e.parse(P.sdp),T=j.media.find(_=>_.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P),this._remoteSdp.sendSctpAssociation({offerMediaObject:T});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let E={streamId:x.id,ordered:x.ordered,maxPacketLifeTime:x.maxPacketLifeTime,maxRetransmits:x.maxRetransmits};return{dataChannel:w,sctpStreamParameters:E}}async receive(p){this.assertNotClosed(),this.assertRecvDirection();let x=[],w=new Map;for(let T of p){let{trackId:k,kind:_,rtpParameters:A,streamId:M}=T;l.debug("receive() [trackId:%s, kind:%s]",k,_);let V=A.mid??String(this._mapMidTransceiver.size);w.set(k,V);let{msidStreamId:Y}=u.getMsidStreamIdAndTrackId(A.msid);this._remoteSdp.receive({mid:V,kind:_,offerRtpParameters:A,streamId:M??Y??A.rtcp?.cname??"-",trackId:k})}let E={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",E),await this._pc.setRemoteDescription(E);for(let T of p){let{trackId:k,onRtpReceiver:_}=T;if(_){let A=w.get(k),M=this._pc.getTransceivers().find(V=>V.mid===A);if(!M)throw new Error("transceiver not found");_(M.receiver)}}let P=await this._pc.createAnswer(),j=e.parse(P.sdp);for(let T of p){let{trackId:k,rtpParameters:_}=T,A=w.get(k),M=j.media.find(V=>String(V.mid)===A);c.applyCodecParameters({offerRtpParameters:_,answerMediaObject:M}),P={type:"answer",sdp:e.write(j)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",P),await this._pc.setLocalDescription(P);for(let T of p){let{trackId:k}=T,_=w.get(k),A=this._pc.getTransceivers().find(M=>M.mid===_);if(!A)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(_,A),x.push({localId:_,track:A.receiver.track,rtpReceiver:A.receiver})}return x}async stopReceiving(p){if(this.assertRecvDirection(),this._closed)return;for(let E of p){l.debug("stopReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(P.mid)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let E of p)this._mapMidTransceiver.delete(E)}async pauseReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("pauseReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="inactive",this._remoteSdp.pauseMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("resumeReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(p){this.assertRecvDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.receiver.getStats()}async receiveDataChannel({maxMessageSize:p,sctpStreamParameters:x,label:w,protocol:E}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k}=x,_={negotiated:!0,id:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k,protocol:E};l.debug("receiveDataChannel() [options:%o]",_);let A=this._pc.createDataChannel(w,_);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let M={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",M),await this._pc.setRemoteDescription(M);let V=await this._pc.createAnswer(),Y=e.parse(V.sdp),H=Y.media.find(F=>F.type==="application");H.maxMessageSize=p,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:Y}),V={type:"answer",sdp:e.write(Y)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",V),await this._pc.setLocalDescription(V),this._hasDataChannelMediaSection=!0}return{dataChannel:A}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:p,localSdpObject:x}){x||(x=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:x});w.role=p,this._remoteSdp.updateDtlsRole(p==="client"?"server":"client"),await new Promise((E,P)=>{this.safeEmit("@connect",{dtlsParameters:w},E,P)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=p=>{this.emit("@icecandidateerror",p)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new n.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Firefox120=m}),hZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Safari12=void 0;var e=Za(),r=Us(),s=Es(),n=Oo(),i=jn(),o=ff(),a=xm(),c=bm(),d=wm(),u=vm(),l=new s.Logger("Safari12"),f="Safari12",h={OS:65535,MIS:65535},m=class p1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:f,factory:p=>new p1(p),getNativeRtpCapabilities:async({direction:p})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",p);let x=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{x.addTransceiver("audio",{direction:p}),x.addTransceiver("video",{direction:p});let w=await x.createOffer();try{x.close()}catch{}x=void 0;let E=e.parse(w.sdp);return p1.getLocalRtpCapabilities(E)}catch(w){try{x?.close()}catch{}throw x=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:h})}}static getLocalRtpCapabilities(p,x=[]){let w=c.extractRtpCapabilities({sdpObject:p});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let E of x)u.addHeaderExtensionSupport(w,E);return w}constructor({direction:p,iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P,iceServers:j,iceTransportPolicy:T,additionalSettings:k,getSendExtendedRtpCapabilities:_}){super(),l.debug("constructor()"),this._direction=p,this._remoteSdp=new a.RemoteSdp({iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P}),this._getSendExtendedRtpCapabilities=_,E.role&&E.role!=="auto"&&(this._forcedLocalDtlsRole=E.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:T??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",A=>{this.emit("@icecandidateerror",A)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return f}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(p){this.assertNotClosed(),l.debug("updateIceServers()");let x=this._pc.getConfiguration();x.iceServers=p,this._pc.setConfiguration(x)}async restartIce(p){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(p),!!this._transportReady)if(this._direction==="send"){let x=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",x),await this._pc.setLocalDescription(x);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:p,streamId:x,encodings:w,codecOptions:E,headerExtensionOptions:P,codec:j,onRtpSender:T}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",p.kind,p.id,x);let k=this._remoteSdp.getNextMediaSectionIdx(),_=this._pc.addTransceiver(p,{direction:"sendonly",streams:[this._sendStream]});T&&T(_.sender);let A=await this._pc.createOffer(),M=e.parse(A.sdp);M.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let V=[];V.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:p.kind,direction:"sendonly"});let Y=p1.getLocalRtpCapabilities(M,V),H=this._getSendExtendedRtpCapabilities(Y),F=n.getSendingRtpParameters(p.kind,H);F.codecs=n.reduceCodecs(F.codecs,j);let K=n.getSendingRemoteRtpParameters(p.kind,H);K.codecs=n.reduceCodecs(K.codecs,j);let I;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:M});let G=(0,o.parse)((w??[{}])[0].scalabilityMode);w&&w.length>1&&(l.debug("send() | enabling legacy simulcast"),M=e.parse(A.sdp),I=M.media[k.idx],d.addLegacySimulcast({offerMediaObject:I,numStreams:w.length}),A={type:"offer",sdp:e.write(M)}),P?.absCaptureTime&&(I=M.media[k.idx],c.addHeaderExtension({offerMediaObject:I,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:K.headerExtensions.find(O=>O.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),A={type:"offer",sdp:e.write(M)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",A),await this._pc.setLocalDescription(A);let se=_.mid;if(F.mid=se,M=e.parse(this._pc.localDescription.sdp),I=M.media[k.idx],F.rtcp.cname=c.getCname({offerMediaObject:I}),F.msid=`${x??this._sendStream.id} ${p.id}`,F.encodings=d.getRtpEncodings({offerMediaObject:I,codecs:F.codecs}),w)for(let O=0;O<F.encodings.length;++O)w[O]&&Object.assign(F.encodings[O],w[O]);if(F.encodings.length>1&&(F.codecs[0].mimeType.toLowerCase()==="video/vp8"||F.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let O of F.encodings)O.scalabilityMode?O.scalabilityMode=`L1T${G.temporalLayers}`:O.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:I,reuseMid:k.reuseMid,offerRtpParameters:F,answerRtpParameters:K,codecOptions:E});let D={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",D),await this._pc.setRemoteDescription(D),this._mapMidTransceiver.set(se,_),{localId:se,rtpParameters:F,rtpSender:_.sender}}async stopSending(p){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");if(x.sender.replaceTrack(null),this._pc.removeTrack(x.sender),this._remoteSdp.closeMediaSection(x.mid))try{x.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E),this._mapMidTransceiver.delete(p)}async pauseSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="inactive",this._remoteSdp.pauseMediaSection(p);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async resumeSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(p);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async replaceTrack(p,x){this.assertNotClosed(),this.assertSendDirection(),x?l.debug("replaceTrack() [localId:%s, track.id:%s]",p,x.id):l.debug("replaceTrack() [localId:%s, no track]",p);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(x)}async setMaxSpatialLayer(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{k<=x?T.active=!0:T.active=!1}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{E.encodings[k]={...T,...x}}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(p){this.assertNotClosed(),this.assertSendDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.sender.getStats()}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this.assertSendDirection();let x={negotiated:!0,id:this._nextSendSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,protocol:p.protocol};l.debug("sendDataChannel() [options:%o]",x);let w=this._pc.createDataChannel(p.label,x);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%h.MIS,!this._hasDataChannelMediaSection){let P=await this._pc.createOffer(),j=e.parse(P.sdp),T=j.media.find(_=>_.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P),this._remoteSdp.sendSctpAssociation({offerMediaObject:T});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let E={streamId:x.id,ordered:x.ordered,maxPacketLifeTime:x.maxPacketLifeTime,maxRetransmits:x.maxRetransmits};return{dataChannel:w,sctpStreamParameters:E}}async receive(p){this.assertNotClosed(),this.assertRecvDirection();let x=[],w=new Map;for(let T of p){let{trackId:k,kind:_,rtpParameters:A,streamId:M}=T;l.debug("receive() [trackId:%s, kind:%s]",k,_);let V=A.mid??String(this._mapMidTransceiver.size);w.set(k,V);let{msidStreamId:Y}=u.getMsidStreamIdAndTrackId(A.msid);this._remoteSdp.receive({mid:V,kind:_,offerRtpParameters:A,streamId:M??Y??A.rtcp?.cname??"-",trackId:k})}let E={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",E),await this._pc.setRemoteDescription(E);for(let T of p){let{trackId:k,onRtpReceiver:_}=T;if(_){let A=w.get(k),M=this._pc.getTransceivers().find(V=>V.mid===A);if(!M)throw new Error("transceiver not found");_(M.receiver)}}let P=await this._pc.createAnswer(),j=e.parse(P.sdp);for(let T of p){let{trackId:k,rtpParameters:_}=T,A=w.get(k),M=j.media.find(V=>String(V.mid)===A);c.applyCodecParameters({offerRtpParameters:_,answerMediaObject:M})}P={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",P),await this._pc.setLocalDescription(P);for(let T of p){let{trackId:k}=T,_=w.get(k),A=this._pc.getTransceivers().find(M=>M.mid===_);if(!A)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(_,A),x.push({localId:_,track:A.receiver.track,rtpReceiver:A.receiver})}return x}async stopReceiving(p){if(this.assertRecvDirection(),this._closed)return;for(let E of p){l.debug("stopReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(P.mid)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let E of p)this._mapMidTransceiver.delete(E)}async pauseReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("pauseReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="inactive",this._remoteSdp.pauseMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("resumeReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(p){this.assertNotClosed(),this.assertRecvDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.receiver.getStats()}async receiveDataChannel({maxMessageSize:p,sctpStreamParameters:x,label:w,protocol:E}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k}=x,_={negotiated:!0,id:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k,protocol:E};l.debug("receiveDataChannel() [options:%o]",_);let A=this._pc.createDataChannel(w,_);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let M={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",M),await this._pc.setRemoteDescription(M);let V=await this._pc.createAnswer(),Y=e.parse(V.sdp),H=Y.media.find(F=>F.type==="application");H.maxMessageSize=p,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:Y}),V={type:"answer",sdp:e.write(Y)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",V),await this._pc.setLocalDescription(V),this._hasDataChannelMediaSection=!0}return{dataChannel:A}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:p,localSdpObject:x}){x||(x=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:x});w.role=p,this._remoteSdp.updateDtlsRole(p==="client"?"server":"client"),await new Promise((E,P)=>{this.safeEmit("@connect",{dtlsParameters:w},E,P)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=p=>{this.emit("@icecandidateerror",p)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Safari12=m}),pZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReactNative106=void 0;var e=Za(),r=Us(),s=Es(),n=Oo(),i=jn(),o=ff(),a=xm(),c=bm(),d=wm(),u=vm(),l=new s.Logger("ReactNative106"),f="ReactNative106",h={OS:65535,MIS:65535},m=class m1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:f,factory:p=>new m1(p),getNativeRtpCapabilities:async({direction:p})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",p);let x=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{x.addTransceiver("audio",{direction:p}),x.addTransceiver("video",{direction:p});let w=await x.createOffer();try{x.close()}catch{}x=void 0;let E=e.parse(w.sdp);return m1.getLocalRtpCapabilities(E)}catch(w){try{x?.close()}catch{}throw x=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:h})}}static getLocalRtpCapabilities(p,x=[]){let w=c.extractRtpCapabilities({sdpObject:p});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let E of x)u.addHeaderExtensionSupport(w,E);return w}constructor({direction:p,iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P,iceServers:j,iceTransportPolicy:T,additionalSettings:k,getSendExtendedRtpCapabilities:_}){super(),l.debug("constructor()"),this._direction=p,this._remoteSdp=new a.RemoteSdp({iceParameters:x,iceCandidates:w,dtlsParameters:E,sctpParameters:P}),this._getSendExtendedRtpCapabilities=_,E.role&&E.role!=="auto"&&(this._forcedLocalDtlsRole=E.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:T??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return f}close(){if(l.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(p){this.assertNotClosed(),l.debug("updateIceServers()");let x=this._pc.getConfiguration();x.iceServers=p,this._pc.setConfiguration(x)}async restartIce(p){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(p),!!this._transportReady)if(this._direction==="send"){let x=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",x),await this._pc.setLocalDescription(x);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:p,streamId:x,encodings:w,codecOptions:E,headerExtensionOptions:P,codec:j,onRtpSender:T}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",p.kind,p.id,x),w&&w.length>1&&w.forEach((W,q)=>{W.rid=`r${q}`});let k=this._remoteSdp.getNextMediaSectionIdx(),_=this._pc.addTransceiver(p,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});T&&T(_.sender);let A=await this._pc.createOffer(),M=e.parse(A.sdp);M.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let V=[];V.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:p.kind,direction:"sendonly"});let Y=m1.getLocalRtpCapabilities(M,V),H=this._getSendExtendedRtpCapabilities(Y),F=n.getSendingRtpParameters(p.kind,H);F.codecs=n.reduceCodecs(F.codecs,j);let K=n.getSendingRemoteRtpParameters(p.kind,H);K.codecs=n.reduceCodecs(K.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:M});let I=!1,G=(0,o.parse)((w??[{}])[0].scalabilityMode),se;w?.length===1&&G.spatialLayers>1&&F.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),I=!0,M=e.parse(A.sdp),se=M.media[k.idx],d.addLegacySimulcast({offerMediaObject:se,numStreams:G.spatialLayers}),A={type:"offer",sdp:e.write(M)}),P?.absCaptureTime&&(se=M.media[k.idx],c.addHeaderExtension({offerMediaObject:se,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:K.headerExtensions.find(W=>W.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),A={type:"offer",sdp:e.write(M)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",A),await this._pc.setLocalDescription(A);let D=_.mid??void 0;if(D||l.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),F.mid=D,M=e.parse(this._pc.localDescription.sdp),se=M.media[k.idx],F.rtcp.cname=c.getCname({offerMediaObject:se}),F.msid=`${x??this._sendStream.id} ${p.id}`,!w)F.encodings=d.getRtpEncodings({offerMediaObject:se,codecs:F.codecs});else if(w.length===1){let W=d.getRtpEncodings({offerMediaObject:se,codecs:F.codecs});Object.assign(W[0],w[0]),I&&(W=[W[0]]),F.encodings=W}else F.encodings=w;if(F.encodings.length>1&&(F.codecs[0].mimeType.toLowerCase()==="video/vp8"||F.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let W of F.encodings)W.scalabilityMode?W.scalabilityMode=`L1T${G.temporalLayers}`:W.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:se,reuseMid:k.reuseMid,offerRtpParameters:F,answerRtpParameters:K,codecOptions:E});let O={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",O),await this._pc.setRemoteDescription(O),D||(D=_.mid,F.mid=D),this._mapMidTransceiver.set(D,_),{localId:D,rtpParameters:F,rtpSender:_.sender}}async stopSending(p){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");if(x.sender.replaceTrack(null),this._pc.removeTrack(x.sender),this._remoteSdp.closeMediaSection(x.mid))try{x.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E),this._mapMidTransceiver.delete(p)}async pauseSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="inactive",this._remoteSdp.pauseMediaSection(p);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async resumeSending(p){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",p);let x=this._mapMidTransceiver.get(p);if(this._remoteSdp.resumeSendingMediaSection(p),!x)throw new Error("associated RTCRtpTransceiver not found");x.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let E={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",E),await this._pc.setRemoteDescription(E)}async replaceTrack(p,x){this.assertNotClosed(),this.assertSendDirection(),x?l.debug("replaceTrack() [localId:%s, track.id:%s]",p,x.id):l.debug("replaceTrack() [localId:%s, no track]",p);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(x)}async setMaxSpatialLayer(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{k<=x?T.active=!0:T.active=!1}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(p,x){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,x);let w=this._mapMidTransceiver.get(p);if(!w)throw new Error("associated RTCRtpTransceiver not found");let E=w.sender.getParameters();E.encodings.forEach((T,k)=>{E.encodings[k]={...T,...x}}),await w.sender.setParameters(E),this._remoteSdp.muxMediaSectionSimulcast(p,E.encodings);let P=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(p){this.assertNotClosed(),this.assertSendDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.sender.getStats()}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this.assertSendDirection();let x={negotiated:!0,id:this._nextSendSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,protocol:p.protocol};l.debug("sendDataChannel() [options:%o]",x);let w=this._pc.createDataChannel(p.label,x);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%h.MIS,!this._hasDataChannelMediaSection){let P=await this._pc.createOffer(),j=e.parse(P.sdp),T=j.media.find(_=>_.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",P),await this._pc.setLocalDescription(P),this._remoteSdp.sendSctpAssociation({offerMediaObject:T});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let E={streamId:x.id,ordered:x.ordered,maxPacketLifeTime:x.maxPacketLifeTime,maxRetransmits:x.maxRetransmits};return{dataChannel:w,sctpStreamParameters:E}}async receive(p){this.assertNotClosed(),this.assertRecvDirection();let x=[],w=new Map;for(let T of p){let{trackId:k,kind:_,rtpParameters:A,streamId:M}=T;l.debug("receive() [trackId:%s, kind:%s]",k,_);let V=A.mid??String(this._mapMidTransceiver.size);w.set(k,V);let{msidStreamId:Y}=u.getMsidStreamIdAndTrackId(A.msid);this._remoteSdp.receive({mid:V,kind:_,offerRtpParameters:A,streamId:M??Y??A.rtcp?.cname??"-",trackId:k})}let E={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",E),await this._pc.setRemoteDescription(E);for(let T of p){let{trackId:k,onRtpReceiver:_}=T;if(_){let A=w.get(k),M=this._pc.getTransceivers().find(V=>V.mid===A);if(!M)throw new Error("transceiver not found");_(M.receiver)}}let P=await this._pc.createAnswer(),j=e.parse(P.sdp);for(let T of p){let{trackId:k,rtpParameters:_}=T,A=w.get(k),M=j.media.find(V=>String(V.mid)===A);c.applyCodecParameters({offerRtpParameters:_,answerMediaObject:M})}P={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",P),await this._pc.setLocalDescription(P);for(let T of p){let{trackId:k}=T,_=w.get(k),A=this._pc.getTransceivers().find(M=>M.mid===_);if(A)this._mapMidTransceiver.set(_,A),x.push({localId:_,track:A.receiver.track,rtpReceiver:A.receiver});else throw new Error("new RTCRtpTransceiver not found")}return x}async stopReceiving(p){if(this.assertRecvDirection(),this._closed)return;for(let E of p){l.debug("stopReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(P.mid)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let E of p)this._mapMidTransceiver.delete(E)}async pauseReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("pauseReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="inactive",this._remoteSdp.pauseMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(p){this.assertNotClosed(),this.assertRecvDirection();for(let E of p){l.debug("resumeReceiving() [localId:%s]",E);let P=this._mapMidTransceiver.get(E);if(!P)throw new Error("associated RTCRtpTransceiver not found");P.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(E)}let x={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",x),await this._pc.setRemoteDescription(x);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(p){this.assertNotClosed(),this.assertRecvDirection();let x=this._mapMidTransceiver.get(p);if(!x)throw new Error("associated RTCRtpTransceiver not found");return x.receiver.getStats()}async receiveDataChannel({maxMessageSize:p,sctpStreamParameters:x,label:w,protocol:E}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k}=x,_={negotiated:!0,id:P,ordered:j,maxPacketLifeTime:T,maxRetransmits:k,protocol:E};l.debug("receiveDataChannel() [options:%o]",_);let A=this._pc.createDataChannel(w,_);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let M={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",M),await this._pc.setRemoteDescription(M);let V=await this._pc.createAnswer(),Y=e.parse(V.sdp),H=Y.media.find(F=>F.type==="application");H.maxMessageSize=p,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:Y}),V={type:"answer",sdp:e.write(Y)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",V),await this._pc.setLocalDescription(V),this._hasDataChannelMediaSection=!0}return{dataChannel:A}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:p,localSdpObject:x}){x||(x=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:x});w.role=p,this._remoteSdp.updateDtlsRole(p==="client"?"server":"client"),await new Promise((E,P)=>{this.safeEmit("@connect",{dtlsParameters:w},E,P)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=p=>{this.emit("@icecandidateerror",p)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.ReactNative106=m}),mZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Device=void 0,t.detectDevice=h,t.detectDeviceAsync=m;var e=Es(),r=Us(),s=jn(),n=uf(),i=Oo(),o=oZ(),a=lZ(),c=uZ(),d=fZ(),u=hZ(),l=pZ(),f=new e.Logger("Device");function h(k,_){return f.debug("detectDevice()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!_&&typeof navigator=="object"&&(_=navigator.userAgentData),p(k,_)}async function m(k,_){return f.debug("detectDeviceAsync()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!_&&typeof navigator=="object"&&(_=navigator.userAgentData),p(k,_)}var v=class xM{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new r.EnhancedEventEmitter;static async factory({handlerName:_,handlerFactory:A}={}){if(f.debug("factory()"),_&&A)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!_&&!A&&(_=await m(),!_))throw new s.UnsupportedError("device not supported");return new xM({handlerName:_,handlerFactory:A})}constructor({handlerName:_,handlerFactory:A}={}){if(f.debug("constructor()"),_&&A)throw new TypeError("just one of handlerName or handlerInterface can be given");if(A)this._handlerFactory=A;else{if(_)f.debug("constructor() | handler given: %s",_);else if(_=h(),_)f.debug("constructor() | detected handler: %s",_);else throw new s.UnsupportedError("device not supported");switch(_){case"Chrome111":{this._handlerFactory=a.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=c.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=d.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=u.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=l.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${_}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:_,preferLocalCodecsOrder:A=!1}){if(f.debug("load() [routerRtpCapabilities:%o]",_),this._loaded)throw new s.InvalidStateError("already loaded");let M=n.clone(_);i.validateAndNormalizeRtpCapabilities(M);let{getNativeRtpCapabilities:V,getNativeSctpCapabilities:Y}=this._handlerFactory,H=n.clone(await V({direction:"recvonly"}));f.debug("load() | got native receiving RTP capabilities:%o",H),i.validateAndNormalizeRtpCapabilities(H);let F=n.clone(await V({direction:"sendonly"}));f.debug("load() | got native sending RTP capabilities:%o",F),i.validateAndNormalizeRtpCapabilities(F),this._getSendExtendedRtpCapabilities=G=>n.clone(i.getExtendedRtpCapabilities(G,M,A));let K=i.getExtendedRtpCapabilities(H,M,!1);this._recvRtpCapabilities=i.getRecvRtpCapabilities(K),f.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let I=i.getExtendedRtpCapabilities(F,M,A);this._sendRtpCapabilities=i.getSendRtpCapabilities(I),f.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=i.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=i.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await Y(),i.validateSctpCapabilities(this._sctpCapabilities),f.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),f.debug("load() succeeded"),this._loaded=!0}canProduce(_){if(this._loaded){if(_!=="audio"&&_!=="video")throw new TypeError(`invalid kind "${_}"`)}else throw new s.InvalidStateError("not loaded");return this._canProduceByKind[_]}createSendTransport({id:_,iceParameters:A,iceCandidates:M,dtlsParameters:V,sctpParameters:Y,iceServers:H,iceTransportPolicy:F,additionalSettings:K,appData:I}){return f.debug("createSendTransport()"),this.createTransport({direction:"send",id:_,iceParameters:A,iceCandidates:M,dtlsParameters:V,sctpParameters:Y,iceServers:H,iceTransportPolicy:F,additionalSettings:K,appData:I})}createRecvTransport({id:_,iceParameters:A,iceCandidates:M,dtlsParameters:V,sctpParameters:Y,iceServers:H,iceTransportPolicy:F,additionalSettings:K,appData:I}){return f.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:_,iceParameters:A,iceCandidates:M,dtlsParameters:V,sctpParameters:Y,iceServers:H,iceTransportPolicy:F,additionalSettings:K,appData:I})}createTransport({direction:_,id:A,iceParameters:M,iceCandidates:V,dtlsParameters:Y,sctpParameters:H,iceServers:F,iceTransportPolicy:K,additionalSettings:I,appData:G}){if(this._loaded){if(typeof A!="string")throw new TypeError("missing id");if(typeof M!="object")throw new TypeError("missing iceParameters");if(Array.isArray(V)){if(typeof Y!="object")throw new TypeError("missing dtlsParameters");if(H&&typeof H!="object")throw new TypeError("wrong sctpParameters");if(G&&typeof G!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new s.InvalidStateError("not loaded");let se=new o.Transport({direction:_,id:A,iceParameters:M,iceCandidates:V,dtlsParameters:Y,sctpParameters:H,iceServers:F,iceTransportPolicy:K,additionalSettings:I,appData:G,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",se),se}};t.Device=v;function p(k,_){f.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',k,_);let A=x(k,_);if(A){if(A>=111)return f.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(A>=74)return f.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";f.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let M=w(k);if(M){if(M>=120)return f.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";f.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let V=E(k);if(V){if(V>=605)return f.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";f.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let Y=P(k);if(Y){if(Y>=605)return f.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";f.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(T()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return f.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";f.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}f.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',k,_)}function x(k,_){if(f.debug("getChromiumMajorVersion()"),j(k,_)){f.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(T()){f.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(_){let M=(Array.isArray(_.brands)?_.brands:[]).find(V=>V.brand==="Chromium");if(M){let V=Number(M.version);return f.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${V}`),V}}let A=k?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(A?.[1]){let M=Number(A[1]);return f.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${M}`),M}f.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function w(k){if(f.debug("getFirefoxMajorVersion()"),j(k)){f.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(T()){f.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let _=k?.match(/\bFirefox\/(\w+)/i);if(_?.[1]){let A=Number(_[1]);return f.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${A}`),A}f.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function E(k){if(f.debug("getMacOSWebKitMajorVersion()"),j(k)){f.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(T()){f.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(k&&/\bSafari\b/i.test(k)&&!/\bChrome\b/i.test(k)&&!/\bChromium\b/i.test(k)&&!/\bFirefox\b/i.test(k))){f.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let _=k.match(/AppleWebKit\/(\w+)/i);if(_?.[1]){let A=Number(_[1]);return f.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${A}`),A}f.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function P(k){if(f.debug("getIOSWebKitMajorVersion()"),!j(k)){f.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(T()){f.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let _=k?.match(/AppleWebKit\/(\w+)/i);if(_?.[1]){let A=Number(_[1]);return f.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${A}`),A}f.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function j(k,_){return f.debug("isIOS()"),_?.platform==="iOS"?(f.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):_?.platform?(f.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):k&&/iPad|iPhone|iPod/.test(k)?(f.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(f.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(f.debug("isIOS() | this is not iOS => false"),!1)}function T(){return f.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(f.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(f.debug("isReactNative() | this is not React-Native => false"),!1)}}),gZ=et(t=>{"use strict";for(var e=256,r=[],s;e--;)r[e]=(e+256).toString(16).substring(1);function n(){var i=0,o,a="";if(!s||e+16>256){for(s=Array(i=256);i--;)s[i]=256*Math.random()|0;i=e=0}for(;i<16;i++)o=s[e+i],i==6?a+=r[o&15|64]:i==8?a+=r[o&63|128]:a+=r[o],i&1&&i>1&&i<11&&(a+="-");return e++,a}t.v4=n}),yZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),xZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEvent=void 0;var e=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(r,s={}){this.type=r,this.bubbles=s.bubbles??!1,this.cancelable=s.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(r,s,n){}};t.FakeEvent=e}),bZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=e;function e(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}}),wZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeMediaStreamTrack=void 0;var e=gZ(),r=yZ(),s=xZ(),n=bZ(),i=class bM extends r.FakeEventTarget{#m;#u;#f;#e;#r;#t;#s;#h;#n;#p;#i;#o=null;#a=null;#c=null;#d=null;#l=null;constructor({kind:a,id:c,label:d,contentHint:u,enabled:l,muted:f,readyState:h,capabilities:m,constraints:v,settings:p,data:x}){super(),this.#m=c??(0,e.v4)(),this.#u=a,this.#f=d??"",this.#s=u??"",this.#r=l??!0,this.#t=f??!1,this.#e=h??"live",this.#h=m??{},this.#n=v??{},this.#p=p??{},this.#i=x??{}}get id(){return this.#m}get kind(){return this.#u}get label(){return this.#f}get contentHint(){return this.#s}set contentHint(a){this.#s=a}get enabled(){return this.#r}set enabled(a){let c=this.#r!==a;this.#r=a,c&&this.dispatchEvent(new s.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(a){this.#i=a}get onmute(){return this.#o}set onmute(a){this.#o&&this.removeEventListener("mute",this.#o),this.#o=a,a&&this.addEventListener("mute",a)}get onunmute(){return this.#a}set onunmute(a){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=a,a&&this.addEventListener("unmute",a)}get onended(){return this.#c}set onended(a){this.#c&&this.removeEventListener("ended",this.#c),this.#c=a,a&&this.addEventListener("ended",a)}get onenabledchange(){return this.#d}set onenabledchange(a){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=a,a&&this.addEventListener("enabledchange",a)}get onstopped(){return this.#l}set onstopped(a){this.#l&&this.removeEventListener("stopped",this.#l),this.#l=a,a&&this.addEventListener("stopped",a)}addEventListener(a,c,d){super.addEventListener(a,c,d)}removeEventListener(a,c,d){super.removeEventListener(a,c,d)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")))}clone({id:a,data:c}={}){return new bM({id:a??(0,e.v4)(),kind:this.#u,label:this.#f,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,n.clone)(this.#h),constraints:(0,n.clone)(this.#n),settings:(0,n.clone)(this.#p),data:c??(0,n.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#n}async applyConstraints(a={}){return this.#n=a,Promise.resolve()}getSettings(){return this.#p}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")),this.dispatchEvent(new s.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new s.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new s.FakeEvent("unmute")))}};t.FakeMediaStreamTrack=i}),vZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),_Z=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeHandler=void 0;var e=wZ(),r=Us(),s=Es(),n=uf(),i=Oo(),o=jn(),a=vZ(),c=new s.Logger("FakeHandler"),d="FakeHandler",u=class g1 extends r.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${n.generateRandomNumber()}`;_defaultSendStreamId=`${n.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(h){return{name:d,factory:m=>new g1(m,h),getNativeRtpCapabilities:async({direction:m})=>(c.debug("getNativeRtpCapabilities() [direction:%o]",m),g1.getLocalRtpCapabilities(h)),getNativeSctpCapabilities:async()=>(c.debug("getNativeSctpCapabilities()"),h.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(h){let m=h.generateNativeRtpCapabilities();return i.validateAndNormalizeRtpCapabilities(m),m}constructor({getSendExtendedRtpCapabilities:h},m){super(),c.debug("constructor()"),this._getSendExtendedRtpCapabilities=h,this._fakeParameters=m}get name(){return d}close(){c.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(h){this.emit("@icegatheringstatechange",h)}setConnectionState(h){this.emit("@connectionstatechange",h)}async updateIceServers(h){this.assertNotClosed(),c.debug("updateIceServers()")}async restartIce(h){this.assertNotClosed(),c.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:h,streamId:m,encodings:v,codecOptions:p,codec:x}){this.assertNotClosed(),c.debug("send() [kind:%s, track.id:%s]",h.kind,h.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let w=g1.getLocalRtpCapabilities(this._fakeParameters),E=this._getSendExtendedRtpCapabilities(w),P=i.getSendingRtpParameters(h.kind,E);P.codecs=i.reduceCodecs(P.codecs,x);let j=P.codecs.some(k=>/.+\/rtx$/i.test(k.mimeType));P.mid=`mid-${n.generateRandomNumber()}`,P.msid=`${m??"-"} ${h.id}`,v||(v=[{}]);for(let k of v)k.ssrc=n.generateRandomNumber(),j&&(k.rtx={ssrc:n.generateRandomNumber()});P.encodings=v,P.rtcp={cname:this._cname,reducedSize:!0,mux:!0},P.msid=`${m??this._defaultSendStreamId} ${h.id}`;let T=this._nextLocalId++;return this._tracks.set(T,h),{localId:String(T),rtpParameters:P}}async stopSending(h){if(c.debug("stopSending() [localId:%s]",h),!this._closed){if(!this._tracks.has(Number(h)))throw new Error("local track not found");this._tracks.delete(Number(h))}}async pauseSending(h){this.assertNotClosed()}async resumeSending(h){this.assertNotClosed()}async replaceTrack(h,m){this.assertNotClosed(),m?c.debug("replaceTrack() [localId:%s, track.id:%s]",h,m.id):c.debug("replaceTrack() [localId:%s, no track]",h),this._tracks.delete(Number(h)),this._tracks.set(Number(h),m)}async setMaxSpatialLayer(h,m){this.assertNotClosed(),c.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",h,m)}async setRtpEncodingParameters(h,m){this.assertNotClosed(),c.debug("setRtpEncodingParameters() [localId:%s, params:%o]",h,m)}async getSenderStats(h){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:h}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),c.debug("sendDataChannel()");let m=new l({id:this._nextSctpStreamId++,ordered:h.ordered,maxPacketLifeTime:h.maxPacketLifeTime,maxRetransmits:h.maxRetransmits,label:h.label,protocol:h.protocol}),v={streamId:this._nextSctpStreamId,ordered:h.ordered,maxPacketLifeTime:h.maxPacketLifeTime,maxRetransmits:h.maxRetransmits};return{dataChannel:m,sctpStreamParameters:v}}async receive(h){this.assertNotClosed();let m=[];for(let v of h){let{trackId:p,kind:x}=v;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receive() [trackId:%s, kind:%s]",p,x);let w=this._nextLocalId++,E=new e.FakeMediaStreamTrack({kind:x});this._tracks.set(w,E),m.push({localId:String(w),track:E})}return m}async stopReceiving(h){if(!this._closed)for(let m of h)c.debug("stopReceiving() [localId:%s]",m),this._tracks.delete(Number(m))}async pauseReceiving(h){this.assertNotClosed()}async resumeReceiving(h){this.assertNotClosed()}async getReceiverStats(h){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:h,label:m,protocol:v}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receiveDataChannel()"),{dataChannel:new l({id:h.streamId,ordered:h.ordered,maxPacketLifeTime:h.maxPacketLifeTime,maxRetransmits:h.maxRetransmits,label:m,protocol:v})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:h,localSdpObject:m}){let v=n.clone(this._fakeParameters.generateLocalDtlsParameters());h&&(v.role=h),this.emit("@connectionstatechange","connecting"),await new Promise((p,x)=>this.emit("@connect",{dtlsParameters:v},p,x)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new o.InvalidStateError("method called in a closed handler")}};t.FakeHandler=u;var l=class extends a.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:f,ordered:h=!0,maxPacketLifeTime:m=null,maxRetransmits:v=null,label:p="",protocol:x=""}){super(),c.debug(`constructor() [id:${f}, ordered:${h}, maxPacketLifeTime:${m}, maxRetransmits:${v}, label:${p}, protocol:${x}`),this._id=f,this._ordered=h,this._maxPacketLifeTime=m,this._maxRetransmits=v,this._label=p,this._protocol=x}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(f){this._bufferedAmountLowThreshold=f}get binaryType(){return this._binaryType}set binaryType(f){this._binaryType=f}get onopen(){return this._onopen}set onopen(f){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=f,f&&this.addEventListener("open",f)}get onclosing(){return this._onclosing}set onclosing(f){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=f,f&&this.addEventListener("closing",f)}get onclose(){return this._onclose}set onclose(f){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=f,f&&this.addEventListener("close",f)}get onmessage(){return this._onmessage}set onmessage(f){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=f,f&&this.addEventListener("message",f)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(f){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=f,f&&this.addEventListener("bufferedamountlow",f)}get onerror(){return this._onerror}set onerror(f){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=f,f&&this.addEventListener("error",f)}addEventListener(f,h,m){super.addEventListener(f,h,m)}removeEventListener(f,h,m){super.removeEventListener(f,h,m)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(f){if(this._readyState!=="open")throw new o.InvalidStateError("not open")}}}),SZ=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateRouterRtpCapabilities=s,t.generateNativeRtpCapabilities=n,t.generateNativeSctpCapabilities=i,t.generateLocalDtlsParameters=o,t.generateTransportRemoteParameters=a,t.generateProducerRemoteParameters=c,t.generateConsumerRemoteParameters=d,t.generateDataProducerRemoteParameters=u,t.generateDataConsumerRemoteParameters=l;var e=uf();function r(){return String(e.generateRandomNumber())}function s(){return e.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function n(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function i(){return e.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function o(){return e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function a(){return{id:r(),iceParameters:e.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:e.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:e.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function c(){return e.deepFreeze({id:r()})}function d({id:f,codecMimeType:h}={}){switch(h){case"audio/opus":return{id:f??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:f??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:f??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:f??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${h}'`)}}function u(){return e.deepFreeze({id:r()})}function l({id:f}={}){return{id:f??r(),dataProducerId:r(),sctpStreamParameters:e.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}}),wM=et(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.debug=t.testFakeParameters=t.FakeHandler=t.enhancedEvents=t.ortc=t.parseScalabilityMode=t.detectDeviceAsync=t.detectDevice=t.Device=t.version=t.types=void 0;var e=S1();t.debug=e.default,t.types=XQ(),t.version="3.20.0";var r=mZ();Object.defineProperty(t,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(t,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(t,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var s=ff();Object.defineProperty(t,"parseScalabilityMode",{enumerable:!0,get:function(){return s.parse}}),t.ortc=Oo(),t.enhancedEvents=Us();var n=_Z();Object.defineProperty(t,"FakeHandler",{enumerable:!0,get:function(){return n.FakeHandler}}),t.testFakeParameters=SZ()}),EZ=et((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,s="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(s=!1));function i(d,u,l){this.fn=d,this.context=u,this.once=l||!1}function o(d,u,l,f,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var m=new i(l,f||d,h),v=s?s+u:u;return d._events[v]?d._events[v].fn?d._events[v]=[d._events[v],m]:d._events[v].push(m):(d._events[v]=m,d._eventsCount++),d}function a(d,u){--d._eventsCount===0?d._events=new n:delete d._events[u]}function c(){this._events=new n,this._eventsCount=0}c.prototype.eventNames=function(){var d=[],u,l;if(this._eventsCount===0)return d;for(l in u=this._events)r.call(u,l)&&d.push(s?l.slice(1):l);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},c.prototype.listeners=function(d){var u=s?s+d:d,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,h=l.length,m=new Array(h);f<h;f++)m[f]=l[f].fn;return m},c.prototype.listenerCount=function(d){var u=s?s+d:d,l=this._events[u];return l?l.fn?1:l.length:0},c.prototype.emit=function(d,u,l,f,h,m){var v=s?s+d:d;if(!this._events[v])return!1;var p=this._events[v],x=arguments.length,w,E;if(p.fn){switch(p.once&&this.removeListener(d,p.fn,void 0,!0),x){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,l),!0;case 4:return p.fn.call(p.context,u,l,f),!0;case 5:return p.fn.call(p.context,u,l,f,h),!0;case 6:return p.fn.call(p.context,u,l,f,h,m),!0}for(E=1,w=new Array(x-1);E<x;E++)w[E-1]=arguments[E];p.fn.apply(p.context,w)}else{var P=p.length,j;for(E=0;E<P;E++)switch(p[E].once&&this.removeListener(d,p[E].fn,void 0,!0),x){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,u);break;case 3:p[E].fn.call(p[E].context,u,l);break;case 4:p[E].fn.call(p[E].context,u,l,f);break;default:if(!w)for(j=1,w=new Array(x-1);j<x;j++)w[j-1]=arguments[j];p[E].fn.apply(p[E].context,w)}}return!0},c.prototype.on=function(d,u,l){return o(this,d,u,l,!1)},c.prototype.once=function(d,u,l){return o(this,d,u,l,!0)},c.prototype.removeListener=function(d,u,l,f){var h=s?s+d:d;if(!this._events[h])return this;if(!u)return a(this,h),this;var m=this._events[h];if(m.fn)m.fn===u&&(!f||m.once)&&(!l||m.context===l)&&a(this,h);else{for(var v=0,p=[],x=m.length;v<x;v++)(m[v].fn!==u||f&&!m[v].once||l&&m[v].context!==l)&&p.push(m[v]);p.length?this._events[h]=p.length===1?p[0]:p:a(this,h)}return this},c.prototype.removeAllListeners=function(d){var u;return d?(u=s?s+d:d,this._events[u]&&a(this,u)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=s,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),cA=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(t){this._ws=t,this._onMessage=e=>{if(typeof e.data!="string")return;let r;try{r=JSON.parse(e.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let n of s)n(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r.delete(e),r.size===0&&this._handlers.delete(t)}}emit(t,e){if(this._disposed)return;let r=JSON.stringify({channel:t,...e});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let t=this._pendingSends;this._pendingSends=[];for(let e of t)this._ws.send(e)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},dA=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(t){if(this._disposed)return;this.detachTarget(),this._target=t;for(let[r,s]of this._handlers)for(let n of s)this._targetUnsubscribes.push(t.on(r,n));let e=this._pendingSends;this._pendingSends=[];for(let r of e)t.emit(r.channel,r.data)}rewriteSessionChannels(t,e){if(t===e)return;let r=`session:${t}:`,s=`session:${e}:`,n=new Map;for(let[i,o]of this._handlers)n.set(i.startsWith(r)?s+i.slice(r.length):i,o);this._handlers=n,this._pendingSends=this._pendingSends.map(i=>({...i,channel:i.channel.startsWith(r)?s+i.channel.slice(r.length):i.channel}))}on(t,e){if(this._disposed)return()=>{};let r=this._handlers.get(t);r||(r=new Set,this._handlers.set(t,r)),r.add(e);let s=this._target?.on(t,e);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(n=>n!==s))}}emit(t,e){if(!this._disposed){if(this._target){this._target.emit(t,e);return}this._pendingSends.push({channel:t,data:e})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let t of this._targetUnsubscribes)t();this._targetUnsubscribes=[],this._target=null}},E1=class extends Error{code="session_end_unavailable";constructor(t="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",e){super(t),this.name="SessionEndUnavailableError",e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},Wd=class extends Error{code;httpStatus;requestId;constructor(t,e){super(t),this.name="SessionEndError",this.code=e.code??"session_end_failed",this.httpStatus=e.httpStatus,this.requestId=e.requestId,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},ec=class extends Error{requestId;code;constructor(t,e){super(t),this.name="RequestError",this.requestId=e?.requestId,this.code=e?.code,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},lA=class extends ec{timeoutMs;constructor(t,e){super(`[urun] request timed out after ${t}ms`,{requestId:e}),this.name="RequestTimeoutError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},uA=class extends ec{timeoutMs;constructor(t,e){super(`[urun] request doc-sync did not establish within ${t}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:e}),this.name="RequestDocSyncError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},fA=class extends Error{stream;owner;attempted;constructor(t,e,r){super(`[urun] stream "${t}" is already produced by the ${e}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=t,this.owner=e,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},pm=15e3,hA=class extends Error{kind;stream;timeoutMs;constructor(t,e){let r=e?.timeoutMs??pm,s=e?.stream??t,n=s!==t?` "${s}"`:"";super(`[urun] SFU did not ack producer ${t}${n} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=t,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},C1=class extends ec{constructor(t){super("[urun] request aborted",{requestId:t}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},pA=class extends ec{constructor(t){super("[urun] request cancelled: session disconnected",{requestId:t}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};function mA(t,e){let r=e.error?.reason,s=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(t){case"create-failed":return{message:`[urun] session create failed${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""}${r?`: ${r}`:""}`,hint:e.error?.httpStatus===401||e.error?.httpStatus===403?"The backend rejected this client \u2014 sign in again or check the auth token / org access.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."};case"never-live":{let n=s!==void 0?` after ${s}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`;return e.error?.code==="expired"?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${n} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?{message:`[urun] session ${e.sessionId} was created but never went live${n}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${n} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${r?`: ${r}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${r?`: ${r}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"ended":return{message:`[urun] session ended before going live${e.sessionId?` (id ${e.sessionId})`:""}`,hint:"The session was closed (server-side, or superseded by another connection). Start a new session."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${r?`: ${r}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs, then start a new session."};case"produce-timeout":return{message:`[urun] publishing a track timed out${r?`: ${r}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"expired":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} ended \u2014 ${r??"it reached its maximum length"}`,hint:"The session reached its end. Start a new session to continue."}}}var Xd=class extends Error{kind;status;hint;constructor(t,e,r){let{message:s,hint:n}=mA(t,e);super(s),this.name="SessionFailedError",this.kind=t,this.status=e,this.hint=n,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}};function vM(t,e){if(t instanceof Xd)return t;let r=t instanceof Error?t:new Error(String(t)),s={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:r.message,code:r.name,kind:"media-permission"}};return new Xd("media-permission",s,{cause:t})}var x1=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(t,e){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${t??"(unknown)"} but setConnection() asked for ${e} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=t,this.requestedSessionId=e,Object.setPrototypeOf(this,new.target.prototype)}},Mn=class extends Error{httpStatus;constructor(t,e){super(t),this.name="SessionAllocationError",this.httpStatus=e?.httpStatus,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}};function gA(t){if(!t)return!1;let e=typeof t=="string"?t:t.name;return e==="queued"||e==="unavailable"||e==="provisioning"}var yA=45e3;function xA(t,e={}){let{timeout:r=yA,signal:s}=e;return new Promise((n,i)=>{if(s?.aborted){i(s.reason instanceof Error?s.reason:new Error("whenLive aborted"));return}if(t.phase?.name==="live"){n();return}let o=t.phase?.name;if(o==="error"||o==="ended"||o==="expired"){let m=t.phase,v=t.status??{phase:m.name,transportState:"disconnected",sessionId:m.sessionId,requestId:m.requestId,queue:m.queue,error:m.error};i(new Xd(o==="ended"?"ended":o==="expired"?"expired":m.error?.kind??"transport-failed",v));return}let a,c,d=!1,u=m=>{d||(d=!0,c!==void 0&&clearTimeout(c),s?.removeEventListener("abort",l),a?.(),m?i(m):n())},l=()=>{u(s?.reason instanceof Error?s.reason:new Error("whenLive aborted"))};s?.addEventListener("abort",l,{once:!0});let f=()=>{let m=t.phase;return t.status??{phase:m?.name??"idle",transportState:"disconnected",sessionId:m?.sessionId,requestId:m?.requestId,queue:m?.queue,error:m?.error}},h=m=>u(new Xd(m,f()));r>0&&(c=setTimeout(()=>{let m=f();m.elapsedMs===void 0&&(m.elapsedMs=r),u(new Xd("never-live",m))},r)),a=t.onPhase(m=>{m?.name==="live"?u():m?.name==="error"?h(m.error?.kind??"transport-failed"):m?.name==="ended"?h("ended"):m?.name==="expired"&&h("expired")}),d&&a()})}function _M(t){switch(t.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return t.queue?`Waiting in queue (position ${t.queue.position} of ${t.queue.depth})\u2026`:t.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return t.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"connecting":return"Connecting\u2026";case"live":return"Live";case"error":return t.error?.reason?`Session failed \u2014 ${t.error.reason}`:"Session failed";case"ended":return"Session ended";case"expired":return"Session ended \u2014 reached its maximum length. Start a new session."}}var T1=500,A1=15e3,lf=6;function _m(t,e=Math.random){if(!Number.isFinite(t)||t<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${t}`);let r=Math.min(A1,T1*2**t);return Math.round(e()*r)}function k1(t){if(t instanceof Mn){let e=t.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return t instanceof Error?t.name==="TypeError"||t.name==="TimeoutError"||t.name==="AbortError":!1}var SM=10,CZ=.5,b1=SM;function EM(){return b1<1?!1:(b1-=1,!0)}function CM(){b1=Math.min(SM,b1+CZ)}var TZ="session-api.prod.cloud.urun.sh",AZ=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Ss(t){return t.trim().replace(/\/+$/,"")}function I1(t,e){let r=[],s=n=>{if(!n)return;let i=Ss(n);i&&!r.includes(i)&&r.push(i)};s(t);for(let n of e??[])s(n);for(let n of GZ(t))s(n);return r}function bA(t){try{if(typeof fetch!="function")return;let e=`${Ss(t.baseUrl)}/api/session-requests/${encodeURIComponent(t.requestId)}/release`;fetch(e,{method:"POST",headers:Ja(t,t.jwt),keepalive:!0}).catch(()=>{})}catch{}}async function TM(t){try{let e=`${Ss(t.baseUrl)}/api/session-requests/${encodeURIComponent(t.requestId)}/release`,r=await Qa(t);if(t.getAccessToken&&!r)throw new Wd("[urun] session release refused: getAccessToken resolved no token (an unauthenticated release is never sent)",{requestId:t.requestId,code:"no_access_token"});let s=await fetch(e,{method:"POST",headers:Ja(t,r)});if((s.status===401||s.status===403)&&t.getAccessToken){let o=await Qa(t,{forceRefresh:!0,reason:"unauthorized"});o&&o!==r&&(s=await fetch(e,{method:"POST",headers:Ja(t,o)}))}let n=await R1(s);if(!s.ok)throw new Wd(n.error_message||n.error_code||`[urun] session release failed: HTTP ${s.status}`,{requestId:t.requestId,code:n.error_code,httpStatus:s.status});let i=String(n.status??"");if(i==="closed")return{status:"ended",requestId:t.requestId};if(i==="cancelled"||i==="canceled")return{status:"canceled",requestId:t.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"ended",requestId:t.requestId,platformStatus:i};throw new Wd(`[urun] session release returned an unrecognized terminal status ${JSON.stringify(i)} (recognized: closed, cancelled/canceled, failed, rejected, expired)`,{requestId:t.requestId,code:"invalid_release_response",httpStatus:s.status})}catch(e){throw e instanceof Wd?e:new Wd("[urun] session release request failed",{requestId:t.requestId,cause:e})}}function AM(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}var kZ=120,IZ=1e3,RZ=20,PZ=5,BZ=500,kM=1e4,DZ=new Set([502,503,504]),NZ=3,OZ=50,FU=1e4;async function HU(t,e){let r=Date.now()+FU;for(;;){await mm(OZ);let s=await Qa(t);if(s)return s;if(Date.now()>=r)throw new Mn(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(FU/1e3)}s (no unauthenticated request was sent)`)}}function LZ(t,e){if(!t)return null;try{let r=new URL(t),s=e?new URL(Ss(e)):null,n=r.pathname==="/api/sessions/create"||r.pathname==="/api/sessions/create/";return r.protocol!=="https:"||!n||!UZ(r,s)?null:Ss(r.origin)}catch{return null}}function UZ(t,e){return $U(t.hostname)&&(!e||$U(e.hostname))}function $U(t){let e=t.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}async function IM(t){let e=I1(t.baseUrl,t.fallbackUrls),r=null,s=e.length>1;for(let n=0;n<lf;n++){for(let i of e)try{let o=await MZ(i,t,{pollAttempts:kZ,retryAfterLimitMs:s?IZ:void 0});return CM(),o}catch(o){if(r=o instanceof Error?o:new Error(String(o)),r instanceof Gd||r instanceof fm)throw r}if(!k1(r))break;if(n+1<lf){if(!EM())break;await mm(_m(n))}}throw r??new Error("[urun] session allocation failed")}async function MZ(t,e,r){let s,n,i,o=t,a=0,c=new Set,d=Date.now()+r.pollAttempts*kM;for(let u=0;u<r.pollAttempts;u++){n=i??await Qa(e),i=void 0,e.getAccessToken&&!n&&(n=await HU(e,o));let l=!!s,f=Date.now(),h;if(s){let x=0;for(;;){let w=d-Date.now();if(w<=0)throw eA(o,!0);let E=Math.max(1,Math.min(RZ,Math.floor(w/1e3)));f=Date.now();try{h=await fetch(`${o}/api/session-requests/${encodeURIComponent(s)}?wait_s=${E}`,{headers:Ja(e,n),signal:zZ((E+PZ)*1e3)})}catch(k){throw new fm(`[urun] session allocation poll failed at ${o}`,{cause:k})}if(!DZ.has(h.status))break;try{await h.body?.cancel()}catch(k){throw new fm(`[urun] session allocation poll response cleanup failed at ${o}`,{cause:k})}let P=Math.min(A1,T1*2**x),j=Math.max(Math.ceil(P/2),_m(x));x+=1;let T=Math.min(Math.max(zU(h,{},r.retryAfterLimitMs),j),Math.max(0,d-Date.now()));if(T<=0)throw eA(o,!0);await mm(T)}}else h=await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ja(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(jZ(e))});if(!s&&(h.status===307||h.status===308)){let x=LZ(h.headers.get("location"),o);if(x&&x!==o&&a<NZ){a+=1,o=x;continue}throw new Mn(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:h.status})}let m=await R1(h);if(m.request_id)try{e.onRequest?.({requestId:m.request_id,baseUrl:o})}catch{}if(h.ok&&(m.status==="allocated"||!m.status&&m.session_id)&&m.session_id){let x=m.session_id,w=DM(m.ws_url,o,x,"gateway allocated session");return{baseUrl:o,sessionId:x,wsUrl:w,endsAt:AM(m.ends_at),response:m}}if(h.status===202||m.status==="pending"||m.status==="queued"||m.queued){if(s=m.request_id||s,!s)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(qZ(m,s))}catch{}let x=Date.now()-f<BZ;l&&x&&await mm(zU(h,m,r.retryAfterLimitMs));continue}if((h.status===401||h.status===403)&&e.getAccessToken){let x=n??"";c.add(x);let w=await Qa(e,{forceRefresh:!0,reason:"unauthorized"});if(w&&!c.has(w)){i=w;continue}if(w===void 0){let E=await HU(e,o);if(!c.has(E)){i=E;continue}}}let v=m.error_message||m.error_code||`HTTP ${h.status}`,p=l?fm:Mn;throw new p(`[urun] session allocation failed at ${o}: ${v}`,{httpStatus:h.status})}throw eA(o,!!s)}function eA(t,e=!1){let r=e?fm:Mn;return new r(`[urun] timed out waiting for session allocation at ${t}`)}function Ja(t,e){let r={"X-Tenant-Id":t.orgId,"X-Auth-Provider":t.authProvider||"default","X-User-Id":"anonymous"};return e&&(r.Authorization=`Bearer ${e}`),r}async function Qa(t,e){return t.getAccessToken?await t.getAccessToken(e)??void 0:t.jwt}function jZ(t){let e=t.priority==="preempt";return{app:t.app,function:t.functionName,gpus:1,idempotency_key:t.idempotencyKey,...t.sessionKey&&!e?{logical_id:t.sessionKey}:{},...e?{priority:"preempt"}:{}}}async function RM(t){let e=I1(t.baseUrl,t.fallbackUrls),r=null;for(let s=0;s<lf;s++){for(let n of e)try{let i={baseUrl:n,app:"",functionName:"",orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider,idempotencyKey:""},o=`${Ss(n)}/api/sessions/${encodeURIComponent(t.sessionId)}/viewer-connect`,a=await Qa(i);if(t.getAccessToken&&!a)throw new Mn(`[urun] viewer-connect for ${t.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let c=await fetch(o,{headers:Ja(i,a)});if((c.status===401||c.status===403)&&t.getAccessToken){let l=await Qa(i,{forceRefresh:!0,reason:"unauthorized"});l&&l!==a&&(c=await fetch(o,{headers:Ja(i,l)}))}if(!c.ok)throw new Mn(`[urun] viewer-connect for ${t.sessionId} failed: HTTP ${c.status}`,{httpStatus:c.status});let d=await R1(c),u=DM(d.ws_url,n,t.sessionId,"viewer-connect");return CM(),{baseUrl:Ss(n),sessionId:t.sessionId,wsUrl:u,endsAt:AM(d.ends_at),response:d}}catch(i){if(r=i instanceof Error?i:new Error(String(i)),r instanceof Gd)throw r}if(!k1(r))break;if(s+1<lf){if(!EM())break;await mm(_m(s))}}throw r??new Error("[urun] viewer-connect failed")}async function PM(t){try{let e=Ss(t.baseUrl),r=await Qa(t);if(t.getAccessToken&&!r)return{status:"unavailable"};let s=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Ja(t,r),"Content-Type":"application/json"},body:JSON.stringify({app:t.app,function:t.functionName})});if(s.status===404)return{status:"unknown-app"};if(!s.ok)return{status:"unavailable"};let n=await R1(s),i={status:n.status==="prebound"?"prebound":"warming"};return typeof n.expires_at=="string"&&(i.expiresAt=n.expires_at),typeof n.warm_capable=="boolean"&&(i.warmCapable=n.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function R1(t){try{let e=await t.json();return e&&typeof e=="object"?e:{}}catch{return{}}}var FZ=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function BM(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function VU(t){return typeof t=="string"&&t.trim().length>0}function qU(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function HZ(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function $Z(t){if(BM(t)&&!(!VU(t.snapshot_id)||!VU(t.snapshot_compat_key)||!qU(t.artifact_size_bytes)||!qU(t.durable_arena_bytes)||t.volatile_arena_bytes!==0||!HZ(t.uncovered_weight_bytes)))return{snapshotId:t.snapshot_id,snapshotCompatKey:t.snapshot_compat_key,artifactSizeBytes:t.artifact_size_bytes,durableArenaBytes:t.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:t.uncovered_weight_bytes}}function VZ(t){if(!BM(t)||t.schema!=="urun.runtime.wake.v1"||t.portability!=="portable"&&t.portability!=="none"||t.expected_wake_path!=="portable-golden-restore"&&t.expected_wake_path!=="cold-boot"||typeof t.reason_code!="string"||!FZ.has(t.reason_code)||t.expectation_basis!=="snapshot-registry"||t.restore_observation!=="not-observed")return;let e=t.reason_code;if(t.portability==="portable"&&t.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let r=$Z(t.golden);return r?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:r}:void 0}if(t.portability==="none"&&t.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&t.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function qZ(t,e){let r={status:t.status==="queued"||t.queued?"queued":"pending",requestId:e};typeof t.queue_position=="number"&&typeof t.queue_depth=="number"&&(r.queue={position:t.queue_position,depth:t.queue_depth});let s=t.runtime_state;if(s==="unavailable"||s==="starting"||s==="busy"){r.runtime={state:s},typeof t.runtime_reason=="string"&&t.runtime_reason.length>0&&(r.runtime.reason=t.runtime_reason);let n=VZ(t.runtime_wake);n&&(r.runtime.wake=n)}return r}function zU(t,e,r){let s=Number(t.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??s),i=r??kM;return Number.isFinite(n)&&n>0?Math.min(n*1e3,i):1e3}function mm(t){return new Promise(e=>setTimeout(e,t))}function zZ(t){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(t):void 0}var Gd=class extends Error{},fm=class extends Mn{};function DM(t,e,r,s){if(!t)throw new Gd(`[urun] ${s} ${r} without ws_url`);let n,i;try{n=new URL(t)}catch{throw new Gd(s==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${r}`:`[urun] ${s} ${r} with non-absolute ws_url`)}try{i=new URL(Ss(e))}catch{throw new Gd(`[urun] ${s} ${r} has invalid gateway base URL`)}let o=KZ(i.hostname)&&i.protocol==="http:";if(!(o&&n.protocol==="ws:"||n.protocol==="wss:"))throw new Gd(`[urun] ${s} ${r} with insecure ws_url`);if(!WZ(n,i,o))throw new Gd(`[urun] ${s} ${r} with cross-origin ws_url`);return n.toString()}function KZ(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t.endsWith(".localhost")}function WZ(t,e,r){return!!(r||t.hostname===e.hostname&&t.port===e.port||KU(t.hostname)&&KU(e.hostname))}function KU(t){return t==="urun.sh"||t.endsWith(".urun.sh")}function GZ(t){try{return new URL(t).hostname!==TZ?[]:AZ}catch{return[]}}function hf(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function XZ(){return hf()?"Chrome111":void 0}var YZ=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],tA=null,NM=null;function JZ(){return typeof globalThis.RTCPeerConnection<"u"?null:NM??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function P1(){return hf()?tA||(tA=QZ(),tA):Promise.resolve()}async function QZ(){let t=globalThis;if(typeof t.WebSocket>"u")try{let e=await Promise.resolve().then(()=>(n3(),s3)),r=e.default??e;t.WebSocket=r}catch(e){WU("WebSocket",e)}if(typeof t.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(UU(),LU));ZZ(t,e)}catch(e){NM=WU("werift",e)}}function ZZ(t,e){let{RTCPeerConnection:r,useH264:s,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:u}=e,l=()=>({video:[s(),n()],audio:[i()]}),f=()=>({video:[o(),a(),c(),d(),u()],audio:[o(),c(),d()]});class h extends r{constructor(v){super({...v,codecs:v?.codecs??l(),headerExtensions:v?.headerExtensions??f()})}}t.RTCPeerConnection=h;for(let m of YZ)e[m]!=null&&typeof t[m]>"u"&&(t[m]=e[m])}function WU(t,e){let r=e instanceof Error?e.message:String(e),s=`optional dependency "${t}" unavailable (${r})`;return console.warn(`[urun-sh/core] Node WebRTC support: ${s}. Realtime media will not work in this Node process; install "${t}" to enable it. Doc/KV transport over WebSocket is unaffected.`),s}function eee(t){return`stream:${t}`}var tee="urun-stream-v1",nA=1,No={BINARY:0,TEXT:1,JSON:2,END:3},OM=Symbol("urun:stream:end");function ree(t){if(t===OM)return Uint8Array.from([nA,No.END]);let e,r;t instanceof Uint8Array?(e=No.BINARY,r=t):t instanceof ArrayBuffer?(e=No.BINARY,r=new Uint8Array(t)):typeof t=="string"?(e=No.TEXT,r=new TextEncoder().encode(t)):(e=No.JSON,r=new TextEncoder().encode(JSON.stringify(t)));let s=new Uint8Array(2+r.length);return s[0]=nA,s[1]=e,s.set(r,2),s}function see(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<2||e[0]!==nA)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);let r=e[1],s=e.subarray(2);switch(r){case No.BINARY:return s.slice();case No.TEXT:return new TextDecoder().decode(s);case No.JSON:return JSON.parse(new TextDecoder().decode(s));case No.END:return OM;default:throw new Error(`[urun] unknown stream envelope KIND 0x${r.toString(16)}`)}}function LM(t){return{get consumerId(){return t.consumerId},onData(e,r){return t.onStreamData(e,r)},sendData(e,r,s){return t.sendStreamData(e,r,s)}}}var nee=cM(wM()),iee=cM(EZ(),1),GU="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function oee(t){let e=globalThis.crypto,r=new Uint8Array(t);if(e?.getRandomValues)return e.getRandomValues(r),r;for(let s=0;s<t;s++)r[s]=Math.floor(Math.random()*256);return r}function B1(t=16){let e=oee(t),r="";for(let s=0;s<t;s++)r+=GU[e[s]%GU.length];return r}var XU=[1e3,2e3,4e3,8e3,3e4],YU=5,aee=15e3,JU=15e3,QU=15e3,cee=2e3,dee=6e3,lee=300,uee=2,fee=750,hee=3,ZU=[1e3,2e3,4e3],pee=15e3;var gm="--",mee=["video","audio"];function wA(t){let e=t.lastIndexOf(gm);if(e<=0)return;let r=t.slice(e+gm.length);return mee.includes(r)?r:void 0}function UM(t,e){return`${t}${gm}${e}`}var gee={queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",allocated:"connecting",connecting:"connecting",live:"live",running:"live",error:"error",failed:"error",rejected:"error",expired:"expired",cancelled:"ended",canceled:"ended",closed:"ended"};function df(t){return t==="error"||t==="ended"||t==="expired"}var eM=3,tM=4e3,rM=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function sM(t){if(!t)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(t);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var vA=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new iee.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(t=>{this._mediaVerdictResolve=t});_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=jM();_candidatePairDiagnosticEmitted=!1;_currentEpoch=0;_consumerId=null;_streamDataHandlers=new Map;_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=yee()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let t=e=>e!==null&&!e.closed&&!e.paused;return t(this._audioProducer)||t(this._videoProducer)}get endsAt(){return this._endsAt}setEndsAt(t){this._endsAt=t}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let t={phase:this._phase.name,transportState:this._state};return this._sessionId&&(t.sessionId=this._sessionId),this._requestId&&(t.requestId=this._requestId),this._lastServerStatus!==void 0&&(t.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(t.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(t.endsAt=this._endsAt),this._phase.queue&&(t.queue=this._phase.queue),this._phase.runtime&&(t.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(t.wakingSince=this._phase.wakingSince),this._phase.error&&(t.error=this._phase.error),t}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}get connectedUrl(){return this._connectedUrl}getTrackByName(t){if(wA(t)!==void 0)return;let e=this._tracksByName.get(t);if(e&&e.readyState!=="ended")return e;for(let r of this._tracks.values())if(!(r.kind!==t||r.readyState==="ended")&&this._streamNameOf(r)===void 0)return r;return e}_streamNameOf(t){for(let[e,r]of this._tracksByName)if(r===t)return e}setAuth(t){this._options={...this._options,...t},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(t){this._options=t??{url:""},t?.sessionId&&(this._sessionId=t.sessionId)}setConnection(t){if(this.isOpen){let e=sM(t.url);if(t.sessionId!==void 0&&t.sessionId!==this._sessionId)throw new x1(this._sessionId,t.sessionId);if(e!==void 0&&e!==this._sessionId)throw new x1(this._sessionId,e);this._options={...this._options,...t};return}this._options={...this._options,...t},t.sessionId&&(this._sessionId=t.sessionId)}setConnectionResolver(t){this._resolveConnection=t}applyControlDocState(t){let e=t&&typeof t=="object"?t.session:void 0,r=See(e);if(r!==void 0&&this.setIncarnation(r),!e||typeof e!="object")return;let s=e,n=typeof s.status=="string"?s.status:void 0;if(n&&!df(this._phase.name)&&!this.isStaleClosedMarker(s))if(n==="error"){let i=s.error_reason??s.errorReason,o=typeof i=="string"&&i?i:"session failed";this._setPhase("error",{error:{reason:o,code:"runtime-failed",kind:"runtime-failed"}})}else(n==="closed"||n==="ended")&&(this._pastDeadline()?this._setPhase("expired",{error:{reason:"session reached its maximum length",code:n,kind:"expired"}}):this._setPhase("ended"))}setIncarnation(t){if(!Number.isFinite(t)||t<=this._currentEpoch)return;let e=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=t,e&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(t){return Number.isFinite(t)?t<this._currentEpoch:!1}isStaleClosedMarker(t){if(!t)return!1;let e=typeof t.status=="string"?t.status:void 0;if(e!=="closed"&&e!=="ended"&&e!=="error")return!1;let r=t.status_epoch??t.statusEpoch,s=typeof r=="number"?r:Number(r);return Number.isFinite(s)?s<this._currentEpoch:!1}async connect(t){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){t!==void 0&&(this._lastStartOptions=t);return}this._lastStartOptions=t,this._intentionalDisconnect=!1,df(this._phase.name)&&(this._phase={name:"idle"}),this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let e=++this._generation,r=this._state==="reconnecting"||this._state==="renegotiating";r||this._setState("connecting");let s=null,n=()=>e!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let u of this._connectUrls()){i();try{return await this._connectOnce(u,e,t),!0}catch(l){s=l instanceof Error?l:new Error(String(l)),n()||this._cleanupSocket()}}return!1},a=this._forceResolveOnNextConnect&&this._resolveConnection!==null;this._forceResolveOnNextConnect=!1;let c=a?0:this._resolveConnection?uee:1;for(let u=0;u<c;u++)if(u>0&&(await nM(fee),i()),await o())return;if(this._resolveConnection)for(let u=0;u<hee;u++){this._setState("reconnecting"),await nM(ZU[Math.min(u,ZU.length-1)]),i();try{let l=await this._resolveConnection();i(),this.setAuth({jwt:l.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:l.url,sessionId:l.sessionId,iceServers:l.iceServers??this._options.iceServers}),l.endsAt!==void 0&&(this._endsAt=l.endsAt)}catch(l){if(n())throw new Error("TransportSession: connect cancelled");s=l instanceof Error?l:new Error(String(l));continue}if(await o())return}if(n())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let d=s??new Error("TransportSession: connect failed");throw r||this._emitError(d),d}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._stopMediaProbe(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(){this._generation+=1,this._intentionalDisconnect=!0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("ended"),this._emitter.emit("disconnected")}on(t,e){return this._emitter.on(t,e),()=>{this._emitter.off(t,e)}}_emitDiagnostic(t){t.level==="debug"?console.debug(`[urun] ${t.message}`,t.detail??{}):console.warn(`[urun] ${t.message}`,t.detail??{}),this._emitter.emit("diagnostic",t)}sendInput(t,e){this._send({type:"input",data:t,sequence:e})}sendSignal(t){this._send(t)}onSignal(t){return this.on("signal",t)}onStreamData(t,e){let r=this._streamDataHandlers.get(t);return r||(r=new Set,this._streamDataHandlers.set(t,r)),r.add(e),()=>{let s=this._streamDataHandlers.get(t);s?.delete(e),s&&s.size===0&&this._streamDataHandlers.delete(t)}}sendStreamData(t,e,r){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._ensureDataProducer(t).then(s=>{s.send(ree(e))})}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((t,e)=>{let r={resolve:n=>{clearTimeout(s),t(n)},reject:n=>{clearTimeout(s),e(n)}},s=setTimeout(()=>{let n=this._sendTransportWaiters.indexOf(r);n>=0&&this._sendTransportWaiters.splice(n,1),e(new Error(`[urun] sendStreamData: no send transport after ${JU}ms (the server never offered createSendTransport \u2014 data-up produce is impossible on this leg)`))},JU);this._sendTransportWaiters.push(r)})}_settleSendTransportWaiters(t,e){let r=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of r)t?s.resolve(t):s.reject(e??new Error("TransportSession: disconnected"))}_ensureDataProducer(t){let e=this._dataProducers.get(t);if(e&&!e.closed)return Promise.resolve(e);let r=this._dataProducerPromises.get(t);if(r)return r;let s=this._awaitSendTransport().then(n=>n.produceData({label:eee(t),protocol:tee,ordered:!0})).then(n=>this._awaitDataChannelOpen(n)).then(n=>(this._dataProducers.set(t,n),this._dataProducerPromises.delete(t),n)).catch(n=>{throw this._dataProducerPromises.delete(t),n});return this._dataProducerPromises.set(t,s),s}_awaitDataChannelOpen(t){if(t.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let e=t.readyState;return e==="open"?Promise.resolve(t):e==="closing"||e==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${e} \u2014 cannot deliver data-up payloads`)):new Promise((r,s)=>{let n=()=>{c(),r(t)},i=u=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${u.message}`))},o=()=>{c(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},a=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${QU}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},QU),c=()=>{clearTimeout(a),t.off("open",n),t.off("error",i),t.observer.off("close",o)},d=u=>{c();try{t.close()}catch{}s(u)};t.on("open",n),t.on("error",i),t.observer.on("close",o)})}_dispatchStreamData(t,e){for(let r of this._streamDataHandlers.get(t)??[])r(e)}_streamNameFromLabel(t){if(t)return t.startsWith("stream:")?t.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(t){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${t}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(t,e){this._requireMediaSupport("addTrack"),await this._publishTrack(t,e)}async _publishTrack(t,e){let r=t.kind==="video",s=r?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===t)return;await s.replaceTrack({track:t}),this._rememberPublishIntent(r,t,e);return}if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");let n=await this._sendTransport.produce({track:t,...r?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...e?{appData:{name:e}}:{}});r?this._videoProducer=n:this._audioProducer=n,this._rememberPublishIntent(r,t,e)}_rememberPublishIntent(t,e,r){let s={track:e,...r!==void 0?{name:r}:{}};t?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){if(this._publishedAudio=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(t,e){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(t,e)}stopVideo(){if(this._publishedVideo=null,this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(t,e){this._send({type:"stream.seek",stream:t,target:e})}async _handleMessage(t){switch(t.type){case"routerRtpCapabilities":await this._onRouterCapabilities(t.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(t);break;case"createSendTransport":await this._onCreateSendTransport(t);break;case"consume":await this._onConsume(t);break;case"consumerClosed":this._closeConsumer(t.consumerId);break;case"producerClosed":this._closeConsumersByProducer(t.producerId);break;case"consumerPaused":this._consumers.get(t.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(t.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(t);break;case"produced":if(this._pendingProduce){let e=this._pendingProduce;this._pendingProduce=null,clearTimeout(e.timeoutId),e.resolve(t.id)}break;case"dataProduced":{let e=t.label,r=e?this._pendingDataProduce.get(e):void 0;r&&e&&(this._pendingDataProduce.delete(e),r.resolve(t.id));break}case"consumeData":await this._onConsumeData(t);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(t);break;case"stream.seeked":this._onStreamSeeked(t);break;case"error":this._onServerError(t);break;default:this._emitter.emit("signal",t);break}}_onServerError(t){let e=typeof t.message=="string"?t.message:"signaling error",r=typeof t.code=="string"?t.code:void 0;if(/connect\(\) already called/i.test(e)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:e,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(e));return}if(r==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(e),r);return}console.warn("[urun] signaling error from server:",e)}_onStreamSeeked(t){let e=typeof t.stream=="string"?t.stream:void 0;if(!e)return;let r=t.target,s=r==="live"?"live":typeof r=="number"?r:Number(r);this._emitter.emit("seeked",e,s)}_onStatus(t){let e=t.request_id??t.requestId;e&&(this._requestId=e);let r=typeof t.status=="string"?t.status:void 0,s=(r?gee[r]:void 0)??"provisioning",n=df(s);if(this._liveReached&&!n||df(this._phase.name))return;r!==void 0&&(this._lastServerStatus=r);let i=t.queue_position??t.queuePosition,o=t.queue_depth??t.queueDepth,a=typeof i=="number"&&typeof o=="number";if(s==="expired"){let c=typeof t.reason=="string"&&t.reason?t.reason:this._endsAt!==null?"session reached its maximum length":"session expired";this._setPhase("expired",{error:{reason:c,code:r,kind:"expired"}});return}if(s==="error"){let c=typeof t.reason=="string"&&t.reason?t.reason:r??"admission failed";this._setPhase("error",{error:{reason:c,code:r,kind:r==="error"?"runtime-failed":"create-failed"}});return}if(s==="ended"){this._pastDeadline()?this._setPhase("expired",{error:{reason:"session reached its maximum length",code:r,kind:"expired"}}):this._setPhase("ended");return}if(s==="queued"){this._setPhase("queued",a?{queue:{position:i,depth:o}}:void 0);return}if(s==="connecting"){this._setPhase("connecting");return}this._setPhase("provisioning")}async _onRouterCapabilities(t){hf()&&await P1();let e=JZ();if(e){this._mediaUnavailableReason=e,this._mediaVerdictResolve(e);return}this._mediaVerdictResolve(null);let r=XZ(),s=new nee.Device(r?{handlerName:r}:void 0);await s.load({routerRtpCapabilities:t}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(t){this._device&&this._buildRecvTransport(t)}_buildRecvTransport(t){if(!this._device)return;let e=t.iceCandidates,r=this._device.createRecvTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:e,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??rM});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;r.on("connect",({dtlsParameters:n},i,o)=>{try{this._send({type:"connectTransport",transportId:r.id,dtlsParameters:n}),i()}catch(a){o(a)}}),r.on("connectionstatechange",n=>{if(s===this._generation){if(n==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(r);return}if(!(this._intentionalDisconnect&&n==="closed")&&(n==="failed"||n==="disconnected")){if(this._tryRestartRecvIce())return;n==="failed"&&this._emitError(new Error(`media transport ${n}`),n),this._renegotiate()}}}),this._recvTransport=r}async _reportSelectedCandidatePair(t){let e=null;if(typeof t.getStats=="function")try{e=await t.getStats()}catch{}if(this._recvTransport!==t||(this._selectedCandidatePair=vee(e),this._candidatePairDiagnosticEmitted))return;let r=Object.values(this._selectedCandidatePair).some(s=>s!==null);r&&(this._candidatePairDiagnosticEmitted=!0),this._emitDiagnostic({level:r?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let t=this._recvTransport;return!t||t.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=eM?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_trySendIceRestart(){let t=this._sendTransport;return!t||t.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=eM?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_requestIceRestart(t){this._send({type:"restartIce",transportId:t})}_onIceRestarted(t){let e=t.transportId??t.id,r=t.iceParameters;if(!r)return;let s=!!this._recvTransport&&this._recvTransport.id===e,n=!s&&!!this._sendTransport&&this._sendTransport.id===e,i=s?this._recvTransport:n?this._sendTransport:null;i&&(Promise.resolve(i.restartIce({iceParameters:r})).catch(o=>{this._emitter.emit("error",o instanceof Error?o:new Error(String(o)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():n&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let t=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},tM)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let t=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},tM)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(t){if(!this._device)return;let e=this._device.createSendTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:t.iceCandidates,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??rM});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let r=this._generation;e.on("connect",({dtlsParameters:s},n,i)=>{try{this._send({type:"connectSendTransport",transportId:e.id,dtlsParameters:s}),n()}catch(o){i(o)}}),e.on("produce",({kind:s,rtpParameters:n,appData:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=i&&typeof i.name=="string"?i.name:void 0,d=setTimeout(()=>{let u=this._pendingProduce;if(!u||u.timeoutId!==d)return;this._pendingProduce=null;let l=new hA(s,{stream:c,timeoutMs:pm});this._setPhase("error",{error:{reason:l.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",l),u.reject(l)},pm);this._pendingProduce={timeoutId:d,resolve:u=>{o({id:u})},reject:a};try{this._send(c?{type:"produce",kind:s,name:c,rtpParameters:n}:{type:"produce",kind:s,rtpParameters:n})}catch(u){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),a(u)}}),e.on("producedata",({sctpStreamParameters:s,label:n,protocol:i},o,a)=>{try{n&&this._pendingDataProduce.set(n,{resolve:c=>o({id:c}),reject:a}),this._send({type:"produceData",sctpStreamParameters:s,label:n,protocol:i})}catch(c){n&&this._pendingDataProduce.delete(n),a(c)}}),e.on("connectionstatechange",s=>{if(r===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=e,this._settleSendTransportWaiters(e),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let t=this._publishedAudio;if(t&&t.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(t.track,t.name)}catch(r){console.warn("[urun] republish: mic re-produce after reconnect failed",r)}else t&&t.track.readyState==="ended"&&console.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let e=this._publishedVideo;if(e&&e.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(e.track,e.name)}catch(r){console.warn("[urun] republish: camera re-produce after reconnect failed",r)}else e&&e.track.readyState==="ended"&&console.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(t){if(!this._recvTransport)return;let e=t.label,r=this._streamNameFromLabel(e);if(!r)return;let s=await this._recvTransport.consumeData({id:t.id,dataProducerId:t.dataProducerId,sctpStreamParameters:t.sctpStreamParameters,label:e,protocol:t.protocol});this._dataConsumers.set(r,s),s.on("message",o=>{try{let a=typeof o=="string"?new TextEncoder().encode(o):new Uint8Array(o);this._dispatchStreamData(r,see(a))}catch(a){this._emitter.emit("error",a instanceof Error?a:new Error(String(a)))}});let n=!1,i=()=>{n||s.closed||(n=!0,this._send({type:"dataConsumerReady",id:t.id}))};s.readyState==="open"?i():s.on("open",i)}async _onConsume(t){if(!this._recvTransport)return;let e=this._generation,r=await this._recvTransport.consume({id:t.id,producerId:t.producerId,kind:t.kind,rtpParameters:t.rtpParameters});this._consumers.set(r.id,r),this._tracks.set(r.track.id,r.track),r.kind==="audio"&&this._capAudioJitterBuffer(r);let s=t.streamName??t.label;s&&this._tracksByName.set(s,r.track),r.track.addEventListener?.("unmute",()=>{e!==this._generation||this._intentionalDisconnect||this._isTerminalPhase()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",r.track);let n=r.id;r.track.addEventListener("ended",()=>{e!==this._generation||this._intentionalDisconnect||this._closeConsumer(n)},{once:!0}),this._send({type:"resumeConsumer",consumerId:r.id}),this._startMediaProbe()}_audioJitterBufferTargetMs(){let t=this._options.audioPlayout?.jitterBufferTargetMs;return t===void 0?lee:t}_capAudioJitterBuffer(t){let e=this._audioJitterBufferTargetMs();if(!Number.isFinite(e)){this._emitDiagnostic({level:"warning",kind:"audio-jitter-buffer-invalid",message:`audioPlayout.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(e)}. No jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:String(e)}});return}if(e<=0)return;let r=t.rtpReceiver;if(!r)return;let s=[];if("jitterBufferTarget"in r&&(r.jitterBufferTarget=e,s.push("jitterBufferTarget")),"playoutDelayHint"in r&&(r.playoutDelayHint=e/1e3,s.push("playoutDelayHint")),s.length===0){this._emitDiagnostic({level:"debug",kind:"audio-jitter-buffer-unsupported",message:"Audio receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing audio playout delay is unbounded on this engine.",detail:{consumerId:t.id,targetMs:e}});return}this._emitDiagnostic({level:"debug",kind:"audio-jitter-buffer-capped",message:`Audio receiver jitter buffer capped at ${e}ms.`,detail:{consumerId:t.id,targetMs:e,applied:s}})}_closeConsumer(t){let e=this._consumers.get(t);if(!e)return;this._consumers.delete(t);let r=e.track;try{e.close()}catch{}if(r){this._tracks.delete(r.id);for(let[s,n]of this._tracksByName)n===r&&this._tracksByName.delete(s)}}_closeConsumersByProducer(t){for(let[e,r]of this._consumers)r.producerId===t&&this._closeConsumer(e)}_mediaPollMs(){let t=this._options.mediaLiveness?.pollMs;return t===void 0?cee:t}_firstFrameWindowMs(){let t=this._options.mediaLiveness?.stallTimeoutMs;return t===void 0?dee:t}_startMediaProbe(){let t=this._mediaPollMs();if(t<=0||this._mediaProbeTimer)return;let e=this._generation;this._mediaProbeTimer=setInterval(()=>{e!==this._generation||this._intentionalDisconnect||this._isTerminalPhase()||this._sampleMediaArrival(e)},t)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(t){if(this._consumers.size===0)return;let e=Array.from(this._consumers.entries()),r=await Promise.all(e.map(async([o,a])=>[o,await _ee(a)]));if(t!==this._generation||this._intentionalDisconnect||this._isTerminalPhase())return;for(let o of this._joinProbes.keys())this._consumers.has(o)||this._joinProbes.delete(o);let s=Date.now();!this._liveReached&&r.some(([,o])=>o.total>0)&&this._setPhase("live");let n=null,i=!1;for(let[o,a]of r){if(a.total<=0){i=!0;continue}let c=this._joinProbes.get(o);if(c||(c={firstBytesAt:s,startSample:a,settled:!1},this._joinProbes.set(o,c)),!c.settled){if(a.framesDecoded===null){c.settled=!0;continue}if(a.framesDecoded>0){c.settled=!0;continue}if(s-c.firstBytesAt>=this._firstFrameWindowMs()){n??={id:o,probe:c,sample:a};continue}i=!0}}if(n&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let o=this._firstFrameWindowMs(),a=wee(n.probe.startSample,n.sample),c=a.lossPct!==null&&a.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${o/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${c}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:n.id,firstFrameWindowMs:o,inboundTotal:n.sample.total,framesDecoded:n.sample.framesDecoded,...bee(n.sample),...a,likelyCause:a.lossPct!==null&&a.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!i&&!n&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isTerminalPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isTerminalPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let t=this._recvTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let e=this._sendTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(t,e=!1){if(this._intentionalDisconnect||this._isTerminalPhase()||this._reconnectTimer)return;if(this._reconnectAttempts>=YU){this._setState("failed"),this._emitError(new Error(`Failed after ${YU} attempts`));return}let r=e?0:XU[Math.min(this._reconnectAttempts,XU.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(t??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(t)}},r)}_connectUrls(){let t=[],e=r=>{if(!r)return;let s=sM(r)!==void 0,n=this._sessionId&&!s?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r;t.includes(n)||t.push(n)};e(this._options.url);for(let r of this._options.fallbackUrls??[])e(r);return t}_connectOnce(t,e,r){return new Promise((s,n)=>{let i=!1,o=!1,a=null,c=new WebSocket(t);this._ws=c;let d=()=>this._ws!==c||e!==this._generation,u=f=>{o||(o=!0,a&&clearTimeout(a),this._cancelPendingDial===l&&(this._cancelPendingDial=null),n(f))},l=f=>{try{c.close()}catch{}u(f)};this._cancelPendingDial=l,a=setTimeout(()=>{try{c.close()}catch{}u(new Error("TransportSession: connect timed out"))},aee),c.onopen=()=>{if(!o){if(d()){try{c.close()}catch{}u(new Error("TransportSession: connect superseded during dial"));return}i=!0,a&&clearTimeout(a),this._connectedUrl=t,this._multiplexer=new cA(c),c.send(JSON.stringify(this._startMessage(r))),this._scheduleReconnectBudgetReset(),this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),o=!0,this._cancelPendingDial===l&&(this._cancelPendingDial=null),s()}},c.onerror=()=>{i||u(new Error("WebSocket connection error"))},c.onclose=()=>{if(!i){u(new Error("WebSocket closed before connecting"));return}if(!d()&&(this._clearReconnectBudgetReset(),a&&clearTimeout(a),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&!df(this._phase.name)){this._setPhase("expired",{error:{reason:"session reached its maximum length",kind:"expired"}}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isTerminalPhase()&&this._attemptReconnect(r)}},c.onmessage=f=>{if(!(this._ws!==c||e!==this._generation)&&typeof f.data=="string")try{this._handleMessage(JSON.parse(f.data))}catch(h){this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))}}})}_startMessage(t){let e={type:"start",video:t?.video??{width:854,height:480,frameRate:16}};return t?.prompt&&(e.prompt=t.prompt),t?.cameraControl&&(e.camera_control=t.cameraControl),t?.args&&(e.args=t.args),t?.app&&(e.app=t.app),t?.functionName&&(e.function=t.functionName),t?.role&&(e.role=t.role),this._options.orgId&&(e.orgId=this._options.orgId),this._options.jwt&&(e.jwt=this._options.jwt),this._options.authProvider&&(e.authProvider=this._options.authProvider),e}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let t=this._ws;this._ws=null,t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{t.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},pee))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let t of this._dataProducers.values())try{t.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let t of this._dataConsumers.values())try{t.close()}catch{}this._dataConsumers.clear();for(let t of this._pendingDataProduce.values())try{t.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._resetJoinProbes();for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(t){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(JSON.stringify(t))}_setState(t){this._state!==t&&(this._state=t,this._emitter.emit("stateChange",t))}_isTerminalPhase(){return this._phase.name==="ended"||this._phase.name==="expired"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_setPhase(t,e){t==="live"&&(this._liveReached=!0);let r={name:t};e?.queue&&(r.queue=e.queue),e?.runtime&&(r.runtime=e.runtime),gA(t)?(this._wakingSince??=Date.now(),r.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(r.requestId=this._requestId),this._sessionId&&(r.sessionId=this._sessionId),this._endsAt!==null&&(r.endsAt=this._endsAt),e?.error&&(r.error=e.error),this._phase=r,this._isTerminalPhase()&&(this._stopMediaProbe(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)),this._emitter.emit("phase",r)}reportAdmission(t){if(t.requestId&&(this._requestId=t.requestId),this._lastServerStatus=t.status,this._liveReached||df(this._phase.name))return;let{runtime:e,queue:r}=t;if(e?.state==="unavailable"){this._setPhase("unavailable",{runtime:e});return}if(e?.state==="starting"){this._setPhase("provisioning",{runtime:e});return}if(e?.state==="busy"||t.status==="queued"){this._setPhase("queued",{queue:r,runtime:e});return}this._setPhase("provisioning")}_emitError(t,e){this._setPhase("error",{error:{reason:t.message,code:e,kind:"transport-failed"}}),this._emitter.emit("error",t)}reportAllocationFailure(t,e){this._setPhase("error",{error:{reason:t.message,code:"allocation-failed",kind:"create-failed",httpStatus:e}}),this._emitter.emit("error",t)}};function nM(t){return new Promise(e=>setTimeout(e,t))}function yee(){return B1()}var MM=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount"];function xee(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null}}function bee(t){return Object.fromEntries(MM.map(e=>[e,t[e]]))}function iM(t,e){return t===null||e===null||e<t?null:e-t}function wee(t,e){let r=t.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-t.packetsLost:null,s=iM(t.packetsReceived,e.packetsReceived),n=iM(t.nackCount,e.nackCount),i=r===null?null:Math.max(0,r),o=i!==null&&s!==null?i+s:0;return{packetsLostWindow:r,packetsReceivedWindow:s,nackCountWindow:n,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function jM(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function vee(t){let e=new Map;FM(t,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let r=Array.from(e.values()).find(a=>a.type==="transport"),s=typeof r?.selectedCandidatePairId=="string"?r.selectedCandidatePairId:null,n=(s?e.get(s):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!n)return jM();let i=typeof n.localCandidateId=="string"?e.get(n.localCandidateId):void 0,o=typeof n.remoteCandidateId=="string"?e.get(n.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function FM(t,e){let r=s=>{s&&typeof s=="object"&&e(s)};if(t instanceof Map)for(let[s,n]of t.entries()){if(!n||typeof n!="object")continue;let i=n;e(typeof i.id=="string"?i:{...i,id:s})}else(Array.isArray(t)||t&&typeof t.forEach=="function")&&t.forEach(r)}async function _ee(t){let e=xee();if(typeof t.getStats!="function")return e;let r;try{r=await t.getStats()}catch{return e}return FM(r,s=>{if(s.type==="inbound-rtp"){let n=typeof s.bytesReceived=="number"?s.bytesReceived:0,i=typeof s.packetsReceived=="number"?s.packetsReceived:0;if(e.total+=n+i,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),s.kind==="video"||s.mediaType==="video"){typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let o of MM)typeof s[o]=="number"&&(e[o]=(e[o]??0)+s[o])}}}),e}function See(t){if(!t||typeof t!="object")return;let e=t.epoch,r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:void 0}var Eee=1;function HM(t){let e=new URL(t);return`${e.protocol}//${e.host}/doc`}var Cee=2500,Tee=3e4,Aee=1e4,kee=3;function $M(t){let e=t.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(r,s,n)=>{let i=`${t.sessionId}/${r}`,o=typeof t.token=="function"?t.token:null,a=typeof t.token=="string"?t.token:void 0,c=t.maxBackoffTimeMs??Cee,d=t.dialTimeoutMs??Tee,u=new xg(t.serverUrl,i,s,{awareness:n,params:{dsv:String(Eee),...a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:c,resyncInterval:Aee,connect:o===null}),l=!1,f=0,h=!1,m=K=>{h||(h=!0,console.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,K))},v=()=>{if(!o)return;let K=++f;try{let I=o();if(typeof I=="string"){u.params.token=I,h=!1;return}if(I&&typeof I.then=="function")return I.then(G=>{K===f&&typeof G=="string"&&(u.params.token=G,h=!1)},G=>{m(G)})}catch(I){m(I)}},p={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},x=new Set,w=!1,E=()=>{let K={...p};for(let I of[...x])I(K)},P=null,j=()=>{P!==null&&(clearTimeout(P),P=null)},T=()=>{j(),P=setTimeout(()=>{if(P=null,!l&&u.wsconnecting&&u.ws)try{u.ws.close()}catch{}},d)},k=null,_=()=>{k!==null&&(clearTimeout(k),k=null)},A=()=>{_(),k=setTimeout(()=>{if(k=null,!l&&u.shouldConnect&&!u.wsconnected&&!u.wsconnecting&&u.ws===null)try{u.connect()}catch(K){w||(w=!0,console.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,K)),A()}},c+500)},M=({status:K})=>{if(K==="connecting"){_(),T();return}if(K==="connected"){j(),_(),p={...p,connected:!0},E();return}p.connected&&(p={...p,connected:!1},E())},V=K=>{K&&(w&&(console.info(`[urun] doc connection recovered for room ${i}`),w=!1),p.consecutiveFailures!==0&&(p={...p,consecutiveFailures:0},E()))},Y=K=>{j(),p={connected:!1,consecutiveFailures:p.consecutiveFailures+1,lastCloseCode:K?K.code:null,lastCloseReason:K&&K.reason?K.reason:null},!w&&p.consecutiveFailures>=kee&&(w=!0,console.error(`[urun] doc connection failing for room ${i}: ${p.consecutiveFailures} consecutive failures (last close ${p.lastCloseCode===null?"by provider liveness reap":`code ${p.lastCloseCode}`}${p.lastCloseReason?`, reason "${p.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),E(),v(),A()};u.on("status",M),u.on("sync",V),u.on("connection-close",Y),u.wsconnecting?T():u.wsconnected&&(p={...p,connected:!0});let H=!1,F=null;if(o!==null){let K=v();if(K){H=!0;let I=()=>{H&&(H=!1,F!==null&&(clearTimeout(F),F=null),l||u.connect())};F=setTimeout(I,d),K.then(I)}else u.connect()}return{get awareness(){return u.awareness},get synced(){return u.synced},onSync(K){let I=G=>K(G);return u.on("sync",I),()=>u.off("sync",I)},onConnectionState(K){return x.add(K),K({...p}),()=>x.delete(K)},ensureConnected(){!u.wsconnected&&!H&&u.connect()},destroy(){l=!0,F!==null&&(clearTimeout(F),F=null),j(),_(),u.off("status",M),u.off("sync",V),u.off("connection-close",Y),x.clear(),u.destroy()}}}}var Iee=class{constructor(t,e,r){this._name=t,this._doc=e,this.awareness=r}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(t){return this._syncHandlers.add(t),()=>this._syncHandlers.delete(t)}onConnectionState(t){return this._stateHandlers.add(t),t({...this._lastState}),()=>this._stateHandlers.delete(t)}attach(t){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=t(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(e=>{for(let r of[...this._syncHandlers])r(e)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(e=>{this._lastState=e;for(let r of[...this._stateHandlers])r(e)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let e of[...this._stateHandlers])e({...this._lastState})}if(this._inner.synced)for(let e of[...this._syncHandlers])e(!0)}}ensureConnected(){this._inner?.ensureConnected?.()}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},VM=class{_target=null;_bridges=[];connect=(t,e,r)=>{let s=new Iee(t,e,r);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(t){if(this._target!==t){this._target=t,this._bridges=this._bridges.filter(e=>!e.destroyed);for(let e of this._bridges)e.attach(t)}}};function ym(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var w1="$bytes";function Ree(t){return t instanceof Uint8Array||t instanceof ArrayBuffer}function Pee(t){if(!ym(t))return!1;let e=Object.keys(t);return e.length===1&&e[0]===w1&&typeof t[w1]=="string"}function Bee(t){return t instanceof ArrayBuffer?new Uint8Array(t):t}function Dee(t){if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Nee(t){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(t,"base64"));let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r}function iA(t){if(Ree(t))return{[w1]:Dee(Bee(t))};if(Array.isArray(t))return t.map(iA);if(ym(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=iA(s);return e}return t}function hm(t){if(Pee(t))return Nee(t[w1]);if(Array.isArray(t))return t.map(hm);if(ym(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=hm(s);return e}return t}var qM=Symbol("urun:doc:path-absent");function Oee(t,e){let r=e.split("."),s=t;for(let n of r){if(s===null||typeof s!="object"||!(n in s))return qM;s=s[n]}return s}function Lee(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function oA(t,e){for(let[r,s]of Object.entries(e))if(ym(s)){let n=t.get(r);if(!(n instanceof qo)){let i=n;n=new qo,t.set(r,n),ym(i)&&oA(n,i)}oA(n,s)}else{if(Lee(t.get(r),s))continue;t.set(r,s)}}var Uee=Symbol("urun:doc:local"),zM=class{_doc=new uc;_root=this._doc.getMap("session");_awareness=new wl(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(t,e,r){this._key=t,this._sessionId=e,this._root.observeDeep(this._observer),r?(this._connection=r(t,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(t){this._sessionId=t}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}onConnectionState(t){return this._connection?.onConnectionState?this._connection.onConnectionState(t):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(t){return this._synced?(t(),()=>{}):(this._syncWaiters.add(t),()=>this._syncWaiters.delete(t))}set(t){t=iA(t),this.applyPatch(t)}get(t,e){let r=this.snapshot();if(!t)return hm(r);let s=Oee(r,t);return s===qM?e:hm(s)}on(t,e){return this._listeners.add(e),()=>this._listeners.delete(e)}text(t){let e=this._texts.get(t);return e||(e=new Mee(this._doc.getText(`text:${t}`)),this._texts.set(t,e)),e}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let t of this._texts.values())t.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let t=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let e of t)e()}applyPatch(t){this._doc.transact(()=>{oA(this._root,t)},Uee)}snapshot(){return this._root.toJSON()}notify(){let t=hm(this.snapshot());for(let e of this._listeners)e(t)}},Mee=class{constructor(t){this._ytext=t,this._observer=e=>{for(let r of e.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let n of this._delta)n(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(t){t.length!==0&&this._ytext.insert(this._ytext.length,t)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(t,e){return this._delta.add(e),()=>this._delta.delete(e)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function KM(t){return{get clientId(){return t.clientID},set(e){t.setLocalState(e)},setField(e,r){t.setLocalStateField(e,r)},getLocal(){return t.getLocalState()??null},getStates(){return t.getStates()},on(e,r){let s=()=>r(t.getStates());return t.on("change",s),s(),()=>t.off("change",s)}}}g();g();g();g();function WM(t){let e=t.length,r=0,s=0;for(;s<e;){let n=t.charCodeAt(s++);if((n&4294967168)===0){r++;continue}else if((n&4294965248)===0)r+=2;else{if(n>=55296&&n<=56319&&s<e){let i=t.charCodeAt(s);(i&64512)===56320&&(++s,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?r+=3:r+=4}}return r}function jee(t,e,r){let s=t.length,n=r,i=0;for(;i<s;){let o=t.charCodeAt(i++);if((o&4294967168)===0){e[n++]=o;continue}else if((o&4294965248)===0)e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&i<s){let a=t.charCodeAt(i);(a&64512)===56320&&(++i,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128):(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128)}e[n++]=o&63|128}}var Fee=new TextEncoder,Hee=50;function $ee(t,e,r){Fee.encodeInto(t,e.subarray(r))}function GM(t,e,r){t.length>Hee?$ee(t,e,r):jee(t,e,r)}var Vee=4096;function _A(t,e,r){let s=e,n=s+r,i=[],o="";for(;s<n;){let a=t[s++];if((a&128)===0)i.push(a);else if((a&224)===192){let c=t[s++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){let c=t[s++]&63,d=t[s++]&63;i.push((a&31)<<12|c<<6|d)}else if((a&248)===240){let c=t[s++]&63,d=t[s++]&63,u=t[s++]&63,l=(a&7)<<18|c<<12|d<<6|u;l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|l&1023),i.push(l)}else i.push(a);i.length>=Vee&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var qee=new TextDecoder,zee=200;function Kee(t,e,r){let s=t.subarray(e,e+r);return qee.decode(s)}function XM(t,e,r){return r>zee?Kee(t,e,r):_A(t,e,r)}g();g();var Yd=class{type;data;constructor(e,r){this.type=e,this.data=r}};g();g();var Cs=class t extends Error{constructor(e){super(e);let r=Object.create(t.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};g();function YM(t,e,r){let s=r/4294967296,n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function D1(t,e,r){let s=Math.floor(r/4294967296),n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function N1(t,e){let r=t.getInt32(e),s=t.getUint32(e+4);return r*4294967296+s}function JM(t,e){let r=t.getUint32(e),s=t.getUint32(e+4);return r*4294967296+s}var Wee=-1,Gee=4294967296-1,Xee=17179869184-1;function Yee({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Xee)if(e===0&&t<=Gee){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{let r=t/4294967296,s=t&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|r&3),i.setUint32(4,s),n}else{let r=new Uint8Array(12),s=new DataView(r.buffer);return s.setUint32(0,e),D1(s,4,t),r}}function Jee(t){let e=t.getTime(),r=Math.floor(e/1e3),s=(e-r*1e3)*1e6,n=Math.floor(s/1e9);return{sec:r+n,nsec:s-n*1e9}}function Qee(t){if(t instanceof Date){let e=Jee(t);return Yee(e)}else return null}function Zee(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let r=e.getUint32(0),s=e.getUint32(4),n=(r&3)*4294967296+s,i=r>>>2;return{sec:n,nsec:i}}case 12:{let r=N1(e,4),s=e.getUint32(0);return{sec:r,nsec:s}}default:throw new Cs(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function ete(t){let e=Zee(t);return new Date(e.sec*1e3+e.nsec/1e6)}var QM={type:Wee,encode:Qee,decode:ete};var pf=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(QM)}register({type:e,encode:r,decode:s}){if(e>=0)this.encoders[e]=r,this.decoders[e]=s;else{let n=-1-e;this.builtInEncoders[n]=r,this.builtInDecoders[n]=s}}tryToEncode(e,r){for(let s=0;s<this.builtInEncoders.length;s++){let n=this.builtInEncoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=-1-s;return new Yd(o,i)}}}for(let s=0;s<this.encoders.length;s++){let n=this.encoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=s;return new Yd(o,i)}}}return e instanceof Yd?e:null}decode(e,r,s){let n=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return n?n(e,r,s):new Yd(r,e)}};g();function tte(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Sm(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):tte(t)?new Uint8Array(t):Uint8Array.from(t)}var rte=100,ste=2048,O1=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pf.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??rte,this.initialBufferSize=e?.initialBufferSize??ste,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){let r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){let r=new ArrayBuffer(e),s=new Uint8Array(r),n=new DataView(r);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let s=WM(e);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),GM(e,this.bytes,this.pos),this.pos+=s}encodeObject(e,r){let s=this.extensionCodec.tryToEncode(e,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let s=Sm(e);this.writeU8a(s)}encodeArray(e,r){let s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(`Too large array: ${s}`);for(let n of e)this.doEncode(n,r+1)}countWithoutUndefined(e,r){let s=0;for(let n of r)e[n]!==void 0&&s++;return s}encodeMap(e,r){let s=Object.keys(e);this.sortKeys&&s.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of s){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){let s=e.data(this.pos+6),n=s.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(s);return}let r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),YM(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),D1(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function SA(t,e){return new O1(e).encodeSharedRef(t)}g();g();g();function L1(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}g();var nte=16,ite=16,U1=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=nte,r=ite){this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,s){let n=this.caches[s-1];e:for(let i of n){let o=i.bytes;for(let a=0;a<s;a++)if(o[a]!==e[r+a])continue e;return i.str}return null}store(e,r){let s=this.caches[e.length-1],n={bytes:e,str:r};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,r,s){let n=this.find(e,r,s);if(n!=null)return this.hit++,n;this.miss++;let i=_A(e,r,s),o=Uint8Array.prototype.slice.call(e,r,r+s);return this.store(o,i),i}};var EA="array",Tm="map_key",ej="map_value",ote=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Cs("The type of key must be string or number but "+typeof t)},CA=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let r=this.getUninitializedStateFromPool();r.type=EA,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){let r=this.getUninitializedStateFromPool();r.type=Tm,r.readCount=0,r.size=e,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===EA){let s=e;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(e.type===Tm||e.type===ej){let s=e;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Cm=-1,TA=new DataView(new ArrayBuffer(0)),ate=new Uint8Array(TA.buffer);try{TA.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var ZM=new RangeError("Insufficient data"),cte=new U1,M1=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=TA;bytes=ate;headByte=Cm;stack=new CA;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pf.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:cte,this.mapKeyConverter=e?.mapKeyConverter??ote}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Cm,this.stack.reset()}setBuffer(e){let r=Sm(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Cm&&!this.hasRemaining(1))this.setBuffer(e);else{let r=this.bytes.subarray(this.pos),s=Sm(e),n=new Uint8Array(r.length+s.length);n.set(r),n.set(s,r.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:r,pos:s}=this;return new RangeError(`Extra ${r.byteLength-s} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,s;for await(let a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:n,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${L1(n)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let s=r,n=-1;for await(let i of e){if(r&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else{let n=e-160;r=this.decodeString(n,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){let n=this.lookU8();r=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();r=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();r=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===196){let n=this.lookU8();r=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();r=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();r=this.decodeBinary(n,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();r=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();r=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();r=this.decodeExtension(n,4)}else throw new Cs(`Unrecognized type byte: ${L1(e)}`);this.complete();let s=this.stack;for(;s.length>0;){let n=s.top();if(n.type===EA)if(n.array[n.position]=r,n.position++,n.position===n.size)r=n.array,s.release(n);else continue e;else if(n.type===Tm){if(r==="__proto__")throw new Cs("The key __proto__ is not allowed");n.key=this.mapKeyConverter(r),n.type=ej;continue e}else if(n.map[n.key]=r,n.readCount++,n.readCount===n.size)r=n.map,s.release(n);else{n.key=null,n.type=Tm;continue e}}return r}}readHeadByte(){return this.headByte===Cm&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Cm}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Cs(`Unrecognized array type byte: ${L1(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Cs(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Cs(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new Cs(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw ZM;let s=this.pos+r,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,s,e):n=XM(this.bytes,s,e),this.pos+=r+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Tm:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new Cs(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw ZM;let s=this.pos+r,n=this.bytes.subarray(s,s+e);return this.pos+=r+e,n}decodeExtension(e,r){if(e>this.maxExtLength)throw new Cs(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let s=this.view.getInt8(this.pos+r),n=this.decodeBinary(e,r+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=JM(this.view,this.pos);return this.pos+=8,e}readI64(){let e=N1(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function AA(t,e){return new M1(e).decode(t)}var pIe=globalThis.require??(0,pj.createRequire)(N),dte=15e3,lte=45e3,ute=12e4,mj="platform",gj="activation",yj="desired.activation";function xj(t){if(typeof t=="string"&&t.length>0)return t;if(t&&typeof t=="object"){let e=t.note;if(typeof e=="string"&&e.length>0)return e}}var fte=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],bj=class{constructor(t){this._options=t,this._offPhase=t.onPhase(e=>{if(!this._stopped)if(e?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(e?.name==="error"||e?.name==="ended"||e?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(t,e){if(this._stopped||this._watches.has(t))return;let r={name:t,stream:e,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(t,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(t){let e=this._watches.get(t);!e||e.done||this._settle(e)}onActivation(t){for(let e of this._watches.values())!e.done&&e.lastEvent&&t(e.lastEvent);return this._handlers.add(t),()=>this._handlers.delete(t)}dispose(){if(!this._stopped){this._stopped=!0;for(let t of this._watches.values())t.done||this._settle(t);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(t){let e=r=>{if(!(!r||t.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(t);r.addEventListener("unmute",s,{once:!0}),t.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(t)}};t.cleanups.push(t.stream.on("track",r=>e(r))),this._options.onData&&t.cleanups.push(this._options.onData(t.name,()=>this._firstMedia(t))),e(t.stream.track)}_arm(t){if(!(t.done||t.startedAt!==null||this._stopped)){t.startedAt=Date.now(),this._emit(t,"activating",0);for(let e of fte){let r=setTimeout(()=>{t.done||this._stopped||this._emit(t,e.state,Date.now()-t.startedAt)},e.afterMs);r.unref?.(),t.timers.push(r)}}}_firstMedia(t){if(t.done||this._stopped)return;let e=t.startedAt;this._settle(t),this._emit(t,"first-media",e===null?0:Date.now()-e)}_settle(t){t.done=!0;for(let e of t.timers)clearTimeout(e);t.timers=[];for(let e of t.cleanups.splice(0))e()}_emit(t,e,r){let s={state:e,elapsedMs:r,stream:t.name},n=xj(this._options.hint());n!==void 0&&(s.hint=n),t.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}},an=class extends Error{status;code;constructor(t,e,r=e>0?`http_${e}`:"runtime_artifacts_error",s){super(t),this.name="RuntimeArtifactsError",this.status=e,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},wj=class extends an{constructor(t="[urun] runtime artifacts: unauthorized",e="unauthorized"){super(t,401,e),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},vj=class extends an{constructor(t="[urun] runtime artifacts: not found",e="not_found"){super(t,404,e),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function NA(t){return{baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}function hte(t){return new j1(t)}var j1=class{_options;constructor(t){this._options=t}async list(t){let e=rj(await this._request(t,"")).artifacts;if(!Array.isArray(e))throw new an("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return e.map(tj)}async getDownloadUrl(t,e){let r=rj(await this._request(e,`/${encodeURIComponent(t)}/download`)),s=r.download_url;if(typeof s!="string"||!mte(s))throw new an("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:tj(r.artifact),downloadUrl:s}}async _request(t,e){let r=I1(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let n of r)try{return await this._requestFromBase(n,t,e)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof an&&gte(s.status))throw s}throw s??new an("[urun] runtime artifacts request failed",0)}async _requestFromBase(t,e,r){let s=`${Ss(t)}/api/sessions/${encodeURIComponent(e)}/artifacts${r}`,n=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(n)});if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await fetch(s,{method:"GET",headers:this._headers(n)}))}if(!i.ok){let{code:o,message:a}=await this._readError(i,t);throw yte(i.status,o,a)}try{return await i.json()}catch(o){throw new an(`[urun] runtime artifacts: invalid JSON response from ${Ss(t)}`,0,"bad_response",o)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(t){let e={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return t&&(e.Authorization=`Bearer ${t}`),e}async _readError(t,e){let r=Ss(e);try{let s=(await t.json()).error;if(s&&typeof s=="object"){let{code:n,message:i}=s;return{code:typeof n=="string"&&n.length>0?n:`http_${t.status}`,message:typeof i=="string"&&i.length>0?`[urun] runtime artifacts request failed at ${r}: ${i}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}}catch{}return{code:`http_${t.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}};function tj(t){if(!t||typeof t!="object")throw new an("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=t,r=Lo(e,"artifact_id")||Lo(e,"id"),s=Lo(e,"filename"),n=Lo(e,"kind"),i=Lo(e,"status")||"ready",o=pte(e,"size_bytes"),a=Lo(e,"sha256");if(!r||!s||!n||o==null||!a)throw new an("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:r,kind:n,filename:s,contentType:Lo(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:Lo(e,"created_at"),expiresAt:Lo(e,"expires_at")}}function Lo(t,e){let r=t[e];return typeof r=="string"&&r.length>0?r:void 0}function pte(t,e){let r=t[e];return typeof r=="number"&&Number.isFinite(r)&&Number.isInteger(r)&&r>=0?r:void 0}function mte(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function gte(t){return t===401||t===403}function yte(t,e,r){return t===401?new wj(r,e):t===404?new vj(r,e):new an(r,t,e)}function rj(t){if(!t||typeof t!="object"||Array.isArray(t))throw new an("[urun] runtime artifacts: malformed response",0,"bad_response");return t}var Uo=class extends Error{status;code;constructor(t,e){super(t),this.name="RecordingsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},UA=class extends Uo{constructor(t="[urun] recordings: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},_j=class extends Uo{constructor(t="[urun] recordings: not found",e="not_found"){super(t,{status:404,code:e}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Sj=class extends Uo{constructor(t="[urun] recordings: retain requires a temp recording",e="retain_not_temp"){super(t,{status:409,code:e}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ej=class extends Uo{constructor(t="[urun] recordings: pin requires an active temp recording",e="pin_requires_active_temp"){super(t,{status:409,code:e}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Cj=class extends Uo{constructor(t="[urun] recordings: recording is permanent and locked",e="permanent_locked"){super(t,{status:409,code:e}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},H1=class extends Uo{constructor(t="[urun] recordings: invalid retention duration",e="bad_duration",r=400){super(t,{status:r,code:e}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function MA(t){return/^(\d+[smhdw])+$/.test(t)}function xte(t){if(t==="pin")return{action:"pin"};if(MA(t))return{action:"retain",duration:t};throw new H1(`[urun] recordings: "${t}" is not a duration or "pin"`)}function bte(t,e,r){let s=r||e||`HTTP ${t}`;if(t===401)return new UA(s,e??"unauthorized");if(t===404)return new _j(s,e??"not_found");if(t===400)return new H1(s,e??"bad_request",400);if(t===409)switch(e){case"retain_not_temp":return new Sj(s,e);case"pin_requires_active_temp":return new Ej(s,e);case"permanent_locked":return new Cj(s,e)}return new Uo(s,{status:t,code:e??`http_${t}`})}var jA=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(t){let e=(await this._request("GET","",{params:t?{session_id:t}:void 0})).recordings;return Array.isArray(e)?e:[]}async get(t){return this._one(await this._request("GET",`/${encodeURIComponent(t)}`))}async retain(t,e){if(!MA(e))throw new H1(`[urun] recordings: "${e}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(t)}/retain`,{body:{duration:e}}))}async pin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/pin`))}async unpin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/unpin`))}async permanent(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/permanent`))}async delete(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/delete`))}_one(t){let e=t.recording;if(!e||typeof e!="object")throw new Uo("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return e}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n,r.body);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n,r.body))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw bte(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r,s){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider);let i={method:e,headers:n};return s!==void 0&&(n["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(t,i)}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new UA("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function wte(t){return new jA(t)}var Tj="activity",Aj="visibility",vte=15e3,OA=["pointerdown","pointermove","keydown","wheel","touchstart"];function kj(t){let e=t.now??Date.now,r=t.windowTarget!==void 0?t.windowTarget:typeof window<"u"?window:null,s=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,n=!1,i,o=()=>{if(n)return;let l=e();if(!(i!==void 0&&l-i<15e3)){i=l;try{t.awareness.setLocalStateField(Tj,{at:l})}catch{}}},a=()=>{if(!(n||!s||s.visibilityState===void 0))try{t.awareness.setLocalStateField(Aj,s.visibilityState)}catch{}},c=()=>o(),d=()=>{a(),(!s||s.visibilityState===void 0||s.visibilityState==="visible")&&o()};if(r)for(let l of OA)r.addEventListener(l,c,{passive:!0,capture:!0});s&&s.addEventListener("visibilitychange",d);let u=null;return t.isProducing&&(u=setInterval(()=>{if(!n)try{t.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),a(),{touch:o,dispose(){if(!n){if(n=!0,r)for(let l of OA)r.removeEventListener(l,c,{capture:!0});s&&s.removeEventListener("visibilitychange",d),u&&(clearInterval(u),u=null)}}}}var _te=250;function Ij(t){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,r=()=>{if(document.visibilityState==="hidden")return;let s=Date.now();s-e<250||(e=s,t())};return document.addEventListener("visibilitychange",r),window.addEventListener("pageshow",r),window.addEventListener("focus",r),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pageshow",r),window.removeEventListener("focus",r)}}function Rj(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,r=s=>{s.persisted||e||(e=!0,t())};return window.addEventListener("pagehide",r),()=>{window.removeEventListener("pagehide",r)}}function Pj(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=r=>{t()&&(r.preventDefault(),r.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var sj="video/mp4";function Bj(t,e={}){let r=e.timesliceMs??1e3,s=null,n=null,i=!1,o=(a,c,d)=>{let u=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!u)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof u.isTypeSupported=="function"&&u.isTypeSupported(sj)?sj:void 0),f=new MediaStream([a]),h=new u(f,l?{mimeType:l}:void 0);s=h;let m=Promise.resolve();h.ondataavailable=v=>{let p=v.data;i||!p||p.size===0||(m=m.then(async()=>{let x=new Uint8Array(await p.arrayBuffer());i||c(x)}))},h.onstop=()=>{m.then(()=>{i||d()})},h.onerror=()=>{m.then(()=>{i||d()})},h.start(r)};return{start(a,c){if(s||i)return;let d=t.track();if(d){o(d,a,c);return}n=t.onTrack(u=>{!u||s||i||(n?.(),n=null,o(u,a,c))})},stop(){if(i)return;i=!0,n?.(),n=null;let a=s;if(s=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Ste(t){let e=t;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let r=t.getReader();return{next(){return r.read()},async return(){try{await r.cancel()}catch{}try{r.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Ete(t,e){let r=null,s=!1,n=!1,i=new ReadableStream({pull(o){s||(s=!0,r=t(e),r.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,r?.stop(),r=null}},new CountQueuingStrategy({highWaterMark:0}));return Ste(i)}var Dj=65536;function Nj(t){let e=SA(t),r=new Uint8Array(4+e.byteLength);return new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),r}var Oj=class{buf=new Uint8Array(0);push(t){if(t.byteLength>0){let r=new Uint8Array(this.buf.byteLength+t.byteLength);r.set(this.buf),r.set(t,this.buf.byteLength),this.buf=r}let e=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>Dj)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),e.push(AA(s))}return e}},F1=12,LA=1;function Lj(t){let e=t.getUint8(8);return{groupId:t.getUint32(0,!0),frameSeq:t.getUint32(4,!0),keyframe:(e&LA)===LA,fragIndex:t.getUint8(9),fragCount:t.getUint8(10)}}function Cte(t){let e=new Uint8Array(F1),r=new DataView(e.buffer);return r.setUint32(0,t.groupId,!0),r.setUint32(4,t.frameSeq,!0),r.setUint8(8,t.keyframe?LA:0),r.setUint8(9,t.fragIndex),r.setUint8(10,t.fragCount),r.setUint8(11,0),e}var Tte=100,Uj=class{constructor(t,e={}){this.cb=t,this.now=e.now??(()=>performance.now()),this.debounceMs=e.keyframeRequestDebounceMs??Tte}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(t){if(t.byteLength<F1)return;let e=Lj(new DataView(t.buffer,t.byteOffset));if(this.bytesInWindow+=t.byteLength,e.groupId<this.newestGroupSeen||(e.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e.groupId,this.needKeyframe=!0),e.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(e.frameSeq);if(r||(r={groupId:e.groupId,keyframe:e.keyframe,fragCount:e.fragCount,received:0,chunks:new Array(e.fragCount)},this.pending.set(e.frameSeq,r)),!r.chunks[e.fragIndex]){r.chunks[e.fragIndex]=t.subarray(F1),r.received++,r.received===r.fragCount&&(this.pending.delete(e.frameSeq),this.deliver(e.frameSeq,r));for(let s of this.pending.keys())s<e.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let t={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,t}deliver(t,e){if(this.needKeyframe&&!e.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(t!==this.newestFrameDelivered+1&&!e.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=e.chunks.reduce((i,o)=>i+o.byteLength,0),s=new Uint8Array(r),n=0;for(let i of e.chunks)s.set(i,n),n+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=t,this.framesDelivered++,this.cb.onFrame({seq:t,groupId:e.groupId,keyframe:e.keyframe,data:s})}requestKeyframe(){let t=this.now();t-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=t,this.cb.onKeyframeNeeded())}},Ate=/^avc[13]\.[0-9a-fA-F]{6}$/;function kte(t){return Ate.test(t)?null:`codec ${JSON.stringify(t)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function nj(t,e){let r=kte(t);if(r)throw new Error(`[urun] webtransport ${e} ${r}`)}var Ite=250,Rte=3,Pte=1e4,kA=2500,Mj=class{constructor(t,e,r){this.offer=t,this.sessionId=e,this.canvas=r,this.firstMedia=new Promise((s,n)=>{this.firstFrameResolve=s,this.firstFrameReject=n}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new Uj({onFrame:t=>this.decodeFrame(t.seq,t.keyframe,t.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let t=globalThis.WebTransport;if(typeof t!="function")throw new Error("[urun] WebTransport API not available");nj(this.offer.codec,"transport.offer"),this.wt=new t(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(o=>({algorithm:"sha-256",value:Uint8Array.from(atob(o),a=>a.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let e=await this.wt.createBidirectionalStream();this.writer=e.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=e.readable.getReader(),s=new Oj,n=[],i=await this.readControl(r,s,n);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");nj(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,s,n).catch(o=>this.die(`control loop: ${o}`)),this.datagramLoop().catch(o=>this.die(`datagram loop: ${o}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(o=>this.die(`connection error: ${o}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(t){this.deadCb=t}stats(){return this.lastStats}initDecoder(t,e,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let n=this.canvas.getContext("2d");if(!n)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:t,width:e,height:r},this.decoder=new s({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,n.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),this.decoder.configure({codec:t,...e>0&&r>0?{codedWidth:e,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(t){if(this.stopped||this.deadFired)return;let e=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>e-s<Pte),this.decoderErrorsAt.push(e),this.decoderErrorsAt.length>=Rte){this.die(`decoder: ${t.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",t.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${t.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let t=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${kA}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${kA}ms`))},kA);t.unref?.(),this.firstDecodeTimer=t}async datagramLoop(){let t=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:e,done:r}=await t.read();if(r)break;if(!e)continue;this.armFirstDecodeDeadline();let s=performance.now();if(this.lastArrivalTs>0){let n=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(n-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(e)}}decodeFrame(t,e,r){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({type:e?"key":"delta",timestamp:t*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(t){await this.writer.write(Nj(t))}async readControl(t,e,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:n,done:i}=await t.read();if(i)return null;n&&r.push(...e.push(n))}}async controlLoop(t,e,r){for(;!this.stopped;){let s=await this.readControl(t,e,r);if(!s)break;s.t==="ping"&&this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})}}feedbackLoop(){let t=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let e=performance.now(),r=(e-t)/1e3;t=e;let s=this.reassembler.drainWindow(),n=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:n>0?100*s.abandoned/n:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Ite)}die(t){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(t)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(t)}}},ij=2500,oj=["av01.0.08M.08","avc1.42E01F","avc1.640028"],jj=class{constructor(t,e,r){this.signaling=t,this.sessionId=e,this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let t=globalThis,e=typeof t.WebTransport=="function",r=typeof t.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,n={webtransport:e&&r&&s,webcodecs:r,codecs:oj};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:n});let i=n.webtransport&&!!this.offer.webtransport;if(n.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let o=null;try{return o=this.createWebTransportSession(),await aj(o.start(),this.opts.quicDeadlineMs??ij,"quic connect deadline"),this.session=o,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(a){console.warn("[urun] webtransport failed, falling back to webrtc:",a),o?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(a instanceof Error?a.message:a))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let t=globalThis;if(!(typeof t.WebTransport=="function"&&typeof t.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let e=this.session;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:oj}}),!this.offer.webtransport)return null;let r=this.createWebTransportSession();try{await aj(r.start(),this.opts.quicDeadlineMs??ij,"quic connect deadline")}catch(s){throw r.stop().catch(()=>{}),s}return this.session!==e?(r.stop().catch(()=>{}),null):(this.session=r,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),e?.stop().catch(()=>{}),r)}createWebTransportSession(){let t=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(t);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new Mj(t,this.sessionId,this.opts.canvas)}async startWebRtc(){let t=this.opts.createWebRtcSession();return await t.start(),t.onDead(e=>{console.error("[urun] webrtc path died:",e)}),t}armFailover(){let t=this.session;t.onDead(e=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",e),t.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${e}`),this.opts.onTransportChange?.("webrtc",e)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(t,e){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:t,fallbackReason:e})}};function aj(t,e,r){return new Promise((s,n)=>{let i=setTimeout(()=>n(new Error(r)),e);t.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),n(o)})})}var Bte=1e4,Fj=class{constructor(t,e=Bte){this.carrier=t,this.requestTimeoutMs=e}carrier;requestTimeoutMs;request(t,e){let r=B1();return new Promise((s,n)=>{let i=setTimeout(()=>{o(),n(new Error(`[urun] signaling request timed out: ${t}`))},this.requestTimeoutMs),o=this.carrier.onSignal(a=>{if(a.type!==`${t}.response`||a.requestId!==r)return;if(clearTimeout(i),o(),a.error){n(new Error(`[urun] ${t} failed: ${String(a.error)}`));return}let{type:c,requestId:d,...u}=a;s(u)});this.carrier.sendSignal({type:t,requestId:r,...e})})}notify(t,e){this.carrier.sendSignal({type:t,...e})}on(t,e){return this.carrier.onSignal(r=>{r.type===t&&e(r)})}},Dte="video",Hj=class{constructor(t,e=Dte){this.transport=t,this.streamName=e,this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let e=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(e(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(e)})}async stop(){for(let t of this.unsubscribers.splice(0))t()}onDead(t){this.deadCb=t}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(t){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(t)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(t))}},Nte="video";function Ote(t,e,r){let s=globalThis,n=s.document;if(!(typeof n?.createElement=="function"&&typeof s.WebTransport=="function"&&typeof s.VideoDecoder=="function")||r.allowWebTransport===!1)return null;let i=n.createElement("canvas"),o=!1,a=null,c=!1,d=()=>{if(a){for(let P of a.getVideoTracks())try{P.stop()}catch{}a=null}c&&(c=!1,r.onOverrideTrack(null))},u=new jj(new Fj(t),e,{canvas:i,createWebRtcSession:r.createWebRtcSession??(()=>new Hj(t,r.streamName??Nte)),createWebTransportSession:r.createWebTransportSession,onTransportChange:(P,j)=>{P==="webrtc"&&(d(),x()),r.onTransportChange?.(P,j)}}),l=null,f=()=>{l!==null&&(clearTimeout(l),l=null)},h=r.wtRetryBaseMs??2e3,m=r.wtRetryCapMs??3e4,v=null,p=0,x=()=>{if(o||v!==null||u.activeTransport==="webtransport")return;let P=Math.min(h*2**p,m);v=setTimeout(()=>{v=null,p+=1,u.retryWebTransport().then(j=>{if(!o){if(j)return console.debug(`[urun] webtransport upgraded in background (retry ${p})`),p=0,E(j);x()}}).catch(j=>{o||(console.debug(`[urun] webtransport background retry ${p} failed:`,j),x())})},P)},w=()=>{v!==null&&(clearTimeout(v),v=null)},E=async P=>{if(o||P.kind!=="webtransport")return;let j=r.firstMediaWarnMs??1e4;if(f(),l=setTimeout(()=>{o||u.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${j}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},j),await P.firstMedia,f(),o||u.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;a=i.captureStream();let T=a.getVideoTracks()[0];T&&(c=!0,r.onOverrideTrack(T))};return(async()=>{let P=await u.connect();await E(P)})().catch(P=>{f(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",P),x()}),{activeTransport:()=>u.activeTransport,dispose(){o=!0,f(),w(),d(),u.disconnect().catch(()=>{})}}}var Lte=new Set;function $j(t){if(t.functionsUrl)return{functionsUrl:t.functionsUrl,orgId:t.orgId,apiKey:t.apiKey,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}var Ute="rpc",Vj=3e4,Mte="rpc-resp";function jte(t){return`${Mte}:${t}`}function IA(){return B1()}function Fte(t){if(t&&typeof t=="object"){let e=t.error;if(e&&typeof e=="object"){let{message:r,code:s}=e;return{message:typeof r=="string"?r:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof t=="string"?t:JSON.stringify(t)}}function Hte(t,e,r,s,n,i,o,a,c,d){let u=[],l=null,f=!1,h=null,m=!1,v,p,x=new Promise((O,W)=>{v=O,p=W});x.catch(()=>{});let w=o(),E=null,P=null,j=null,T=null,k=!0,_=()=>{j&&(clearTimeout(j),j=null),T&&(T(),T=null)},A=!1,M=()=>{A||!m||(A=!0,t.set({rpc:{[e]:null}}))},V=()=>{k=!1,_(),E?.(),E=null,P?.(),P=null,a?.removeEventListener("abort",I),w.dispose(),M()},Y=()=>{if(l){if(u.length>0){let O=l;l=null,O.resolve({value:u.shift(),done:!1})}else if(h!==null){let O=l;l=null,O.reject(h)}else if(f){let O=l;l=null,O.resolve({value:void 0,done:!0})}}},H=O=>{f||(u.push(O),Y())},F=O=>{f||(h=O,f=!0,p(O),V(),Y())},K=O=>{f||(f=!0,v(O),V(),Y())},I=()=>{let O=a?.reason;F(O instanceof ec?O:new C1(e))},G=O=>{if(!(f||!O||typeof O!="object"))switch(M(),O.t){case"delta":typeof O.delta=="string"&&H(O.delta);break;case"response":K(O.body);break;case"error":{let{message:W,code:q}=Fte(O.body);F(new ec(W,{requestId:e,code:O.code??q}));break}}},se=()=>{let O=w.messages()[Symbol.asyncIterator]();E=()=>{O.return?.(void 0)};let W=()=>{k&&O.next().then(q=>{if(k){if(q.done){f||K(void 0);return}G(q.value),W()}},q=>{k&&F(q)})};W()},D=()=>{if(!m){if(m=!0,a){if(a.aborted){F(new C1(e));return}a.addEventListener("abort",I,{once:!0})}P=c?.(O=>F(O))??null,se(),t.set({rpc:{[e]:{args:r,respond_on:s,consumer_id:n,stream:i}}}),d&&d>0&&!t.synced&&(j=setTimeout(()=>{j=null,!f&&!t.synced&&F(new uA(d,e))},d),T=t.onSynced(()=>_()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(D(),u.length>0)return Promise.resolve({value:u.shift(),done:!1});if(h!==null){let O=h;return h=null,Promise.reject(O)}return f?Promise.resolve({value:void 0,done:!0}):new Promise((O,W)=>{l={resolve:O,reject:W}})},return(){return f||(f=!0,v(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(O){return f||(f=!0,p(O),V()),Promise.reject(O)}}}},body:x,start:D}}function cj(t){if(t&&typeof t=="object"){let{epoch:e,by:r}=t,s={epoch:typeof e=="number"?e:0};return(r==="runtime"||r==="browser")&&(s.by=r),s}}function $te(t,e){let r=t.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:n,br:i}=r,o={};(s==="audio"||s==="video"||s==="data")&&(o.kind=s);let a=cj(n);a&&(o.rt=a);let c=cj(i);return c&&(o.br=c),o}var Vte=class{constructor(t,e,r,s,n){this._name=t,this._transport=e,this._streamData=r,this._controlDoc=s,this._onActivity=n,this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let t=this;return{[Symbol.asyncIterator](){let e=[...t._replay],r=null,s=!1,n=null,i={push(a){if(!s)if(r){let c=r;r=null,c.resolve({value:a,done:!1})}else e.push(a)},end(){if(s=!0,r){let a=r;r=null,a.resolve({value:void 0,done:!0})}}};t._messageConsumers.add(i);let o=()=>{s=!0,t._messageConsumers.delete(i)};return t._transport.mediaAvailability().then(a=>{if(!(a===null||s)&&(n=t._streamConsumeUnavailableError(a),o(),r)){let c=r;r=null,c.reject(n)}}),{next(){return e.length>0?Promise.resolve({value:e.shift(),done:!1}):n?Promise.reject(n):s?Promise.resolve({value:void 0,done:!0}):new Promise((a,c)=>{r={resolve:a,reject:c}})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let t=this._transport.mediaUnavailableReason();if(t)throw this._streamConsumeUnavailableError(t)}_streamConsumeUnavailableError(t){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${t}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,t=>this._deliver(t))))}_deliver(t){this._replay.push(t);for(let e of this._messageConsumers)e.push(t)}get track(){let t=this._transport.getTrackByName(this._name)??this._track;return t!==this._track&&this._setTrack(t),this._overrideTrack??this._track}_setOverrideTrack(t){if(this._overrideTrack===t)return;this._overrideTrack=t,t&&t.addEventListener?.("ended",()=>{this._overrideTrack===t&&this._setOverrideTrack(null)},{once:!0});let e=t??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(e)}_claimBrowserProducer(t){if(!this._controlDoc)return;let e=this._controlDoc(),r=$te(e,this._name),s=r?.br;if(s?.by==="runtime")throw new fA(this._name,"runtime","browser");if(s)return;let n={br:{epoch:1}};r?.rt&&(n.rt=r.rt);let i=r?.kind??t;i&&(n.kind=i),e.set({streams:{[this._name]:n}})}async attach(t){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(t,this._name)}async attachVideo(t){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(t,this._name)}async emit(t,e={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,t,e)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(t){if(t!=="live"&&(!Number.isFinite(t)||t<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,t)}chunks(t={}){let e=t.source??Bj;return Ete(e,{track:()=>this.track,onTrack:r=>this.on("track",r)})}onSeeked(t){return this._transport.on("seeked",(e,r)=>{e===this._name&&t(r)})}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let t of this._messageConsumers)t.end();this._messageConsumers.clear()}_setTrack(t){if(this._track=t,t&&t.addEventListener("ended",()=>{this._track===t&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let e=this._handlers.get("track");if(e)for(let r of e)r(t)}},qj=class zj{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new VM;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,r,s,n,i){this._sessionId=e,this._multiplexer=r,this._transport=s,this._recordingsAuth=n,this._artifactsAuth=i,this._streamData=LM(s),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ij(()=>this.recover()),this._activity=kj({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new bj({onPhase:o=>this.onPhase(o),hint:()=>this.doc(mj).get(gj)??this.doc("control").get(yj),onData:(o,a)=>this._streamData.onData(o,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",r=>{this._transport.applyControlDocState(r)})}static async attach(e,r){let s=await RM({baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,sessionId:e,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}),n=r.getAccessToken?await r.getAccessToken()??void 0:r.jwt,i=new dA,o=new vA({url:s.wsUrl,orgId:r.orgId,jwt:n,authProvider:r.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new zj(e,i,o,$j(r),NA({...r,baseUrl:s.baseUrl}));o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),o.setEndsAt(s.endsAt),hf()&&await P1();let c=r.getAccessToken,d=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:s.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}whenLive(e){return xA(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let r=new jA(e);return this._recordingsAccessor={list:s=>r.list(s??this._sessionId),get:s=>r.get(s),retain:(s,n)=>r.retain(s,n),pin:s=>r.pin(s),unpin:s=>r.unpin(s),permanent:s=>r.permanent(s),delete:s=>r.delete(s)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new j1(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,r)=>new j1(this._requireArtifactsAuth()).getDownloadUrl(e,r??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e!==this._sessionId){this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}}setEndHandler(e){this._endHandler=e}stream(e){let r=this._streams.get(e);return r||(r=new Vte(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,r),this._activation.watch(e,r)),r}doc(e){let r=this._docs.get(e);return r||(r=new zM(e,this._sessionId,Lte.has(e)?null:this._docConnector.connect),this._docs.set(e,r)),r}get presence(){return this._presence||(this._presence=KM(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let r=HM(e.wsUrl),s=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${r}\0${s}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs($M({serverUrl:r,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,r={}){let s=IA(),n=new AbortController;r.signal&&(r.signal.aborted?n.abort(r.signal.reason):r.signal.addEventListener("abort",()=>n.abort(r.signal.reason),{once:!0}));let i=null;if(typeof r.timeout=="number"&&r.timeout>=0){let a=r.timeout;i=setTimeout(()=>n.abort(new lA(a,s)),a)}let o=this._consumeResponse(s,e,!1,n.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,r,s,n,i){this._activity?.touch();let o=this.doc(Ute),a=jte(e);return Hte(o,e,r,a,this._streamData.consumerId,s,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??Vj)}requestStream(e,r={}){let s=IA();return this._consumeResponse(s,e,!0,r.signal,r.docSyncTimeout).deltas}complete(e,r={}){let s=IA(),n=this._consumeResponse(s,e,!1,r.signal,r.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(r){console.warn("[urun] session recovery hook failed:",r)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Ote(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:r=>this.stream("video")._setOverrideTrack(r)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new E1)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of e)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new pA)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect()}};function qte(t){return`urun:logical:v1:${t.orgId}:${t.app}:${t.functionName}`}function FA(){try{return globalThis.sessionStorage??null}catch{return null}}function zte(t){let e=FA();if(!e)return null;try{let r=e.getItem(t);if(!r)return null;let s=JSON.parse(r);return typeof s?.logicalId!="string"||s.logicalId.length===0?null:{logicalId:s.logicalId}}catch{return null}}function Kte(t,e){let r=FA();if(r)try{r.setItem(t,JSON.stringify({logicalId:e.logicalId}))}catch{}}function RA(t){let e=FA();if(e)try{e.removeItem(t)}catch{}}var Wte=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Gte(t,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(r,s){if(!(Wte.has(s)||typeof s!="string"))return n=>{let i=n??{},o=qte({orgId:e.orgId,app:t,functionName:s}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),d=e.jwt,u=e.getAccessToken?async T=>{let k=await e.getAccessToken(T);return k&&(d=k),k}:void 0,l={...e,getAccessToken:u},f=new dA,h=new vA({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c,audioPlayout:e.audioPlayout}),m=new qj(c,f,h,$j(l),NA(l)),v,p,x=new Promise(T=>{p=T}),w=T=>{v=T,p({status:"ready",handle:T})};m.setEndHandler(async()=>{let T=v?{status:"ready",handle:v}:await x;if(T.status==="unavailable")throw new E1("[urun] session allocation failed before a releasable request was created",{cause:T.cause});let k=T.handle;return RA(o),TM({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:u,authProvider:e.authProvider})});let E=async T=>{let k=await IM({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:t,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:u,authProvider:e.authProvider,idempotencyKey:T,sessionKey:e.sessionKey??zte(o)?.logicalId,priority:e.priority,onAdmission:A=>h.reportAdmission(A),onRequest:w}),_=u?await u()??void 0:e.jwt;return e.sessionKey||Kte(o,{logicalId:k.sessionId}),m.setSessionId(k.sessionId),m.setArtifactsAuth(NA({...l,baseUrl:k.baseUrl})),h.setEndsAt(k.endsAt),{url:k.wsUrl,sessionId:k.sessionId,jwt:_,iceServers:k.response.ice_servers,endsAt:k.endsAt}},P,j=u?async()=>await u()??P:()=>P;if(h.setConnectionResolver(async()=>{let T=await E(a());return P=T.jwt,T}),h.on("connected",()=>{h.multiplexer&&f.setTarget(h.multiplexer);let T=h.connectedUrl;T&&m.setDocTransport({wsUrl:T,token:j})}),(async()=>{let T;try{T=await E(c)}catch(k){console.error(`[urun] Failed to create session for ${s}:`,k),RA(o);let _=k instanceof Error?k:new Error(String(k)),A=k instanceof Mn?k.httpStatus:void 0;h.reportAllocationFailure(_,A),p({status:"unavailable",cause:k});return}h.setAuth({jwt:T.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:T.url,sessionId:T.sessionId,iceServers:T.iceServers}),hf()&&await P1(),P=T.jwt,m.setDocTransport({wsUrl:T.url,token:j}),await h.connect({app:t,functionName:s,args:i}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(T=>{console.error(`[urun] Failed to connect session for ${s}:`,T)}),e.releaseOnLeave!==!1){let T=Rj(()=>{if(h.leaveLeg()||h.connectedUrl!==null)return;let V=v;V&&(RA(o),bA({baseUrl:V.baseUrl,requestId:V.requestId,orgId:e.orgId,jwt:d,authProvider:e.authProvider}))});m.onDisconnect(T);let k,_,A=!1,M=()=>{A||(A=!0,k?.(),_?.())};x.then(V=>{V.status!=="ready"||A||(k=Pj(()=>v!==void 0))}),_=m.onPhase(V=>{let Y=V?.name;(Y==="ended"||Y==="expired"||Y==="error")&&M()}),A&&_(),m.onDisconnect(M)}return m}}})}var Kj="https://api.urun.sh",Am=class extends Error{status;constructor(t,e){super(t),this.name="ClientTokenError",this.status=e}};async function Xte(t,e={}){if(!t)throw new Am("[urun] createClientToken requires an org API key");let r=e.fetch??globalThis.fetch,s=Ss(e.baseUrl??Kj),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata);let i;try{i=await r(`${s}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(f){throw new Am(`[urun] client token mint request failed: ${f instanceof Error?f.message:String(f)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let f=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new Am(`[urun] client token mint failed: ${f}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,u=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Am("[urun] client token mint returned no token (control-plane contract violation)",i.status);let l=Number.isFinite(d)?new Date(d):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var dj=3e4,lj="stream:",Yte=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(t,e){this._ws=t,this._multiplexer=e,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let n=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(n.timer),s.error?n.reject(new Error(s.error)):n.resolve(s.result)}})}async get(t){return this._sendRpc("store.get",{key:t})}async has(t){return await this._sendRpc("store.has",{key:t})}on(t,e){let r=`${lj}${t}`;return this._multiplexer.on(r,s=>{e(s)})}emit(t,e){let r=`${lj}${t}`,s=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{data:e};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(t,e){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let n=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(n)&&(this._pendingRpc.delete(n),s(new Error(`RPC request "${t}" timed out after ${dj}ms`)))},dj);this._pendingRpc.set(n,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:n,type:t,...e}))})}};function Jte(t){let e=`${t.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(t.orgId)}`,r=new WebSocket(e);(t.jwt||t.apiKey)&&r.addEventListener("open",()=>{r.send(JSON.stringify({type:"auth",orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,apiKey:t.apiKey}))});let s=new cA(r);return new Yte(r,s)}var Qte='video/mp4; codecs="avc1.42E01E"';function Zte(t,e){let r=e?.codec??Qte,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let f;try{f=n.addSourceBuffer(r)}catch(p){throw p instanceof DOMException&&p.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):p}let h=t.getReader();function m(){return f.updating?new Promise(p=>{f.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function v(){try{for(;;){let{done:p,value:x}=await h.read();if(p){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{f.appendBuffer(x)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let E=f.buffered;if(E.length>0){let P=E.start(E.length-1);f.remove(0,P),await m(),f.appendBuffer(x)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}v()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),d=c.getTracks(),u=0,l=d.length;if(l===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let f of d)f.addEventListener("ended",()=>{u++,u>=l&&URL.revokeObjectURL(i)});return c}function ere(t){return t.status.startsWith("pending_")}var Wj=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function uj(t){let e=[];return t.audio&&e.push("audio"),t.video&&e.push("video"),e.join("+")}function tre(t,e){return e==="audio"?t.getAudioTracks():t.getVideoTracks()}function rre(t,e){let r=t.getTracks();if(r.length===1&&r[0]===e)return t;try{return new MediaStream([e])}catch{return t}}function PA(t,e){for(let r of[...t.lostListeners])try{r(e)}catch{}}var Gj=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(t){this.injectedGetUserMedia=t?.getUserMedia}claim(t,e){return this.enqueue(async()=>{let r=this.claims.get(t);r&&(this.claims.delete(t),r.released=!0,r.track=null,r.stream=null,PA(r,new Error(`${t} capture claim superseded by a newer claim`)));let s=this.createState(t,e);return this.claims.set(t,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(t){let e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!t?.getUserMedia)throw new Wj;return e=>t.getUserMedia(e)}async converge(t){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.stream=null);if(this.claims.size===0)return;let e=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await e(r)}catch(i){let o=`one-capture getUserMedia(${uj(r)}) failed`,a=i instanceof Error?i.message:String(i);for(let c of[...this.claims.values()])if(this.claims.delete(c.kind),c.released=!0,c!==t){let d=new Error(`${o} \u2014 ${c.kind} capture lost: ${a||i}`);d.cause=i,PA(c,d)}throw i}let n=[...this.claims.values()].sort((i,o)=>i===t?1:o===t?-1:0);for(let i of n){let o=tre(s,i.kind)[0]??null;if(i.released){o?.stop();continue}if(!o){this.claims.delete(i.kind),i.released=!0;let a=Object.assign(new Error(`one-capture getUserMedia(${uj(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===t)throw a;PA(i,a);continue}if(i.track=o,i.stream=rre(s,o),i!==t)for(let a of[...i.trackListeners])try{a(o,i.stream)}catch{}}}createState(t,e){let r=this,s={kind:t,constraints:e,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:t,get track(){return s.track},get stream(){return s.stream},update(n){return r.enqueue(async()=>{if(s.released)throw new Error(`${t} capture claim already released`);if(s.constraints=n,await r.converge(s),!s.track)throw new Error(`${t} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(t)===s&&r.claims.delete(t),s.track?.stop(),s.track=null,s.stream=null)},onTrack(n){return s.trackListeners.add(n),()=>s.trackListeners.delete(n)},onLost(n){return s.lostListeners.add(n),()=>s.lostListeners.delete(n)}}};return s}},sre=null;function nre(){return sre??=new Gj}var Xj="input",ire=30;function ore(t){let e=t.now??Date.now,r=t.field??Xj,s=1e3/Math.max(t.hz??30,.001),n=new Set,i=0,o=0,a=0,c=0,d,u=null,l=!1,f=()=>{if(l)return;d=e(),c+=1;let m={keys:[...n],buttons:i,pointer:{x:o,y:a},seq:c,at:d};try{t.awareness.setLocalStateField(r,m)}catch{}},h=()=>{if(l)return;let m=e();if(d===void 0||m-d>=s){u&&(clearTimeout(u),u=null),f();return}if(u)return;let v=Math.max(s-(m-d),0);u=setTimeout(()=>{u=null,f()},v),u.unref?.()};return{keyDown(m){let v=String(m).toLowerCase();n.has(v)||(n.add(v),h())},keyUp(m){let v=String(m).toLowerCase();n.delete(v)&&h()},setButtons(m){let v=Number.isFinite(m)?Number(m):0;v!==i&&(i=v,h())},movePointer(m,v){let p=Number.isFinite(m)?Number(m):0,x=Number.isFinite(v)?Number(v):0;p===0&&x===0||(o+=p,a+=x,h())},heldKeys(){return[...n]},clear(){l||(n.clear(),i=0,u&&(clearTimeout(u),u=null),f())},dispose(){if(l)return;let m=n.size>0||i!==0;n.clear(),i=0,u&&(clearTimeout(u),u=null),m&&f(),l=!0}}}var are=1024,cre=.92,dre=262144,lre=256e3,BA=[.9,.8,.7,.6,.5],fj=.8,ure=8;function HA(t,e,r){if(!(t>0)||!(e>0))throw new Error(`reference image has no pixels (${t}x${e})`);let s=Math.min(1,r/Math.max(t,e));return{width:Math.max(1,Math.round(t*s)),height:Math.max(1,Math.round(e*s))}}async function fre(t){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(t,{imageOrientation:"from-image"})}async function Yj(t,e,r){let s=await new Promise(n=>{t.toBlob(n,e,e==="image/jpeg"?r:void 0)});if(!s)throw new Error(`could not encode the reference image as ${e}`);return s}function hj(t,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${t} -> ${e} bytes`)}async function DA(t,e,r,s,n){let i=document.createElement("canvas");i.width=e,i.height=r;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return s==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,r)),o.drawImage(t,0,0,e,r),await Yj(i,s,n)}async function hre(t,e,r,s){let{width:n,height:i}=e,o=await DA(t,n,i,r,s);if(o.size<=256e3)return{blob:o,width:n,height:i};if(r==="image/jpeg"){for(let c of BA)if(!(c>=s)&&(o=await DA(t,n,i,r,c),o.size<=256e3))return hj(`quality ${s} -> ${c}`,o.size),{blob:o,width:n,height:i}}let a=r==="image/jpeg"?BA[BA.length-1]:s;for(let c=0;c<ure;c++)if(n=Math.max(16,Math.round(n*fj)),i=Math.max(16,Math.round(i*fj)),o=await DA(t,n,i,r,a),o.size<=256e3)return hj(`downscaled to ${n}x${i} @ q${a}`,o.size),{blob:o,width:n,height:i};throw new Error(`this image cannot be sent: even at ${n}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function pre(t,e){let{maxSize:r=1024,type:s="image/jpeg",quality:n=.92,source:i}=e,o=await fre(t);try{let a=HA(o.width,o.height,r),c=await hre(o,a,s,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:s,width:c.width,height:c.height,source:i}}finally{o.close()}}function mre(t){let e=t instanceof Error?t.name:"",r=t instanceof Error?t.message:String(t);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(r)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(r)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(r)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function gre(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function yre(t,e){let r=t.videoWidth,s=t.videoHeight;if(!(r>0)||!(s>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=HA(r,s,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(t,0,0,a.width,a.height);let u=await Yj(c,i,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var xre=new Set(["w","a","s","d"]),mf=(t,e)=>Math.min(e,Math.max(-e,t));function bre(t={}){let{panPerPixel:e=9e-4,zoomPerSecond:r=.35,strafePerSecond:s=.18,decayTauMs:n=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=t,c=0,d=0,u=0,l=null,f=new Set;return{pointerDelta(h,m){c=mf(c-h*e,o),d=mf(d-m*e,o)},keyDown(h){let m=h.toLowerCase();xre.has(m)&&f.add(m)},keyUp(h){f.delete(h.toLowerCase())},clearKeys(){f.clear()},frameArrived(){let h=1-i;c*=h,d*=h,u*=h},tick(h){if(l===null){l=h;return}let m=Math.max(0,Math.min(100,h-l))/1e3;l=h,f.has("w")&&(u=mf(u+r*m,a)),f.has("s")&&(u=mf(u-r*m,a)),f.has("a")&&(c=mf(c+s*m,o)),f.has("d")&&(c=mf(c-s*m,o));let v=Math.exp(-m*1e3/n);c*=v,d*=v,u*=v},transform(){return{translateX:c,translateY:d,scale:Math.exp(u)}},isIdentity(h=5e-4){return Math.abs(c)<h&&Math.abs(d)<h&&Math.abs(u)<h},reset(){c=0,d=0,u=0,f.clear()}}}g();var nF=require("@earendil-works/pi-ai");g();g();g();function Jj(t,e,r,s){let n=t.response??{},i={request_id:r,consumer_id:s,stream:!0,kind:"chat",messages:e};return typeof n.instructions=="string"&&(i.instructions=n.instructions),Array.isArray(n.modalities)&&(i.modalities=n.modalities),typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.max_output_tokens=="number"&&(i.max_output_tokens=n.max_output_tokens),n.tools!==void 0&&(i.tools=n.tools),i}function Qj(t,e,r){let s={request_id:e,consumer_id:r,stream:!!t.stream,kind:"responses",input:t.input};return t.model&&(s.model=t.model),t.tools!==void 0&&(s.tools=t.tools),typeof t.temperature=="number"&&(s.temperature=t.temperature),typeof t.max_output_tokens=="number"&&(s.max_output_tokens=t.max_output_tokens),s}g();g();function Zj(t){if(t instanceof Error)return{type:"error",error:{type:"urun_error",code:t.name||null,message:t.message}};if(t&&typeof t=="object"&&t.t==="error"){let e=t,r=e.body??{};return{type:"error",error:{type:"urun_error",code:e.code??null,message:r.message??"unknown error"}}}return{type:"error",error:{type:"urun_error",code:null,message:String(t)}}}var wre="llm-resp";async function*VA(t,e){let r=`${wre}:${e}`,s=`resp_${e}`;yield{type:"response.created",response:{id:s,status:"in_progress"}};for await(let n of t.stream(r).messages()){let i=n;if(i.t==="delta")yield{type:"response.output_text.delta",item_id:s,delta:i.delta};else if(i.t==="response"){yield{type:"response.completed",response:{id:s,status:"completed",...i.body}};return}else if(i.t==="error"){yield Zj(i);return}}}var vre="llm",$1=class{constructor(e){this.session=e}session;get consumerId(){return this.session.consumerId}write(e){this.session.doc(vre).set({requests:{[e.request_id]:{payload:e,consumer_id:e.consumer_id,stream:e.stream}}})}sendResponses(e,r){let s=Qj(e,r,this.consumerId);return this.write(s),VA(this.session,r)}sendResponseCreate(e,r,s){let n=Jj(e,r,s,this.consumerId);return this.write(n),VA(this.session,s)}};var eF=0;function _re(){return eF+=1,`req_${Date.now().toString(36)}_${eF.toString(36)}`}var V1=class{transport;constructor(e){this.transport=new $1(e)}responses={create:async e=>{let r=_re(),s=this.transport.sendResponses(e,r);return Object.assign((async function*(){yield*s})(),{requestId:r})}}};g();g();var qA="https://api.urun.sh/v1";async function tF(t){let e=t.fetchImpl??fetch,r=`${t.apiUrl.replace(/\/+$/,"")}/apps`,s=await e(r,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json"}});if(!s.ok)throw new Error(`org apps listing failed: GET ${r} \u2192 ${s.status}`);let n=await s.json();if(!Array.isArray(n.apps))throw new Error(`org apps listing returned no "apps" array (GET ${r})`);if(n.truncated===!0)throw new Error(`org apps listing was truncated (GET ${r} returned ${n.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return n.apps}async function rF(t){let e=await tF(t),r=e.filter(s=>s.function_name===t.fnName&&s.deployment_status==="active").map(s=>s.app_slug);if(r.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return r.sort()}var zA="urun-serve",Sre="serve",Ere=131072,Cre=16384,sF=3,Tre=42e4,Are=6e4,kre=15e3;function Ire(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||qA,fnName:(t.URUN_FUNCTION??"").trim()||Sre}}function iF(t){let e=(t.URUN_BASE_URL??"").trim(),r=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!r)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let s=(t.URUN_JWT??"").trim();if(s)return{baseUrl:e,orgId:r,auth:{lane:"jwt",jwt:s}};let n=(t.URUN_API_KEY??"").trim();if(!n)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let i=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:r,auth:{lane:"api-key",apiKey:n,gatewayUrl:i}}}function z1(t){return async(e,r,s)=>{let{baseUrl:n,orgId:i,auth:o}=iF(e),{App:a,createClientToken:c}=await t(),u=(o.lane==="jwt"?a(r,{baseUrl:n,orgId:i,jwt:o.jwt}):a(r,{baseUrl:n,orgId:i,getAccessToken:async()=>(await c(o.apiKey,{baseUrl:o.gatewayUrl,expiresIn:300,allowedFunctions:[`${r}/${s}`]})).token}))[s];if(typeof u!="function")throw new Error(`urun pi extension: app "${r}" has no function "${s}"`);let l=u(),f=l.connect;return typeof f=="function"&&await f.call(l),l}}var Rre=z1(async()=>{let{createRequire:t}=await import("module"),e=t(N);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function Pre(t){try{Promise.resolve(t.close?.()).catch(()=>{})}catch{}}var q1=class{constructor(e,r,s){this.open=e;this.env=r;this.fnName=s}open;env;fnName;pool=new Map;acquire(e){let r=this.pool.get(e);if(!r){let s=Promise.resolve(this.open(this.env,e,this.fnName)).then(n=>({session:n,responses:new V1(n)}));r=s,this.pool.set(e,s),s.catch(()=>{this.pool.get(e)===s&&this.pool.delete(e)})}return r}evict(e){let r=this.pool.get(e);r&&(this.pool.delete(e),r.then(s=>Pre(s.session),()=>{}))}closeAll(){for(let e of[...this.pool.keys()])this.evict(e)}};function oF(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let r of t.messages){let s=r.role==="assistant"?"assistant":"user";e.push({role:s,content:Bre(r.content)})}return aF(e)}function aF(t){let e=[];for(let r of t){let s=e[e.length-1];s&&s.role===r.role?s.content=[s.content,r.content].filter(n=>n.length>0).join(`
146
+
147
+ `):e.push({...r})}return e}function Bre(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e?String(e.text):"").join(""):""}function Dre(t){let e=t instanceof Error?t.message:String(t),r=t?.code;return/\b529\b/.test(e)||/overloaded/i.test(e)||r===529||r==="529"}function Nre(t){return new Promise(e=>setTimeout(e,t))}function Ore(t,e,r,s){return new Promise((n,i)=>{let o=!1,a=u=>{o||(o=!0,clearTimeout(c),s?.removeEventListener("abort",d),u())},c=setTimeout(()=>a(()=>i(r())),e),d=()=>a(()=>i(new Error("aborted")));if(s?.aborted){d();return}s?.addEventListener("abort",d,{once:!0}),Promise.resolve(t).then(u=>a(()=>n(u)),u=>a(()=>i(u)))})}async function*Lre(t,e){let r=t[Symbol.asyncIterator](),s,n=new Promise((i,o)=>{s=()=>o(new Error("aborted")),e.addEventListener("abort",s,{once:!0})});try{for(;;){if(e.aborted)throw new Error("aborted");let i=await Promise.race([r.next(),n]);if(i.done)return;yield i.value}}finally{s&&e.removeEventListener("abort",s),r.return?.(void 0)}}function Ure(t,e){let r=t?.sendMessage;if(typeof r=="function")try{r.call(t,{customType:"urun-status",content:e,display:!0},{triggerTurn:!1})}catch{}}function cF(t,e={},r){let s=e.connectDeadlineMs??Tre,n=e.stallTimeoutMs??Are,i=e.phaseHeartbeatMs??kre;return(o,a,c)=>{let d=(0,nF.createAssistantMessageEventStream)(),u={role:"assistant",content:[{type:"text",text:""}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},l=u.content[0],f=new AbortController,h=c?.signal,m=!1,v=()=>{m=!0,f.abort()};h&&(h.aborted?v():h.addEventListener("abort",v,{once:!0}));let p=!1,x,w=()=>{x&&clearTimeout(x),x=setTimeout(()=>{p=!0,f.abort()},n)},E=()=>{x&&clearTimeout(x),x=void 0};return(async()=>{d.push({type:"start",partial:u}),d.push({type:"text_start",contentIndex:0,partial:u});let P=!1,j,T=()=>{j&&clearInterval(j),j=void 0},k=Date.now();j=setInterval(()=>{let _=Math.round((Date.now()-k)/1e3);Ure(r,`uRun: still opening the "${o.id}" session\u2026 (${_}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},i);try{let{responses:_}=await Ore(t.acquire(o.id),s,()=>new Error(`uRun session for "${o.id}" did not connect within ${Math.round(s/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),f.signal);T();let A=oF(a),M,V;for(let H=1;H<=sF;H++)try{let F=await _.responses.create({model:o.id,input:A,stream:!0,max_output_tokens:o.maxTokens});w();for await(let K of Lre(F,f.signal)){w();let I=K;if(I.type==="response.output_text.delta"){let G=typeof I.delta=="string"?I.delta:"";G&&(l.text+=G,d.push({type:"text_delta",contentIndex:0,delta:G,partial:u}))}else if(I.type==="response.completed"){M=I.response;break}else if(I.type==="error"){let G=I.error,se=new Error(`uRun serve error: ${G?.message??"unknown error"}`);throw se.code=G?.code??null,se}}V=void 0;break}catch(F){if(V=F,f.signal.aborted)throw F;if(H<sF&&Dre(F)&&l.text.length===0){await Nre(H*500);continue}throw F}if(V)throw V;E(),d.push({type:"text_end",contentIndex:0,content:l.text,partial:u});let Y=M?.status==="incomplete"?"length":"stop";u.stopReason=Y,d.push({type:"done",reason:Y,message:u}),d.end(u)}catch(_){if(P=!0,E(),m||h?.aborted&&!p)u.stopReason="aborted",u.errorMessage="aborted by user",d.push({type:"error",reason:"aborted",error:u});else{let A=p?`uRun stream stalled \u2014 no output for ${Math.round(n/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:_ instanceof Error?_.message:String(_);u.stopReason="error",u.errorMessage=A,d.push({type:"error",reason:"error",error:u})}d.end(u)}finally{E(),T(),h&&h.removeEventListener("abort",v),P&&t.evict(o.id)}})(),d}}function Mre(t){return{id:t,name:`uRun ${t}`,api:zA,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:Ere,maxTokens:Cre}}function K1(t={}){return async e=>{let r=t.env??process.env,{apiKey:s,apiUrl:n,fnName:i}=Ire(r),o=await rF({apiUrl:n,apiKey:s,fnName:i,fetchImpl:t.fetchImpl}),a=new q1(t.openSession??Rre,r,i);e.on("session_shutdown",()=>a.closeAll());let c={name:"uRun",api:zA,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:o.map(Mre),streamSimple:cF(a,t.timing??{},e)};e.registerProvider("urun",c)}}var l3e=K1();var jre=K1({openSession:z1(()=>$A)});0&&(module.exports={SessionPool,URUN_API,coalesceSameRole,createUrunExtension,makeSessionFactory,makeStreamSimple,resolveSessionEnv,toResponsesInput});
148
+ /*! Bundled license information:
149
+
150
+ reflect-metadata/Reflect.js:
151
+ (*! *****************************************************************************
152
+ Copyright (C) Microsoft. All rights reserved.
153
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
154
+ this file except in compliance with the License. You may obtain a copy of the
155
+ License at http://www.apache.org/licenses/LICENSE-2.0
156
+
157
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
158
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
159
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
160
+ MERCHANTABLITY OR NON-INFRINGEMENT.
161
+
162
+ See the Apache Version 2.0 License for specific language governing permissions
163
+ and limitations under the License.
164
+ ***************************************************************************** *)
165
+
166
+ pvtsutils/build/index.es.js:
167
+ (*!
168
+ * MIT License
169
+ *
170
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
171
+ *
172
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
173
+ * of this software and associated documentation files (the "Software"), to deal
174
+ * in the Software without restriction, including without limitation the rights
175
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
176
+ * copies of the Software, and to permit persons to whom the Software is
177
+ * furnished to do so, subject to the following conditions:
178
+ *
179
+ * The above copyright notice and this permission notice shall be included in all
180
+ * copies or substantial portions of the Software.
181
+ *
182
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
183
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
184
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
185
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
186
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
187
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
188
+ * SOFTWARE.
189
+ *
190
+ *)
191
+
192
+ pvutils/build/utils.es.js:
193
+ (*!
194
+ Copyright (c) Peculiar Ventures, LLC
195
+ *)
196
+
197
+ asn1js/build/index.es.js:
198
+ (*!
199
+ * Copyright (c) 2014, GMO GlobalSign
200
+ * Copyright (c) 2015-2022, Peculiar Ventures
201
+ * All rights reserved.
202
+ *
203
+ * Author 2014-2019, Yury Strozhevsky
204
+ *
205
+ * Redistribution and use in source and binary forms, with or without modification,
206
+ * are permitted provided that the following conditions are met:
207
+ *
208
+ * * Redistributions of source code must retain the above copyright notice, this
209
+ * list of conditions and the following disclaimer.
210
+ *
211
+ * * Redistributions in binary form must reproduce the above copyright notice, this
212
+ * list of conditions and the following disclaimer in the documentation and/or
213
+ * other materials provided with the distribution.
214
+ *
215
+ * * Neither the name of the copyright holder nor the names of its
216
+ * contributors may be used to endorse or promote products derived from
217
+ * this software without specific prior written permission.
218
+ *
219
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
220
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
221
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
222
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
223
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
224
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
225
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
226
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
227
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
228
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
229
+ *
230
+ *)
231
+
232
+ tslib/tslib.es6.js:
233
+ (*! *****************************************************************************
234
+ Copyright (c) Microsoft Corporation.
235
+
236
+ Permission to use, copy, modify, and/or distribute this software for any
237
+ purpose with or without fee is hereby granted.
238
+
239
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
240
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
241
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
242
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
243
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
244
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
245
+ PERFORMANCE OF THIS SOFTWARE.
246
+ ***************************************************************************** *)
247
+
248
+ @peculiar/x509/build/x509.es.js:
249
+ (*!
250
+ * MIT License
251
+ *
252
+ * Copyright (c) Peculiar Ventures. All rights reserved.
253
+ *
254
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
255
+ * of this software and associated documentation files (the "Software"), to deal
256
+ * in the Software without restriction, including without limitation the rights
257
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
258
+ * copies of the Software, and to permit persons to whom the Software is
259
+ * furnished to do so, subject to the following conditions:
260
+ *
261
+ * The above copyright notice and this permission notice shall be included in all
262
+ * copies or substantial portions of the Software.
263
+ *
264
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
265
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
266
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
267
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
268
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
269
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
270
+ * SOFTWARE.
271
+ *
272
+ *)
273
+
274
+ isobject/index.js:
275
+ (*!
276
+ * isobject <https://github.com/jonschlinkert/isobject>
277
+ *
278
+ * Copyright (c) 2014-2017, Jon Schlinkert.
279
+ * Released under the MIT License.
280
+ *)
281
+
282
+ is-plain-object/index.js:
283
+ (*!
284
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
285
+ *
286
+ * Copyright (c) 2014-2017, Jon Schlinkert.
287
+ * Released under the MIT License.
288
+ *)
289
+
290
+ @noble/hashes/esm/utils.js:
291
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
292
+
293
+ @noble/curves/esm/utils.js:
294
+ @noble/curves/esm/abstract/modular.js:
295
+ @noble/curves/esm/abstract/curve.js:
296
+ @noble/curves/esm/abstract/weierstrass.js:
297
+ @noble/curves/esm/_shortw_utils.js:
298
+ @noble/curves/esm/nist.js:
299
+ @noble/curves/esm/p256.js:
300
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
301
+
302
+ aes-js/index.js:
303
+ (*! MIT License. Copyright 2015-2018 Richard Moore <me@ricmoo.com>. See LICENSE.txt. *)
304
+ */