@lakutata/webrtc 3.1.4 → 3.1.5

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.
@@ -1 +1 @@
1
- export const peerWorkerCode = "var Sl=Object.create;var wi=Object.defineProperty;var yl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var wl=Object.getPrototypeOf;var bl=Object.prototype.hasOwnProperty;var a=(r,e)=>wi(r,\"name\",{value:e,configurable:true});var Cl=(r,e)=>{for(var t in e)wi(r,t,{get:e[t],enumerable:true})};var El=(r,e,t,s)=>{if(e&&typeof e===\"object\"||typeof e===\"function\"){for(let i of Tl(e))if(!bl.call(r,i)&&i!==t)wi(r,i,{get:()=>e[i],enumerable:!(s=yl(e,i))||s.enumerable})}return r};var bi=(r,e,t)=>(t=r!=null?Sl(wl(r)):{},El(e||!r||!r.__esModule?wi(t,\"default\",{value:r,enumerable:true}):t,r));var ml=require(\"node:util\");var Ti=require(\"node:worker_threads\");var zc=require(\"node:crypto\");var Ao=require(\"node:crypto\");function _o(){return(0,Ao.randomBytes)(2).readUInt16BE(0)}a(_o,\"random16\");function Ci(){return(0,Ao.randomBytes)(4).readUInt32BE(0)}a(Ci,\"random32\");var ze=class{static{a(this,\"BitWriter\")}constructor(e){this.bitLength=e;this.value=0}set(e,t,s){s&=(1<<e)-1;this.value|=s<<this.bitLength-e-t;return this}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};var gt=class{static{a(this,\"BitWriter2\")}constructor(e){this.bitLength=e;this._value=0n;this.offset=0n;if(e>32){throw new Error}}set(e,t=1){let s=BigInt(e);const i=BigInt(t);s&=(1n<<i)-1n;this._value|=s<<BigInt(this.bitLength)-i-this.offset;this.offset+=i;return this}get value(){return Number(this._value)}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};function k(r,e,t=1){const s=Math.min(e+t,8);return r>>8-s&(1<<s-e)-1}a(k,\"getBit\");function N(r,e){return or(r)(e)}a(N,\"bufferWriter\");function or(r,e){const t=r.reduce((i,n)=>i+n,0);const s=e?Buffer.alloc(t):void 0;return i=>{const n=s||Buffer.alloc(t);let o=0;i.forEach((c,d)=>{const h=r[d];if(h===8)n.writeBigUInt64BE(c,o);else n.writeUIntBE(c,o,h);o+=h});return n}}a(or,\"createBufferWriter\");function F(r,e){let t=0;return e.map(s=>{let i;if(s===8){i=r.readBigUInt64BE(t)}else{i=r.readUIntBE(t,s)}t+=s;return i})}a(F,\"bufferReader\");var Pe=class{static{a(this,\"BitStream\")}constructor(e){this.uint8Array=e;this.position=0;this.bitsPending=0}writeBits(e,t){if(e==0){return this}t&=4294967295>>>32-e;let s;if(this.bitsPending>0){if(this.bitsPending>e){this.uint8Array[this.position-1]|=t<<this.bitsPending-e;s=e;this.bitsPending-=e}else if(this.bitsPending==e){this.uint8Array[this.position-1]|=t;s=e;this.bitsPending=0}else{this.uint8Array[this.position-1]|=t>>e-this.bitsPending;s=this.bitsPending;this.bitsPending=0}}else{s=Math.min(8,e);this.bitsPending=8-s;this.uint8Array[this.position++]=t>>e-s<<this.bitsPending}e-=s;if(e>0){this.writeBits(e,t)}return this}readBits(e){return this._readBits(e)}_readBits(e,t){if(typeof t==\"undefined\"){t=0}if(e==0){return t}let s;let i;if(this.bitsPending>0){const n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;i=Math.min(this.bitsPending,e);this.bitsPending-=i;s=n>>this.bitsPending}else{i=Math.min(8,e);this.bitsPending=8-i;s=this.uint8Array[this.position++]>>this.bitsPending}e-=i;t=t<<i|s;return e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0;this.bitsPending=e%8;if(this.bitsPending>0){this.bitsPending=8-this.bitsPending;this.position++}}};var Rl=3988292384;var xl=2197175160;function yc(r){return typeof r!==\"string\"}a(yc,\"isBufferLike\");function Tc(r){const e=new Array(256);for(let t=0;t<256;++t){let s=t;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;e[t]=s}return new Int32Array(e)}a(Tc,\"generateCRCTable\");function wc(r){const e=new Int32Array(4096);let t;let s;let i;for(i=0;i<256;++i)e[i]=r[i];for(i=0;i<256;++i){s=r[i];for(t=256+i;t<4096;t+=256){s=e[t]=s>>>8^r[s&255]}}const n=[];for(i=1;i<16;++i){n[i-1]=e.subarray(i*256,i*256+256)}return n}a(wc,\"generateSliceBy16Tables\");function bc(r,e,t){let s=e^-1;let i=0;const n=r.length;let o;let c;while(i<n){o=r.charCodeAt(i++);if(o<128){s=s>>>8^t[(s^o)&255]}else if(o<2048){s=s>>>8^t[(s^(192|o>>6&31))&255];s=s>>>8^t[(s^(128|o&63))&255]}else if(o>=55296&&o<57344){o=(o&1023)+64;c=r.charCodeAt(i++)&1023;s=s>>>8^t[(s^(240|o>>8&7))&255];s=s>>>8^t[(s^(128|o>>2&63))&255];s=s>>>8^t[(s^(128|c>>6&15|(o&3)<<4))&255];s=s>>>8^t[(s^(128|c&63))&255]}else{s=s>>>8^t[(s^(224|o>>12&15))&255];s=s>>>8^t[(s^(128|o>>6&63))&255];s=s>>>8^t[(s^(128|o&63))&255]}}return~s>>>0}a(bc,\"crcGenericString\");function Cc(r,e,t,s){const[i,n,o,c,d,h,l,u,g,S,p,f,y,m,T]=s;let C=e^-1;let E=0;let P=r.length-15;while(E<P){C=T[r[E++]^C&255]^m[r[E++]^C>>>8&255]^y[r[E++]^C>>>16&255]^f[r[E++]^C>>>24]^p[r[E++]]^S[r[E++]]^g[r[E++]]^u[r[E++]]^l[r[E++]]^h[r[E++]]^d[r[E++]]^c[r[E++]]^o[r[E++]]^n[r[E++]]^i[r[E++]]^t[r[E++]]}for(P+=15;E<P;){C=C>>>8^t[(C^r[E++])&255]}return~C>>>0}a(Cc,\"crcBuffer\");var Bo=Tc(Rl);var kl=wc(Bo);var Lo=Tc(xl);var vl=wc(Lo);function Ec(r,e=0){if(yc(r)){return Cc(r,e,Bo,kl)}return bc(r,e,Bo)}a(Ec,\"crc32\");function ar(r,e=0){if(yc(r)){return Cc(r,e,Lo,vl)}return bc(r,e,Lo)}a(ar,\"crc32c\");function Rc(r,e){return r+e&255}a(Rc,\"uint8Add\");function j(r,e){return r+e&65535}a(j,\"uint16Add\");function Ae(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}a(Ae,\"uint32Add\");function Ei(r,e){const t=32768;return r<e&&e-r>t||r>e&&r-e<t}a(Ei,\"uint16Gt\");function ae(r,e){const t=2147483648;return r<e&&e-r>t||r>e&&r-e<t}a(ae,\"uint32Gt\");function Xt(r,e){return r===e||ae(r,e)}a(Xt,\"uint32Gte\");var at=a(r=>Number.parseInt(r,10),\"int\");function K(r,e){try{const t=r();if(t instanceof Promise)t.catch(e)}catch(t){e(t)}}a(K,\"runDetached\");function ye(r,e){return(...t)=>{try{const s=r(...t);if(s instanceof Promise)s.catch(e)}catch(s){e(s)}}}a(ye,\"detached\");var Do=require(\"node:dgram\");var Ri=a((r,e)=>e?e[r]:void 0,\"interfaceAddress\");async function xi(r=\"udp4\",e){const t=(0,Do.createSocket)(r);setImmediate(()=>t.bind({port:0,address:Ri(r,e)}));await new Promise(i=>{t.once(\"error\",i);t.once(\"listening\",i)});const s=t.address()?.port;await new Promise(i=>t.close(()=>i()));return s}a(xi,\"randomPort\");async function xc(r,e,t=\"udp4\",s){let i;for(let n=r;n<=e;n++){const o=(0,Do.createSocket)(t);setImmediate(()=>o.bind({port:n,address:Ri(t,s)}));const c=await new Promise(d=>{o.once(\"error\",h=>d(h));o.once(\"listening\",()=>d())});if(c){await new Promise(d=>o.close(()=>d()));continue}i=o.address()?.port;await new Promise(d=>o.close(()=>d()));if(r<=i&&i<=e){break}}if(!i)throw new Error(\"port not found\");return i}a(xc,\"findPort\");function St(r){if(r===\"IPv4\")return 4;if(r===\"IPv6\")return 6;return r}a(St,\"normalizeFamilyNodeV18\");var ki;var Il=new Set;function kc(r){const e=!!ki!==!!r;ki=r;if(e)for(const t of Il)t(!!r)}a(kc,\"setDebugHandler\");function b(r){return(...e)=>{if(ki)ki(r,e)}}a(b,\"debug\");var vi=class{static{a(this,\"Subscribers\")}constructor(){this.list=[];this.size=0;this.#e=0}#e;add(e){this.list.push(e);this.size++}remove(e){if(e.removed)return false;e.removed=true;this.size--;if(++this.#e>16&&this.#e>this.size){this.list=this.list.filter(t=>!t.removed);this.#e=0}return true}clear(){for(const e of this.list)e.removed=true;this.list=[];this.size=0;this.#e=0}};var w=class{static{a(this,\"Event\")}constructor(){this.subscribers=new vi;this.queued=new vi;this.ended=false;this.onerror=e=>{};this.execute=(...e)=>{if(this.ended){return}for(const t of this.subscribers.list){if(!t.removed)t.execute(...e)}if(this.queued.size===0)return;(async()=>{for(const t of this.queued.list){if(!t.removed)await t.execute(...e)}})().catch(t=>{this.onerror(t)})};this.complete=()=>{if(this.ended){return}for(const e of this.subscribers.list){if(e.complete&&!e.removed){e.complete()}}this.allUnsubscribe();this.ended=true;if(this.onended){this.onended();this.onended=void 0}};this.error=e=>{if(this.ended){return}for(const t of this.subscribers.list){if(t.error&&!t.removed){t.error(e)}}this.allUnsubscribe()};this.allUnsubscribe=()=>{if(this.ended){return}this.subscribers.clear();this.queued.clear();this.onsubscriberschange?.()};this.subscribe=(e,t,s)=>{const i={execute:e,complete:t,error:s};const n=this.subscribers;n.add(i);this.onsubscriberschange?.();const o=a(()=>{if(n.remove(i))this.onsubscriberschange?.()},\"unSubscribe\");const c=a(d=>{d.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.queuingSubscribe=(e,t,s)=>{if(this.ended)throw new Error(\"event completed\");const i={execute:e,complete:t,error:s};const n=this.queued;n.add(i);const o=a(()=>{n.remove(i)},\"unSubscribe\");const c=a(d=>{d.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.once=(e,t,s)=>{const i=this.subscribe((...n)=>{i.unSubscribe();e(...n)},t,s)};this.watch=(e,t)=>new Promise((s,i)=>{const n=t&&setTimeout(()=>{i(\"Event watch timeout\")},t);const{unSubscribe:o}=this.subscribe((...c)=>{const d=e(...c);if(d){if(n)clearTimeout(n);o();s(c)}})});this.asPromise=e=>new Promise((t,s)=>{const i=e&&setTimeout(()=>{s(\"Event asPromise timeout\")},e);this.once((...n)=>{if(i)clearTimeout(i);t(n)},()=>{if(i)clearTimeout(i);t([])},n=>{if(i)clearTimeout(i);s(n)})})}pipe(e){this.subscribe((...t)=>{e.execute(...t)})}get returnTrigger(){const{execute:e,error:t,complete:s}=this;return{execute:e,error:t,complete:s}}get returnListener(){const{subscribe:e,once:t,asPromise:s}=this;return{subscribe:e,once:t,asPromise:s}}get length(){return this.subscribers.size}};var Ii=class{static{a(this,\"EventDisposer\")}constructor(){this._disposer=[]}push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e());this._disposer=[]}};var Ic=require(\"node:dgram\");var No=bi(require(\"node:net\"),1);var Pc=bi(require(\"node:tls\"),1);var Ac=require(\"node:net\");var qe=b(\"webrtc/common/transport\");var Pl=8e3;var vc=4*1024*1024;function Al(r){try{if(r.getRecvBufferSize()<vc)r.setRecvBufferSize(vc)}catch(e){qe(\"the receive buffer cannot grow\",e)}}a(Al,\"growReceiveBuffer\");function _l(r,e){return r===e||r[1]===e[1]&&r[0]===e[0]}a(_l,\"sameAddress\");var yt=class r{static{a(this,\"UdpTransport\")}constructor(e,t={}){this.socketType=e;this.options=t;this.type=\"udp\";this.onData=()=>{};this.closed=false;this.send=async(s,i)=>{const n=this.connected;if(n){if(!i||_l(i,n)){this.socket.send(s)}else{qe(\"not sent to an address other than the connected one\",i)}return}if(this.waiting){this.waiting.push([s,i]);return}if(i&&!No.isIP(i[0])){return new Promise((o,c)=>{this.socket.send(s,i[1],i[0],d=>{if(d){qe(\"send error\",i,s);c(d)}else{o()}})})}else{i=i??[this.rinfo.address,this.rinfo.port];this.socket.send(s,i[1],i[0])}};this.close=()=>new Promise(s=>{this.closed=true;this.connectOnReceive=void 0;this.connecting=void 0;this.connected=void 0;this.waiting=void 0;this.socket.once(\"close\",s);try{this.socket.close()}catch(i){s()}});this.socket=(0,Ic.createSocket)(e);this.socket.on(\"message\",(s,i)=>{if(St(i.family)===6){[i.address]=i.address.split(\"%\")}this.rinfo=i;if(this.connectOnReceive&&s[0]>3&&i.port===this.connectOnReceive[1]&&i.address===this.connectOnReceive[0])this.connectNow(this.connectOnReceive);try{this.onData(s,[i.address,i.port])}catch(n){qe(\"onData error\",n)}})}static async init(e,t={}){const s=new r(e,t);await s.init();return s}async init(){const e=Ri(this.socketType,this.options.interfaceAddresses);if(this.options.port){this.socket.bind({port:this.options.port,address:e})}else if(this.options.portRange){const t=await xc(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else{this.socket.bind({port:await xi(this.socketType,this.options.interfaceAddresses),address:e})}await new Promise((t,s)=>{const i=a(n=>s(n),\"failed\");this.socket.once(\"error\",i);this.socket.once(\"listening\",()=>{this.socket.off(\"error\",i);t()})});this.socket.on(\"error\",t=>qe(\"socket error\",t));Al(this.socket)}connectTo(e){if(this.closed||this.connected||this.waiting||!No.isIP(e[0]))return;this.connectOnReceive=e}disconnect(){this.connectOnReceive=void 0;this.connecting=void 0;if(!this.connected)return;this.connected=void 0;try{this.socket.disconnect()}catch(e){qe(\"disconnect\",e)}}connectNow(e){this.connectOnReceive=void 0;this.connecting=e;const t=[];this.waiting=t;const s=a(i=>{if(this.waiting===t)this.waiting=void 0;const n=this.connecting===e;if(n)this.connecting=void 0;if(this.closed)return;if(i){qe(\"connect\",e,i)}else if(n){this.connected=e}else{this.socket.disconnect()}for(const[o,c]of t)this.send(o,c).catch(d=>qe(\"send\",d))},\"done\");try{this.socket.connect(e[1],e[0],s)}catch(i){s(i)}}get address(){return this.socket.address()}get addressFamily(){return this.socketType===\"udp6\"?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}};var cr=class r{static{a(this,\"TcpTransport\")}constructor(e,t={}){this.type=\"tcp\";this.send=async(s,i)=>{await this.stream.send(s,i)};this.close=async()=>{await this.stream.close()};this.stream=new Pi(\"tcp\",()=>(0,Ac.connect)({port:e[1],host:e[0]}),void 0,t.connectTimeoutMs)}static async init(e,t={}){const s=new r(e,t);try{await s.init();return s}catch(i){await s.close();throw i}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var dr=class r{static{a(this,\"TlsTransport\")}constructor(e,t={},s={}){this.type=\"tls\";this.send=async(i,n)=>{await this.stream.send(i,n)};this.close=async()=>{await this.stream.close()};this.stream=new Pi(\"tls\",()=>Pc.connect({...t,host:e[0],port:e[1]}),void 0,s.connectTimeoutMs)}static async init(e,t={},s={}){const i=new r(e,t,s);try{await i.init();return i}catch(n){await i.close();throw n}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var Pi=class{static{a(this,\"StreamTransport\")}constructor(e,t,s=e===\"tls\"?\"secureConnect\":\"connect\",i=Pl){this.createClient=t;this.connectEvent=s;this.connectTimeoutMs=i;this.onData=()=>{};this.closed=false;this.send=async(n,o)=>{void o;await this.connecting;await new Promise((c,d)=>{this.client.write(n,h=>{if(h){d(h);return}c()})})};this.close=async()=>{this.closed=true;this.rejectConnecting?.(new Error(`${this.type} transport closed`));this.client?.destroy()};this.type=e;this.connect()}connect(){if(this.closed){return}if(this.client){this.client.destroy()}const e=this.createClient();this.client=e;this.connecting=new Promise((t,s)=>{let i=false;const n=a(h=>{if(i)return;i=true;clearTimeout(d);e.off(this.connectEvent,o);e.off(\"error\",c);this.rejectConnecting=void 0;h?s(h):t()},\"settle\");const o=a(()=>{n()},\"onConnect\");const c=a(h=>{this.closed=true;n(h);e.destroy()},\"onConnectError\");const d=setTimeout(()=>{this.closed=true;n(new Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`));e.destroy()},this.connectTimeoutMs);this.rejectConnecting=h=>n(h);e.once(this.connectEvent,o);e.once(\"error\",c)});e.on(\"data\",t=>{this.onData(t,this.remoteAddress)});e.on(\"error\",t=>{qe(`${this.type} transport error`,t)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){const{remoteAddress:e,remotePort:t}=this.client;if(!e||!t){return void 0}return[Bl(e),t]}};function Bl(r){return r.split(\"%\")[0]}a(Bl,\"stripZoneId\");var x={};Cl(x,{BinaryReader:()=>_i,BinaryWriter:()=>ur,NotEnoughDataError:()=>Ai,decode:()=>Dl,encode:()=>Ll,types:()=>Ul});var Ai=class extends Error{static{a(this,\"NotEnoughDataError\")}constructor(e,t){super(`requested ${e} bytes but only ${t} available`);this.name=\"NotEnoughDataError\"}};var _i=class{static{a(this,\"BinaryReader\")}constructor(e){this.buf=e;this.offset=0}get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(e){this.assertSize(e);const t=this.buf.subarray(this.offset,this.offset+e);this.offset+=e;return t}readUIntBE(e){this.assertSize(e);const t=this.buf.readUIntBE(this.offset,e);this.offset+=e;return t}assertSize(e){if(e>this.length){throw new Ai(e,this.length)}}};var ur=class{static{a(this,\"BinaryWriter\")}constructor(){this.chunks=[];this.written=0}get bytes(){return this.written}writeBuffer(e){this.chunks.push(e);this.written+=e.length}writeUIntBE(e,t){const s=Buffer.allocUnsafe(t);switch(t){case 1:s.writeUInt8(e,0);break;case 2:s.writeUInt16BE(e,0);break;case 4:s.writeUInt32BE(e,0);break;default:s.writeUIntBE(e,0,t)}this.writeBuffer(s)}toBuffer(){return Buffer.concat(this.chunks,this.written)}};var Bc=a(r=>typeof r===\"object\"&&r!==null,\"isObject\");var se=a(r=>Bc(r)&&typeof r.encode===\"function\"&&typeof r.decode===\"function\",\"isType\");var Lc=a(r=>{if(!Bc(r))return false;const e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},\"isPlainObject\");var Dc=a(()=>({node:void 0,current:void 0}),\"createContext\");var _c=a(r=>({node:r.node,current:r.current}),\"cloneContext\");var Nc=a((r,e)=>{if(!Lc(r)){throw new TypeError(e)}},\"assertSchema\");var Mc=a((r,e,t,s)=>{if(se(e)){e.encode(r,t,s)}else{Oc(r,e,t,s)}},\"encodeCommon\");var Oc=a((r,e,t,s)=>{Nc(e,\"Argument `schema` should be a plain object.\");if(s.node===void 0){s.node=r}s.current=r;for(const i of Object.keys(e)){const n=e[i];const o=r[i];if(se(n)){n.encode(o,t,s)}else{Oc(o,n,t,s);s.current=r}}},\"encodeSchema\");var Mo=a((r,e,t)=>{if(se(e)){return e.decode(r,t)}return Uc(r,e,t)},\"decodeCommon\");var Uc=a((r,e,t)=>{Nc(e,\"Argument #2 should be a plain object.\");const s=Object.create(null);if(t.node===void 0){t.node=s}t.current=s;for(const i of Object.keys(e)){const n=e[i];if(se(n)){s[i]=n.decode(r,t)}else{s[i]=Uc(r,n,t);t.current=s}}return s},\"decodeSchema\");function Ll(r,e){const t=new ur;Mc(r,e,t,Dc());return t.toBuffer()}a(Ll,\"encode\");function Dl(r,e){return Mo(new _i(r),e,Dc())}a(Dl,\"decode\");var hr=a(r=>({encode:a((e,t)=>t.writeUIntBE(e,r),\"encode\"),decode:a(e=>e.readUIntBE(r),\"decode\")}),\"createUIntBE\");var Oo=a(r=>{if(typeof r!==\"number\"&&!se(r)&&typeof r!==\"function\"){throw new TypeError(\"Unknown type of argument #1.\")}},\"assertLengthSpec\");var lr=a((r,e,t)=>{if(r!==e){throw new Error(`${t} required length ${r} instead of ${e}`)}},\"checkLength\");var Tt=a((r,e)=>{if(typeof r!==\"number\"){throw new TypeError(e)}},\"checkLengthType\");function Nl(r){Oo(r);const e=\"Length of a buffer should be a number.\";return{encode(t,s,i){if(!Buffer.isBuffer(t)){throw new TypeError(\"Argument 1 should be a Buffer or a BinaryStream.\")}if(typeof r===\"number\"){lr(r,t.length,\"Buffer\")}else if(se(r)){r.encode(t.length,s,i)}else{const n=r(i);Tt(n,e);lr(n,t.length,\"Buffer\")}s.writeBuffer(t)},decode(t,s){let i;if(typeof r===\"number\"){i=r}else if(se(r)){i=r.decode(t,s)}else{i=r(s)}Tt(i,e);return t.readBuffer(i)}}}a(Nl,\"buffer\");function Ml(r,e,t=\"count\"){if(!se(r)&&!Lc(r)){throw new TypeError(\"Argument #1 should be a valid type.\")}Oo(e);const s=t===\"bytes\";const i=\"Length of an array should be a number.\";return{encode(n,o,c){if(!Array.isArray(n)){throw new TypeError(\"Argument #1 should be an Array.\")}const d=_c(c);let h;if(typeof e===\"number\"){h=e}else if(se(e)){h=n.length}else{h=e(d);Tt(h,i)}const l=new ur;for(const u of n){Mc(u,r,l,d)}if(s){if(se(e)){h=l.bytes}lr(l.bytes,h,\"Argument #1\")}else{lr(h,n.length,\"Argument #1\")}if(se(e)){e.encode(h,o,d)}o.writeBuffer(l.toBuffer())},decode(n,o){const c=_c(o);let d;if(typeof e===\"number\"){d=e}else if(se(e)){d=e.decode(n,c)}else{d=e(c)}Tt(d,i);const h=[];if(s){const l=n.bytes;let u=0;while(u<d){h.push(Mo(n,r,c));u=n.bytes-l}if(u>d){throw new Error(\"Incorrect length of an array.\")}}else{for(let l=0;l<d;l++){h.push(Mo(n,r,c))}}return h}}}a(Ml,\"array\");function Ol(r,e=\"ascii\"){if(!Buffer.isEncoding(e)){throw new Error(\"Argument #2 should be an encoding name.\")}Oo(r);const t=\"Length of a buffer should be a number.\";return{encode(s,i,n){const o=Buffer.from(s.toString(),e);if(typeof r===\"number\"){if(o.length!==r){throw new Error(`Size of string should be ${r} in bytes.`)}}else if(se(r)){r.encode(o.length,i,n)}else{const c=r(n);Tt(c,t);lr(c,o.length,\"Buffer\")}i.writeBuffer(o)},decode(s,i){let n;if(typeof r===\"number\"){n=r}else if(se(r)){n=r.decode(s,i);Tt(n,\"Size of a string should be a number.\")}else{n=r(i);Tt(n,t)}return s.readBuffer(n).toString(e)}}}a(Ol,\"string\");var Ul={uint8:hr(1),uint16be:hr(2),uint24be:hr(3),uint32be:hr(4),uint48be:hr(6),buffer:Nl,array:Ml,string:Ol};var fr=class{static{a(this,\"Deque\")}#e=new Array(16);#t=0;#s=0;get length(){return this.#s}push(e){if(this.#s===this.#e.length)this.#n();this.#e[this.#t+this.#s&this.#e.length-1]=e;this.#s++}unshift(e){if(this.#s===this.#e.length)this.#n();this.#t=this.#t-1&this.#e.length-1;this.#e[this.#t]=e;this.#s++}shift(){if(!this.#s)return void 0;const e=this.#e[this.#t];this.#e[this.#t]=void 0;this.#t=this.#t+1&this.#e.length-1;this.#s--;return e}at(e){const t=e<0?this.#s+e:e;if(t<0||t>=this.#s)return void 0;return this.#e[this.#t+t&this.#e.length-1]}findIndex(e){for(let t=0;t<this.#s;t++){if(e(this.#e[this.#t+t&this.#e.length-1]))return t}return-1}clear(){this.#e=new Array(16);this.#t=0;this.#s=0}*[Symbol.iterator](){for(let e=0;e<this.#s;e++)yield this.#e[this.#t+e&this.#e.length-1]}#n(){const e=new Array(this.#e.length*2);for(let t=0;t<this.#s;t++)e[t]=this.#e[this.#t+t&this.#e.length-1];this.#e=e;this.#t=0}};var Hc=require(\"node:events\");var Ng=b(\"webrtc/peer/helper\");function Uo(r){return r.map((e,t)=>[t,e])}a(Uo,\"enumerate\");function _e(r,e){const t=r.split(e);return[t[0],t.slice(1).join(e)]}a(_e,\"divide\");var he=class extends Hc.EventEmitter{static{a(this,\"EventTarget\")}constructor(){super(...arguments);this.addEventListener=(e,t,s)=>{if(typeof s===\"object\"&&s?.once){this.once(e,t);return}this.addListener(e,t)};this.removeEventListener=(e,t)=>{this.removeListener(e,t)};this.dispatchEvent=e=>this.emit(e.type,e)}emit(e,...t){if(typeof e!==\"string\"){return super.emit(e,...t)}if(t.length===0){return super.emit(e,new Event(e))}const[s,...i]=t;if(s&&typeof s===\"object\"&&!(\"type\"in s)){try{Object.defineProperty(s,\"type\",{configurable:true,enumerable:true,value:e})}catch{return super.emit(e,{type:e,...s},...i)}}return super.emit(e,s,...i)}};var Bi=b(\"webrtc/peer/dataChannel\");function pr(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}a(pr,\"getDataChannelMessageSize\");var Jt=class extends he{static{a(this,\"RTCDataChannel\")}constructor(e,t,s=true){super();this.sctp=e;this.parameters=t;this.sendOpen=s;this.statsId=(0,zc.randomUUID)().toString();this.stateChange=new w;this.stateChanged=new w;this.onMessage=new w;this.error=new w;this.bufferedAmountLow=new w;this.bufferedAmountChanged=new w;this.isCreatedByRemote=false;this.readyState=\"connecting\";this.bufferedAmount=0;this._bufferedAmountLowThreshold=0;this.messagesSent=0;this.bytesSent=0;this.messagesReceived=0;this.bytesReceived=0;this.id=this.parameters.id;if(t.negotiated){if(this.id==void 0||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{if(s){this.sendOpen=false;this.sctp.dataChannelOpen(this)}}}get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){if(e<0||e>4294967295){throw new Error(\"bufferedAmountLowThreshold must be in range 0 - 4294967295\")}this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){this.readyState=e;this.stateChange.execute(e);this.stateChanged.execute(e);switch(e){case\"open\":if(this.onopen)K(()=>this.onopen(),t=>Bi(\"onopen failed\",t));this.emit(\"open\");break;case\"closed\":if(this.onclose)K(()=>this.onclose(),t=>Bi(\"onclose failed\",t));this.emit(\"close\");break;case\"closing\":if(this.onclosing)K(()=>this.onclosing(),t=>Bi(\"onclosing failed\",t));break}Bi(\"change state\",e)}}addBufferedAmount(e){const t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e;this.bufferedAmountChanged.execute();if(t){this.bufferedAmountLow.execute();this.emit(\"bufferedamountlow\")}}send(e){const t=this.sctp.datachannelSend(this,e);this.messagesSent++;this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}};var Zt=class{static{a(this,\"RTCDataChannelParameters\")}constructor(e={}){this.label=\"\";this.ordered=true;this.protocol=\"\";this.negotiated=false;Object.assign(this,e)}};var re=class{static{a(this,\"RTCRtpCodecParameters\")}constructor(e){this.rtcpFeedback=[];this.direction=\"all\";Object.assign(this,e)}get name(){return this.mimeType.split(\"/\")[1]}get contentType(){return this.mimeType.split(\"/\")[0]}get str(){let e=`${this.name}/${this.clockRate}`;if(this.channels===2)e+=\"/2\";return e}};var Te=class{static{a(this,\"RTCRtpHeaderExtensionParameters\")}constructor(e){Object.assign(this,e)}};var Li=class{static{a(this,\"RTCRtcpFeedback\")}constructor(e={}){Object.assign(this,e)}};var Di=class{static{a(this,\"RTCRtpRtxParameters\")}constructor(e={}){Object.assign(this,e)}};var Ni=class{static{a(this,\"RTCRtpCodingParameters\")}constructor(e){Object.assign(this,e)}};var es=class{static{a(this,\"RTCRtpSimulcastParameters\")}constructor(e){Object.assign(this,e)}};var Wo=require(\"node:crypto\");var ts=1;var ct=7;var qc=a(r=>{switch(r){case ts:case ct:return 16}},\"keyLength\");var Fc=a(r=>{switch(r){case ts:return 14;case ct:return 12}},\"saltLength\");function Kc(r){if(!Number.isInteger(r)||r<0||!Number.isSafeInteger(r)){throw new Error(\"LEB128 encode requires a non-negative safe integer\")}const e=[];let t=r;do{let s=t&127;t=Math.floor(t/128);if(t!==0){s|=128}e.push(s)}while(t!==0);return Buffer.from(e)}a(Kc,\"leb128encode\");var Hl=b(\"webrtc/rtp/codec/av1\");var Ho=class r{static{a(this,\"AV1RtpPayload\")}constructor(){this.obu_or_fragment=[]}static{this.deSerialize=e=>{const t=new r;let s=0;t.zBit_RtpStartsWithFragment=k(e[s],0);t.yBit_RtpEndsWithFragment=k(e[s],1);t.w_RtpNumObus=k(e[s],2,2);t.nBit_RtpStartsNewCodedVideoSequence=k(e[s],4);s++;if(t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment){throw new Error}[...Array(t.w_RtpNumObus-1).keys()].forEach(n=>{const[o,c]=zl(e.subarray(s));const d=s+c;const h=d+o;let l=false;if(t.zBit_RtpStartsWithFragment&&n===0){l=true}t.obu_or_fragment.push({data:e.subarray(d,h),isFragment:l});s+=c+o});let i=false;if(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment){i=true}t.obu_or_fragment.push({data:e.subarray(s),isFragment:i});return t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){const t=[];const s=e.flatMap(c=>c.obu_or_fragment).reduce((c,d,h)=>{c[h]=d;return c},{});const i=Object.keys(s).length;for(const c of Object.keys(s).map(Number)){const d=s[c];if(!d)continue;const{data:h,isFragment:l}=d;if(l){let u=[];for(let g=c;g<i;g++){const S=s[g];if(S.isFragment){u.push(S.data);delete s[g]}else{break}}if(u.length<=1){Hl(\"fragment lost, maybe packet lost\");u=[]}t.push(Buffer.concat(u))}else{t.push(h)}}const n=t.map(c=>zo.deSerialize(c));const o=n.pop();return Buffer.concat([...n.map(c=>{c.obu_has_size_field=1;return c.serialize()}),o.serialize()])}};var zo=class r{static{a(this,\"AV1Obu\")}static deSerialize(e){const t=new r;let s=0;t.obu_forbidden_bit=k(e[s],0);t.obu_type=Gc[k(e[s],1,4)];t.obu_extension_flag=k(e[s],5);t.obu_has_size_field=k(e[s],6);t.obu_reserved_1bit=k(e[s],7);s++;t.payload=e.subarray(s);return t}serialize(){const e=new gt(8).set(this.obu_forbidden_bit).set(ql[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;let t=Buffer.alloc(0);if(this.obu_has_size_field){t=Kc(this.payload.length)}return Buffer.concat([e,t,this.payload])}};function zl(r){let e=0;let t=0;for(let s=0;s<8;s++){if(s>=r.length){throw new Error(\"LEB128 decode incomplete\")}const i=r.readUInt8(s);e+=(i&127)*128**s;t++;if(!(i&128)){if(!Number.isSafeInteger(e)){throw new Error(\"LEB128 value exceeds safe integer\")}return[e,t]}}throw new Error(\"LEB128 decode incomplete\")}a(zl,\"leb128decode\");var Gc={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\"};var ql=Object.entries(Gc).reduce((r,[e,t])=>{r[t]=Number(e);return r},{});var tS=Buffer.from([0,0,0,1]);function qo(r,e){const t=Buffer.alloc(e);r.copy(t);return t}a(qo,\"growBufferSize\");function ss(r){return Number.parseInt(r.toString(),10)}a(ss,\"Int\");function jc(r){const e=r[0];return e>127&&e<192}a(jc,\"isMedia\");var mr=4;var V=class r{static{a(this,\"RtcpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.count=0;this.type=0;this.length=0;Object.assign(this,e)}static serialize(e,t,s,i){const n=new r({type:e,count:t,version:2,length:i});const o=n.serialize();return Buffer.concat([o,s])}serialize(){const e=new ze(8);e.set(2,0,this.version);if(this.padding)e.set(1,2,1);e.set(5,3,this.count);const t=N([1,1,2],[e.value,this.type,this.length]);return t}static deSerialize(e){const[t,s,i]=F(e,[1,1,2]);const n=k(t,0,2);const o=k(t,2,1)>0;const c=k(t,3,5);return new r({version:n,padding:o,count:c,type:s,length:i})}};var gr=class r{static{a(this,\"FullIntraRequest\")}static{this.count=4}constructor(e={}){this.count=r.count;this.fir=[];Object.assign(this,e)}get length(){return this.serialize().length/4}static deSerialize(e){const[t,s]=F(e,[4,4]);const i=[];for(let n=8;n<e.length;n+=8){i.push({ssrc:e.readUInt32BE(n),sequenceNumber:e[n+4]})}return new r({senderSsrc:t,mediaSsrc:s,fir:i})}serialize(){const e=N([4,4],[this.senderSsrc,this.mediaSsrc]);const t=Buffer.alloc(this.fir.length*8);this.fir.forEach(({ssrc:s,sequenceNumber:i},n)=>{t.writeUInt32BE(s,n*8);t[n*8+4]=i});return Buffer.concat([e,t])}};var Fe=class r{static{a(this,\"PictureLossIndication\")}static{this.count=1}constructor(e={}){this.count=r.count;this.length=2;Object.assign(this,e)}static deSerialize(e){const[t,s]=F(e,[4,4]);return new r({senderSsrc:t,mediaSsrc:s})}serialize(){return N([4,4],[this.senderSsrc,this.mediaSsrc])}};var Ke=class r{static{a(this,\"ReceiverEstimatedMaxBitrate\")}static{this.count=15}constructor(e={}){this.count=r.count;this.uniqueID=\"REMB\";this.ssrcNum=0;this.ssrcFeedbacks=[];Object.assign(this,e)}static deSerialize(e){const[t,s,i,n,o]=F(e,[4,4,4,1,1]);const c=k(o,0,6);const d=(k(o,6,2)<<16)+(e[14]<<8)+e[15];const h=c>46?18446744073709551615n:BigInt(d)<<BigInt(c);const l=[];for(let u=16;u<e.length;u+=4){const g=e.slice(u).readUIntBE(0,4);l.push(g)}return new r({senderSsrc:t,mediaSsrc:s,uniqueID:N([4],[i]).toString(),ssrcNum:n,brExp:c,brMantissa:d,ssrcFeedbacks:l,bitrate:h})}serialize(){const e=Buffer.concat([N([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),N([1],[this.ssrcNum])]);const t=new ze(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);const s=Buffer.concat(this.ssrcFeedbacks.map(n=>N([4],[n])));const i=Buffer.concat([e,N([3],[t.value]),s]);this.length=i.length/4;return i}};var Kl=b(\"webrtc/rtp/rtcp/psfb/index\");var we=class r{static{a(this,\"RtcpPayloadSpecificFeedback\")}static{this.type=206}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return V.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case gr.count:s=gr.deSerialize(e);break;case Fe.count:s=Fe.deSerialize(e);break;case Ke.count:s=Ke.deSerialize(e);break;default:Kl(\"unknown psfb packet\",t.count);break}return new r({feedback:s})}};var be=class r{static{a(this,\"RtcpRrPacket\")}static{this.type=201}constructor(e={}){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}serialize(){let e=N([4],[this.ssrc]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return V.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const[s]=F(e,[4]);let i=4;const n=[];for(let o=0;o<t;o++){n.push(wt.deSerialize(e.slice(i,i+24)));i+=24}return new r({ssrc:s,reports:n})}};var wt=class r{static{a(this,\"RtcpReceiverInfo\")}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 N([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){const[t,s,i,n,o,c,d]=F(e,[4,1,3,4,4,4,4]);return new r({ssrc:t,fractionLost:s,packetsLost:i,highestSequence:n,jitter:o,lsr:c,dlsr:d})}};var Mi=205;var Ge=class r{static{a(this,\"GenericNack\")}static{this.count=1}toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){this.count=r.count;this.lost=[];Object.assign(this,e);if(!this.header){this.header=new V({type:Mi,count:this.count,version:2})}}static deSerialize(e,t){const[s,i]=F(e,[4,4]);const n=[];for(let o=8;o<e.length;o+=4){const[c,d]=F(e.subarray(o),[2,2]);n.push(c);for(let h=0;h<16;h++){if(d>>h&1){n.push(c+h+1)}}}return new r({header:t,senderSsrc:s,mediaSourceSsrc:i,lost:n})}serialize(){const e=N([4,4],[this.senderSsrc,this.mediaSourceSsrc]);const t=[];if(this.lost.length>0){let i=this.lost[0],n=0;this.lost.slice(1).forEach(o=>{const c=o-i-1;if(c>=0&&c<16){n|=1<<c}else{t.push(N([2,2],[i,n]));i=o;n=0}});t.push(N([2,2],[i,n]))}const s=Buffer.concat([e,Buffer.concat(t)]);this.header.length=s.length/4;return Buffer.concat([this.header.serialize(),s])}};var Gl=b(\"webrtc/rtp/rtcp/rtpfb/twcc\");var je=class r{static{a(this,\"TransportWideCC\")}static{this.count=15}constructor(e={}){this.count=r.count;this.length=2;this.packetChunks=[];this.recvDeltas=[];Object.assign(this,e);if(!this.header){this.header=new V({type:205,count:this.count,version:2})}}static deSerialize(e,t){const[s,i,n,o,c,d]=F(e,[4,4,2,2,3,1]);const h=[];const l=[];let u=16;for(let S=0;S<o;){const p=k(e.slice(u,u+1)[0],0,1);let f;switch(p){case dt.TypeTCCRunLengthChunk:{const y=rs.deSerialize(e.slice(u,u+2));f=y;const m=Math.min(o-S,y.runLength);if(y.packetStatus===z.TypeTCCPacketReceivedSmallDelta||y.packetStatus===z.TypeTCCPacketReceivedLargeDelta){for(let T=0;T<m;T++){l.push(new bt({type:y.packetStatus}))}}S+=m}break;case dt.TypeTCCStatusVectorChunk:{const y=Sr.deSerialize(e.slice(u,u+2));f=y;if(y.symbolSize===0){y.symbolList.forEach(m=>{if(m===z.TypeTCCPacketReceivedSmallDelta){l.push(new bt({type:z.TypeTCCPacketReceivedSmallDelta}))}})}if(y.symbolSize===1){y.symbolList.forEach(m=>{if(m===z.TypeTCCPacketReceivedSmallDelta||m===z.TypeTCCPacketReceivedLargeDelta){l.push(new bt({type:m}))}})}S+=y.symbolList.length}break}if(!f)throw new Error;u+=2;h.push(f)}let g=u;l.forEach(S=>{if(S.type===z.TypeTCCPacketReceivedSmallDelta){S.deSerialize(e.slice(g,g+1));g++}if(S.type===z.TypeTCCPacketReceivedLargeDelta){S.deSerialize(e.slice(g,g+2));g+=2}});return new r({senderSsrc:s,mediaSourceSsrc:i,baseSequenceNumber:n,packetStatusCount:o,referenceTime:c,fbPktCount:d,recvDeltas:l,packetChunks:h,header:t})}serialize(){const e=N([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]);const t=Buffer.concat(this.packetChunks.map(o=>o.serialize()));const s=Buffer.concat(this.recvDeltas.map(o=>{try{return o.serialize()}catch(c){Gl(c?.message);return void 0}}).filter(o=>o));const i=Buffer.concat([e,t,s]);const n=i.length%4;this.header.padding=n!==0;if(n!==0){const o=Buffer.alloc(4-n);o[o.length-1]=o.length;this.header.length=(i.length+o.length)/4;return Buffer.concat([this.header.serialize(),i,o])}this.header.length=i.length/4;return Buffer.concat([this.header.serialize(),i])}get packetResults(){const e=[];for(const n of this.packetChunks){if(n instanceof rs){for(let o=0;o<n.runLength;o++)e.push(n.packetStatus)}else{e.push(...n.symbolList)}}if(e.length>this.packetStatusCount)e.length=this.packetStatusCount;const t=[];let s=this.referenceTime*64e3;let i=0;e.forEach((n,o)=>{const c=new Fo({sequenceNumber:this.baseSequenceNumber+o&65535});if(n===z.TypeTCCPacketReceivedSmallDelta||n===z.TypeTCCPacketReceivedLargeDelta){const d=this.recvDeltas[i++];if(d){s+=d.delta;c.received=true;c.delta=d.delta;c.receivedAtMs=s/1e3}}t.push(c)});return t}};var rs=class r{static{a(this,\"RunLengthChunk\")}constructor(e={}){Object.assign(this,e);this.type=dt.TypeTCCRunLengthChunk}static deSerialize(e){const t=k(e[0],1,2);const s=(k(e[0],3,5)<<8)+e[1];return new r({type:0,packetStatus:t,runLength:s})}serialize(){const e=new gt(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer;return e}};var Sr=class r{static{a(this,\"StatusVectorChunk\")}constructor(e={}){this.symbolList=[];Object.assign(this,e)}static deSerialize(e){const t=dt.TypeTCCStatusVectorChunk;let s=k(e[0],1,1);const i=[];function n(o,c){for(let d=0;d<o;d++){c(d)}}a(n,\"range\");switch(s){case 0:n(6,o=>i.push(k(e[0],2+o,1)));n(8,o=>i.push(k(e[1],o,1)));break;case 1:n(3,o=>i.push(k(e[0],2+o*2,2)));n(4,o=>i.push(k(e[1],o*2,2)));break;default:s=(k(e[0],2,6)<<8)+e[1]}return new r({type:t,symbolSize:s,symbolList:i})}serialize(){const e=Buffer.alloc(2);const t=new gt(16).set(1).set(this.symbolSize);const s=this.symbolSize===0?1:2;this.symbolList.forEach(i=>{t.set(i,s)});e.writeUInt16BE(t.value);return e}};var bt=class r{static{a(this,\"RecvDelta\")}constructor(e={}){this.parsed=false;Object.assign(this,e)}static deSerialize(e){let t;let s;if(e.length===1){t=z.TypeTCCPacketReceivedSmallDelta;s=250*e[0]}else if(e.length===2){t=z.TypeTCCPacketReceivedLargeDelta;s=250*e.readInt16BE()}if(t===void 0||s===void 0)throw new Error;return new r({type:t,delta:s})}deSerialize(e){const t=r.deSerialize(e);this.delta=t.delta}parseDelta(){this.delta=Math.floor(this.delta/250);if(this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=z.TypeTCCPacketReceivedLargeDelta}else{if(!this.type)this.type=z.TypeTCCPacketReceivedSmallDelta}this.parsed=true}serialize(){if(!this.parsed)this.parseDelta();if(this.type===z.TypeTCCPacketReceivedSmallDelta){const e=Buffer.alloc(1);e.writeUInt8(this.delta);return e}else if(this.type===z.TypeTCCPacketReceivedLargeDelta){const e=Buffer.alloc(2);e.writeInt16BE(this.delta);return e}throw new Error(\"errDeltaExceedLimit \"+this.delta+\" \"+this.type)}};var dt;(function(r){r[r[\"TypeTCCRunLengthChunk\"]=0]=\"TypeTCCRunLengthChunk\";r[r[\"TypeTCCStatusVectorChunk\"]=1]=\"TypeTCCStatusVectorChunk\";r[r[\"packetStatusChunkLength\"]=2]=\"packetStatusChunkLength\"})(dt||(dt={}));var z;(function(r){r[r[\"TypeTCCPacketNotReceived\"]=0]=\"TypeTCCPacketNotReceived\";r[r[\"TypeTCCPacketReceivedSmallDelta\"]=1]=\"TypeTCCPacketReceivedSmallDelta\";r[r[\"TypeTCCPacketReceivedLargeDelta\"]=2]=\"TypeTCCPacketReceivedLargeDelta\";r[r[\"TypeTCCPacketReceivedWithoutDelta\"]=3]=\"TypeTCCPacketReceivedWithoutDelta\"})(z||(z={}));var Fo=class{static{a(this,\"PacketResult\")}constructor(e){this.sequenceNumber=0;this.delta=0;this.received=false;this.receivedAtMs=0;Object.assign(this,e)}};var jl=b(\"webrtc/rtp/rtcp/rtpfb/index\");var Z=class r{static{a(this,\"RtcpTransportLayerFeedback\")}static{this.type=Mi}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return e}static deSerialize(e,t){let s;switch(t.count){case Ge.count:s=Ge.deSerialize(e,t);break;case je.count:s=je.deSerialize(e,t);break;default:jl(\"unknown rtpfb packet\",t.count);break}return new r({feedback:s,header:t})}};var We=class r{static{a(this,\"RtcpSourceDescriptionPacket\")}static{this.type=202}constructor(e){this.type=r.type;this.chunks=[];Object.assign(this,e)}get length(){let e=0;this.chunks.forEach(t=>e+=t.length);return e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));while(e.length%4)e=Buffer.concat([e,Buffer.from([0])]);return V.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){const s=[];for(let i=0;i<e.length;){const n=yr.deSerialize(e.slice(i));s.push(n);i+=n.length}return new r({chunks:s})}};var yr=class r{static{a(this,\"SourceDescriptionChunk\")}constructor(e={}){this.items=[];Object.assign(this,e)}get length(){let e=4;this.items.forEach(t=>e+=t.length);e+=1;e+=Wc(e);return e}serialize(){const e=Buffer.concat([N([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);const t=Buffer.concat([e,Buffer.alloc(Wc(e.length))]);return t}static deSerialize(e){const t=e.readUInt32BE();const s=[];for(let i=4;i<e.length;){const n=e[i];if(n===0)break;const o=Tr.deSerialize(e.slice(i));s.push(o);i+=o.length}return new r({source:t,items:s})}};var Tr=class r{static{a(this,\"SourceDescriptionItem\")}constructor(e){Object.assign(this,e)}get length(){return 1+1+Buffer.from(this.text).length}serialize(){const e=Buffer.from(this.text);return Buffer.concat([N([1,1],[this.type,e.length]),e])}static deSerialize(e){const t=e[0];const s=e[1];const i=e.slice(2,2+s).toString();return new r({type:t,text:i})}};function Wc(r){if(r%4==0){return 0}return 4-r%4}a(Wc,\"getPadding\");var ue=class r{static{a(this,\"RtcpSrPacket\")}static{this.type=200}constructor(e){this.ssrc=0;this.reports=[];this.type=r.type;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);e.writeUInt32BE(this.ssrc);e=Buffer.concat([e,this.senderInfo.serialize()]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return V.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const s=e.readUInt32BE();const i=wr.deSerialize(e.subarray(4,24));let n=24;const o=[];for(let d=0;d<t;d++){o.push(wt.deSerialize(e.subarray(n,n+24)));n+=24}const c=new r({ssrc:s,senderInfo:i,reports:o});return c}};var wr=class r{static{a(this,\"RtcpSenderInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:Wl(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return N([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){const[t,s,i,n]=F(e,[8,4,4,4]);return new r({ntpTimestamp:t,rtpTimestamp:s,packetCount:i,octetCount:n})}};var Wl=a(r=>{const[e,t]=F(N([8],[r]),[4,4]);return Number(`${e}.${t}`)},\"ntpTime2Sec\");var $l=b(\"webrtc/rtp/rtcp/rtcp\");var Oi=class{static{a(this,\"RtcpPacketConverter\")}static deSerialize(e){let t=0;const s=[];while(t<e.length){const i=V.deSerialize(e.subarray(t,t+mr));t+=mr;let n=e.subarray(t,t+i.length*4);t+=i.length*4;if(i.padding){n=n.subarray(0,n.length-n.subarray(-1)[0])}try{switch(i.type){case ue.type:s.push(ue.deSerialize(n,i.count));break;case be.type:s.push(be.deSerialize(n,i.count));break;case We.type:s.push(We.deSerialize(n,i));break;case Z.type:s.push(Z.deSerialize(n,i));break;case we.type:s.push(we.deSerialize(n,i));break;default:break}}catch(o){$l(\"deSerialize RTCP\",o)}}return s}};function $c(r){return r.length>=2&&r[1]>=192&&r[1]<=208}a($c,\"isRtcp\");var M={sdesMid:\"urn:ietf:params:rtp-hdrext:sdes:mid\",sdesRTPStreamID:\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",repairedRtpStreamId:\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\",transportWideCC:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\",absSendTime:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\",dependencyDescriptor:\"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension\",audioLevelIndication:\"urn:ietf:params:rtp-hdrext:ssrc-audio-level\",videoOrientation:\"urn:3gpp:video-orientation\"};function Vc(r,e){return r.map(t=>{const s=e[t.id];if(!s){return{uri:\"unknown\",value:t.payload}}switch(s){case M.sdesMid:case M.sdesRTPStreamID:case M.repairedRtpStreamId:return{uri:s,value:Vl(t.payload)};case M.transportWideCC:return{uri:s,value:Yl(t.payload)};case M.absSendTime:return{uri:s,value:Ql(t.payload)};case M.audioLevelIndication:{return{uri:s,value:Xl(t.payload)}}case M.videoOrientation:return{uri:s,value:Jl(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>{if(s)t[s.uri]=s.value;return t},{})}a(Vc,\"rtpHeaderExtensionsParser\");function Yc(r){return Buffer.from(r)}a(Yc,\"serializeSdesMid\");function Qc(r){return Buffer.from(r)}a(Qc,\"serializeSdesRTPStreamID\");function Xc(r){return Buffer.from(r)}a(Xc,\"serializeRepairedRtpStreamId\");function Ko(r){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(r);return e}a(Ko,\"serializeTransportWideCC\");function Vl(r){return r.toString()}a(Vl,\"deserializeString\");function Yl(r){return r.readUInt16BE()}a(Yl,\"deserializeUint16BE\");function Ql(r){return F(r,[3])[0]}a(Ql,\"deserializeAbsSendTime\");function Xl(r){const e=new Pe(r);const t={v:e.readBits(1)===1,level:e.readBits(7)};return t}a(Xl,\"deserializeAudioLevelIndication\");function Jl(r){const e=new Pe(r);e.readBits(4);const t={c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)};return t}a(Jl,\"deserializeVideoOrientation\");var Zl=b(\"packages/rtp/src/rtp/red/packet.ts\");var is=class r{static{a(this,\"Red\")}constructor(){this.blocks=[]}static deSerialize(e){const t=e instanceof ArrayBuffer?Buffer.from(e):e;const s=new r;let i=0;[s.header,i]=Ui.deSerialize(t);s.header.fields.forEach(({blockLength:n,timestampOffset:o,blockPT:c})=>{if(n&&o){const d=t.subarray(i,i+n);s.blocks.push({block:d,blockPT:c,timestampOffset:o});i+=n}else{const d=t.subarray(i);s.blocks.push({block:d,blockPT:c})}});return s}serialize(){this.header=new Ui;for(const{timestampOffset:t,blockPT:s,block:i}of this.blocks){if(t){this.header.fields.push({fBit:1,blockPT:s,blockLength:i.length,timestampOffset:t})}else{this.header.fields.push({fBit:0,blockPT:s})}}let e=this.header.serialize();for(const{block:t}of this.blocks){e=Buffer.concat([e,t])}return e}};var Ui=class r{static{a(this,\"RedHeader\")}constructor(){this.fields=[]}static deSerialize(e){let t=0;const s=new r;for(;;){const i={};s.fields.push(i);const n=new Pe(e.subarray(t));i.fBit=n.readBits(1);i.blockPT=n.readBits(7);t++;if(i.fBit===0){break}i.timestampOffset=n.readBits(14);i.blockLength=n.readBits(10);t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(const t of this.fields){try{if(t.timestampOffset&&t.blockLength){const s=new Pe(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,s.uint8Array])}else{const s=new Pe(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){Zl(s?.message)}}return e}};var Hi=class{static{a(this,\"RedEncoder\")}constructor(e=1){this.distance=e;this.cache=[];this.cacheSize=10}push(e){this.cache.push(e);if(this.cache.length>this.cacheSize){this.cache.shift()}}build(){const e=new is;const t=this.cache.slice(-(this.distance+1));const s=t.pop();if(!s){return e}t.forEach(i=>{const n=Ae(s.timestamp,-i.timestamp);if(n>ef){return}e.blocks.push({block:i.block,blockPT:i.blockPT,timestampOffset:n})});e.blocks.push({block:s.block,blockPT:s.blockPT});return e}};var ef=(1<<14)-1;var zi=class{static{a(this,\"RedHandler\")}constructor(){this.size=150;this.sequenceNumbers=[]}push(e,t){const s=[];e.blocks.forEach(({blockPT:n,timestampOffset:o,block:c},d)=>{const h=j(t.header.sequenceNumber,-(e.blocks.length-(d+1)));if(o){s.push(new W(new ee({timestamp:Ae(t.header.timestamp,-o),payloadType:n,ssrc:t.header.ssrc,sequenceNumber:h,marker:true}),c))}else{s.push(new W(new ee({timestamp:t.header.timestamp,payloadType:n,ssrc:t.header.ssrc,sequenceNumber:h,marker:true}),c))}});const i=s.filter(n=>{if(this.sequenceNumbers.includes(n.header.sequenceNumber)){return false}else{if(this.sequenceNumbers.length>this.size){this.sequenceNumbers.shift()}this.sequenceNumbers.push(n.header.sequenceNumber);return true}});return i}};var Ct={OneByte:48862,TwoByte:4096};var Jc=2;var Zc=4;var ed=8;var td=12;var sd=4;var ee=class r{static{a(this,\"RtpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.paddingSize=0;this.extension=false;this.marker=false;this.payloadOffset=0;this.payloadType=0;this.sequenceNumber=0;this.timestamp=0;this.ssrc=0;this.csrcLength=0;this.csrc=[];this.extensionProfile=Ct.OneByte;this.extensions=[];Object.assign(this,e)}static deSerialize(e){const t=new r;let s=0;const i=e[s++];t.version=k(i,0,2);t.padding=k(i,2)>0;t.extension=k(i,3)>0;t.csrcLength=k(i,4,4);t.csrc=[...Array(t.csrcLength)].map(()=>{const o=e.readUInt32BE(s);s+=4;return o});s+=td-1;const n=e[1];t.marker=k(n,0)>0;t.payloadType=k(n,1,7);t.sequenceNumber=e.readUInt16BE(Jc);t.timestamp=e.readUInt32BE(Zc);t.ssrc=e.readUInt32BE(ed);for(let o=0;o<t.csrc.length;o++){const c=td+o*sd;t.csrc[o]=e.subarray(c).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE();s+=2;const o=e.subarray(s).readUInt16BE()*4;t.extensionLength=o;s+=2;switch(t.extensionProfile){case Ct.OneByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const d=e[s]>>4;const h=(e[s]&(e[s]^240))+1;s++;if(d===15){break}const l={id:d,payload:e.subarray(s,s+h)};t.extensions=[...t.extensions,l];s+=h}}break;case Ct.TwoByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const d=e[s];s++;const h=e[s];s++;const l={id:d,payload:e.subarray(s,s+h)};t.extensions=[...t.extensions,l];s+=h}}break;default:{const c={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,c];s+=t.extensions[0].payload.length}break}}t.payloadOffset=s;if(t.padding){t.paddingSize=e[e.length-1]}return t}get serializeSize(){const{csrc:e,extensionProfile:t,extensions:s}=this;let i=12+e.length*sd;if(s.length>0||this.extension===true){let n=4;switch(t){case Ct.OneByte:for(const o of s){n+=1+o.payload.length}break;case Ct.TwoByte:for(const o of s){n+=2+o.payload.length}break;default:n+=s[0].payload.length}i+=Math.floor((n+3)/4)*4}return i}serialize(e){const t=Buffer.alloc(e);let s=0;const i=new ze(8);i.set(2,0,this.version);if(this.padding)i.set(1,2,1);if(this.extensions.length>0)this.extension=true;if(this.extension)i.set(1,3,1);i.set(4,4,this.csrc.length);t.writeUInt8(i.value,s++);const n=new ze(8);if(this.marker)n.set(1,0,1);n.set(7,1,this.payloadType);t.writeUInt8(n.value,s++);t.writeUInt16BE(this.sequenceNumber,Jc);s+=2;t.writeUInt32BE(this.timestamp,Zc);s+=4;t.writeUInt32BE(this.ssrc,ed);s+=4;for(const o of this.csrc){t.writeUInt32BE(o,s);s+=4}if(this.extension){const o=s;t.writeUInt16BE(this.extensionProfile,s);s+=4;const c=s;switch(this.extensionProfile){case Ct.OneByte:for(const l of this.extensions){t.writeUInt8(l.id<<4|l.payload.length-1,s++);l.payload.copy(t,s);s+=l.payload.length}break;case Ct.TwoByte:for(const l of this.extensions){t.writeUInt8(l.id,s++);t.writeUInt8(l.payload.length,s++);l.payload.copy(t,s);s+=l.payload.length}break;default:{const l=this.extensions[0].payload.length;if(l%4!=0){throw new Error}this.extensions[0].payload.copy(t,s);s+=l}}const d=s-c;const h=Math.trunc((d+3)/4)*4;t.writeUInt16BE(Math.trunc(h/4),o+2);for(let l=0;l<h-d;l++){t.writeUInt8(0,s);s++}}this.payloadOffset=s;return t}};var W=class r{static{a(this,\"RtpPacket\")}constructor(e,t){this.header=e;this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new r(new ee({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length);const{payloadOffset:t}=this.header;this.payload.copy(e,t);if(this.header.padding){const 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){const t=ee.deSerialize(e);const s=new r(t,e.subarray(t.payloadOffset,e.length-t.paddingSize));return s}clear(){this.payload=null}};function rd(r,e,t){const s=new W(new ee({payloadType:e,marker:r.header.marker,sequenceNumber:r.payload.readUInt16BE(0),timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2));return s}a(rd,\"unwrapRtx\");function id(r,e,t,s){const i=Buffer.allocUnsafe(2);i.writeUInt16BE(r.header.sequenceNumber,0);const n=new W(new ee({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([i,r.payload]));return n}a(id,\"wrapRtx\");var cs=require(\"node:crypto\");var Ce=require(\"node:crypto\");var ns=class{static{a(this,\"CipherAesBase\")}constructor(e,t,s,i){this.srtpSessionKey=e;this.srtpSessionSalt=t;this.srtcpSessionKey=s;this.srtcpSessionSalt=i}encryptRtp(e,t,s){return Buffer.from([])}decryptRtp(e,t,s){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}};var le=class extends Error{static{a(this,\"SrtpAuthenticationError\")}constructor(e){super(e);this.name=\"SrtpAuthenticationError\"}};var nd=12;var tf=8;function os(r,e,t=\"Failed to authenticate SRTP packet\"){const s=r.length-e;br(r.length>=nd+e,t);const i=od(()=>ee.deSerialize(r.subarray(0,s)),t);i.paddingSize=0;br(i.payloadOffset>=nd&&i.payloadOffset<=s,t);return i}a(os,\"parseSrtpRtpHeader\");function qi(r,e,t,s=\"Failed to authenticate SRTCP packet\"){br(r.length>=tf+e+t,s);return od(()=>V.deSerialize(r.subarray(0,mr)),s)}a(qi,\"parseSrtcpHeader\");function br(r,e){if(!r){throw new le(e)}}a(br,\"assertAuthenticatedPacketLength\");function od(r,e){try{return r()}catch{throw new le(e)}}a(od,\"wrapAuthenticationError\");function Fi(r,e,t=\"Failed to authenticate SRTP packet\"){if(!r.padding){r.paddingSize=0;return r}br(e.length>r.payloadOffset,t);const s=e[e.length-1];br(s>0&&s<=e.length-r.payloadOffset,t);r.paddingSize=s;return r}a(Fi,\"finalizeSrtpRtpHeader\");var Ki=class extends ns{static{a(this,\"CipherAesCtr\")}constructor(e,t,s,i,n,o){super(e,t,s,i);this.srtpSessionAuthTag=n;this.srtcpSessionAuthTag=o;this.authTagLength=10}encryptRtp(e,t,s){const i=e.serialize(e.serializeSize);const n=this.generateCounter(e.sequenceNumber,s,e.ssrc,this.srtpSessionSalt);const o=(0,Ce.createCipheriv)(\"aes-128-ctr\",this.srtpSessionKey,n);const c=o.update(t);const d=this.generateSrtpAuthTag(s,i,c);return Buffer.concat([i,c,d])}decryptRtp(e,t,s=os(e,this.authTagLength)){const i=e.length-this.authTagLength;const n=e.subarray(0,i);const o=e.subarray(i);const c=this.generateSrtpAuthTag(t,n.subarray(0,s.payloadOffset),n.subarray(s.payloadOffset));cd(o,c,\"Failed to authenticate SRTP packet\");const d=this.generateCounter(s.sequenceNumber,t,s.ssrc,this.srtpSessionSalt);const h=(0,Ce.createDecipheriv)(\"aes-128-ctr\",this.srtpSessionKey,d);const l=n.subarray(s.payloadOffset);const u=h.update(l);const g=Buffer.concat([n.subarray(0,s.payloadOffset),u]);return[g,Fi(s,g,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){let s=Buffer.from(e);const i=s.readUInt32BE(4);const n=this.generateCounter(t&65535,t>>16,i,this.srtcpSessionSalt);const o=(0,Ce.createCipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,n);const c=o.update(s.slice(8));c.copy(s,8);s=Buffer.concat([s,Buffer.alloc(4)]);s.writeUInt32BE(t,s.length-4);s[s.length-4]|=128;const d=this.generateSrtcpAuthTag(s);s=Buffer.concat([s,d]);return s}decryptRTCP(e){const t=qi(e,this.authTagLength,ad);const s=e.length-(this.authTagLength+ad);const i=e.subarray(0,e.length-this.authTagLength);const n=e.subarray(e.length-this.authTagLength);const o=this.generateSrtcpAuthTag(i);cd(n,o,\"Failed to authenticate SRTCP packet\");const c=Buffer.from(e).slice(0,s);const d=e[s]>>>7;if(d===0)return[c,t];let h=e.readUInt32BE(s);h&=~(1<<31);const l=e.readUInt32BE(4);const u=this.generateCounter(h&65535,h>>16,l,this.srtcpSessionSalt);const g=(0,Ce.createDecipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,u);const S=g.update(c.subarray(8));S.copy(c,8);return[c,t]}generateSrtcpAuthTag(e){const t=(0,Ce.createHmac)(\"sha1\",this.srtcpSessionAuthTag);return t.update(e).digest().slice(0,10)}generateCounter(e,t,s,i){const n=Buffer.alloc(16);n.writeUInt32BE(s,4);n.writeUInt32BE(t,8);n.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let o=0;o<i.length;o++){n[o]^=i[o]}return n}generateSrtpAuthTag(e,...t){const s=(0,Ce.createHmac)(\"sha1\",this.srtpSessionAuthTag);const i=Buffer.alloc(4);i.writeUInt32BE(e);for(const n of t){s.update(n)}return s.update(i).digest().subarray(0,10)}};var ad=4;function cd(r,e,t){if(r.length!==e.length||!(0,Ce.timingSafeEqual)(r,e)){throw new le(t)}}a(cd,\"assertAuthTag\");var as=require(\"node:crypto\");var Gi=class extends ns{static{a(this,\"CipherAesGcm\")}constructor(e,t,s,i){super(e,t,s,i);this.aeadAuthTagLen=16;this.rtpIvWriter=or([2,4,4,2],true);this.rtcpIvWriter=or([2,4,2,4],true);this.aadWriter=or([4],true)}encryptRtp(e,t,s){const i=e.serialize(e.serializeSize);const n=this.rtpInitializationVector(e,s);const o=(0,as.createCipheriv)(\"aes-128-gcm\",this.srtpSessionKey,n);o.setAAD(i);const c=o.update(t);o.final();const d=o.getAuthTag();const h=Buffer.concat([i,c,d]);return h}decryptRtp(e,t,s=os(e,this.aeadAuthTagLen)){const i=e.subarray(0,s.payloadOffset);const n=e.length-this.aeadAuthTagLen;const o=e.subarray(n);let c=Buffer.from([]);c=qo(c,e.length-this.aeadAuthTagLen);i.copy(c);const d=this.rtpInitializationVector(s,t);const h=e.slice(s.payloadOffset,n);const l=(0,as.createDecipheriv)(\"aes-128-gcm\",this.srtpSessionKey,d);l.setAAD(i);l.setAuthTag(o);const u=l.update(h);hd(l,\"SRTP\");u.copy(c,s.payloadOffset);return[c,Fi(s,c,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){const s=e.readUInt32BE(4);const i=e.length+this.aeadAuthTagLen;let n=Buffer.from([]);n=qo(n,i+Go);e.slice(0,8).copy(n);const o=this.rtcpInitializationVector(s,t);const c=this.rtcpAdditionalAuthenticatedData(e,t);const d=(0,as.createCipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,o);d.setAAD(c);const h=d.update(e.slice(8));d.final();h.copy(n,8);const l=d.getAuthTag();l.copy(n,8+h.length);c.slice(8,12).copy(n,i);return n}decryptRTCP(e){const t=qi(e,this.aeadAuthTagLen,Go);const s=e.length-Go;const i=s-this.aeadAuthTagLen;const n=e.readUInt32BE(4);const o=e.readUInt32BE(s);const c=o>>>31===1;const d=o&~(dd<<24);const h=this.rtcpInitializationVector(n,d);const l=c?Buffer.concat([e.subarray(0,8),e.subarray(s)]):Buffer.concat([e.subarray(0,i),e.subarray(s)]);const u=c?e.slice(8,i):Buffer.alloc(0);const g=c?Buffer.alloc(i):Buffer.from(e.subarray(0,i));if(c){e.slice(0,8).copy(g)}const S=(0,as.createDecipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,h);S.setAAD(l);S.setAuthTag(e.subarray(i,s));const p=S.update(u);hd(S,\"SRTCP\");if(c){p.copy(g,8)}return[g,t]}rtpInitializationVector(e,t){const s=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let i=0;i<s.length;i++){s[i]^=this.srtpSessionSalt[i]}return s}rtcpInitializationVector(e,t){const s=this.rtcpIvWriter([0,e,0,t]);for(let i=0;i<s.length;i++){s[i]^=this.srtcpSessionSalt[i]}return s}rtcpAdditionalAuthenticatedData(e,t){const s=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);s[8]|=dd;return s}};var Go=4;var dd=128;function hd(r,e){try{r.final()}catch{throw new le(`Failed to authenticate ${e} packet`)}}a(hd,\"finalizeAuthenticatedDecryption\");function ji(r,e){const t=(0,cs.createCipheriv)(\"aes-128-ecb\",r,null);t.setAutoPadding(false);return Buffer.concat([t.update(e),t.final()])}a(ji,\"aes128EcbEncrypt\");var ds=class{static{a(this,\"Context\")}constructor(e,t,s){this.masterKey=e;this.masterSalt=t;this.profile=s;this.srtpSSRCStates={};this.srtcpSSRCStates={};{const i=14-t.length;if(i>0){this.masterSalt=Buffer.concat([t,Buffer.alloc(i)])}}this.srtpSessionKey=this.generateSessionKey(0);this.srtpSessionSalt=this.generateSessionSalt(2);this.srtpSessionAuthTag=this.generateSessionAuthTag(1);this.srtpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtpSessionAuthTag);this.srtcpSessionKey=this.generateSessionKey(3);this.srtcpSessionSalt=this.generateSessionSalt(5);this.srtcpSessionAuthTag=this.generateSessionAuthTag(4);this.srtcpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtcpSessionAuthTag);switch(s){case ts:this.cipher=new Ki(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case ct:this.cipher=new Gi(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}generateSessionKey(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let i=s.length-1,n=t.length-1;i>=0;i--,n--){t[n]=t[n]^s[i]}t=Buffer.concat([t,Buffer.from([0,0])]);return ji(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let i=s.length-1,n=t.length-1;i>=0;i--,n--){t[n]=t[n]^s[i]}t=Buffer.concat([t,Buffer.from([0,0])]);t=ji(this.masterKey,t);return t.subarray(0,14)}generateSessionAuthTag(e){const t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let o=s.length-1,c=t.length-1;o>=0;o--,c--){t[c]=t[c]^s[o]}let i=Buffer.concat([t,Buffer.from([0,0])]);let n=Buffer.concat([t,Buffer.from([0,1])]);i=ji(this.masterKey,i);n=ji(this.masterKey,n);return Buffer.concat([i,n.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];if(t)return t;t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0};this.srtpSSRCStates[e]=t;return t}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];if(t)return t;t={srtcpIndex:0,ssrc:e};this.srtcpSSRCStates[e]=t;return t}updateRolloverCount(e,t){if(!t.rolloverHasProcessed){t.rolloverHasProcessed=true}else if(e===0){if(t.lastSequenceNumber>Cr){t.rolloverCounter++}}else if(t.lastSequenceNumber<Cr&&e>ud-Cr){if(t.rolloverCounter>0){t.rolloverCounter--}}else if(e<Cr&&t.lastSequenceNumber>ud-Cr){t.rolloverCounter++}t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtpSessionAuthTag);const s=Buffer.alloc(4);s.writeUInt32BE(t);return this.srtpSessionAuth.update(e).update(s).digest().slice(0,10)}index(e){const t=this.srtcpSSRCStates[e];if(!t){return 0}return t.srtcpIndex}setIndex(e,t){const s=this.getSrtcpSsrcState(e);s.srtcpIndex=t%2147483647}};var Cr=100;var ud=65535;var Wi=class extends ds{static{a(this,\"SrtcpContext\")}constructor(e,t,s){super(e,t,s)}encryptRTCP(e){const t=e.readUInt32BE(4);const s=this.getSrtcpSsrcState(t);s.srtcpIndex++;if(s.srtcpIndex>>sf){s.srtcpIndex=0}const i=this.cipher.encryptRTCP(e,s.srtcpIndex);return i}decryptRTCP(e){const t=this.cipher.decryptRTCP(e);return t}};var sf=2147483647;var hs=class{static{a(this,\"Session\")}constructor(e){this.ContextCls=e}start(e,t,s,i,n){this.localContext=new this.ContextCls(e,t,n);this.remoteContext=new this.ContextCls(s,i,n)}};var $i=class extends hs{static{a(this,\"SrtcpSession\")}constructor(e){super(Wi);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRTCP(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e){const t=this.localContext.encryptRTCP(e);return t}};var Vi=class extends ds{static{a(this,\"SrtpContext\")}constructor(e,t,s){super(e,t,s)}encryptRtp(e,t){const s=this.getSrtpSsrcState(t.ssrc);this.updateRolloverCount(t.sequenceNumber,s);const i=this.cipher.encryptRtp(t,e,s.rolloverCounter);return i}decryptRtp(e){const t=os(e,this.rtpAuthTagLength);const s=this.srtpSSRCStates[t.ssrc];const i=s?{...s}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,i);const n=this.cipher.decryptRtp(e,i.rolloverCounter,t);if(s){Object.assign(s,i)}else{this.srtpSSRCStates[t.ssrc]=i}return n}get rtpAuthTagLength(){return this.profile===ct?16:10}};var Yi=class extends hs{static{a(this,\"SrtpSession\")}constructor(e){super(Vi);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRtp(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e,t){return this.localContext.encryptRtp(e,t)}};var Qi=new WeakMap;var Xi=new WeakSet;function rf(r,e){Xi.add(r);if(e==void 0)Qi.delete(r);else Qi.set(r,e)}a(rf,\"setTrackSourceCodecs\");function Le(r){return r==void 0?void 0:Qi.get(r)}a(Le,\"getTrackSourceCodecs\");function Et(r){if(Xi.has(r))return;Xi.add(r);if(r.codec!=void 0){Qi.set(r,[r.codec])}}a(Et,\"captureTrackSourceCodecs\");var jo=class{static{a(this,\"TrackBroadcastSource\")}constructor(){this.tracks=new Set;this.upstreamStops=new Set}attach(e){this.tracks.add(e)}detach(e){this.tracks.delete(e);if(this.tracks.size>0){return}for(const t of[...this.upstreamStops]){t()}this.upstreamStops.clear()}addUpstreamStop(e){const t=a(()=>{this.upstreamStops.delete(t);e()},\"once\");this.upstreamStops.add(t)}deliverRtp(e,t){const s=[...this.tracks].filter(i=>!i.stopped);for(const i of s){i.applyIncomingRtp(e.clone(),t)}}deliverRtcp(e){for(const t of this.tracks){if(!t.stopped){t.onReceiveRtcp.execute(e)}}}deliverSourceChanged(e){for(const t of this.tracks){if(!t.stopped){t.onSourceChanged.execute(e)}}}stopAllTracks(){for(const e of[...this.tracks]){e.stop()}}};var Be=class r extends he{static{a(this,\"MediaStreamTrack\")}constructor(e){super();this.uuid=(0,Wo.randomUUID)().toString();this.remote=false;this.enabled=true;this.onReceiveRtp=new w;this.onReceiveRtcp=new w;this.onSourceChanged=new w;this.stopped=false;this.muted=true;this.stop=()=>{if(this.stopped){return}this.stopped=true;this.muted=true;this.onReceiveRtp.complete();this.emit(\"ended\");this.broadcastSource.detach(this)};this.writeRtp=s=>{if(this.remote){throw new Error(\"this is remoteTrack\")}const i=Buffer.isBuffer(s)?W.deSerialize(s):s.clone();i.header.payloadType=this.codec?.payloadType??i.header.payloadType;this.broadcastSource.deliverRtp(i)};this.writeRtcp=s=>{this.broadcastSource.deliverRtcp(s)};const t=e.broadcastSource;Object.assign(this,e);this.id??=this.uuid;this.broadcastSource=t??new jo;if(!this.stopped){this.broadcastSource.attach(this)}this.onReceiveRtp.subscribe(s=>{this.muted=false;this.header=s.header});this.label=`${this.remote?\"remote\":\"local\"} ${this.kind}`}get readyState(){return this.stopped?\"ended\":\"live\"}notifySourceChanged(e){this.broadcastSource.deliverSourceChanged(e)}applyIncomingRtp(e,t){if(this.stopped){return}this.onReceiveRtp.execute(e,t)}bindUpstreamStop(e){this.broadcastSource.addUpstreamStop(e)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){const e=new r({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(Xi.has(this)){rf(e,Le(this))}else{Et(e)}return e}};var us=class r{static{a(this,\"MediaStream\")}constructor(e={}){this.tracks=[];if(Array.isArray(e)){this.tracks=e}else{Object.assign(this,e)}this.id??=(0,Wo.randomUUID)().toString()}addTrack(e){e.streamId=this.id;this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e);if(e.streamId===this.id){e.streamId=void 0}}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===\"audio\")}getVideoTracks(){return this.tracks.filter(e=>e.kind===\"video\")}getTrackById(e){return this.tracks.find(t=>t.id===e)}get active(){return this.tracks.some(e=>!e.stopped)}clone(){const e=new r;for(const t of this.tracks){e.addTrack(t.clone())}return e}};var pc=require(\"node:crypto\");var $o;(function(r){r[r[\"DCEP\"]=50]=\"DCEP\";r[r[\"STRING\"]=51]=\"STRING\";r[r[\"BINARY\"]=53]=\"BINARY\";r[r[\"STRING_EMPTY\"]=56]=\"STRING_EMPTY\";r[r[\"BINARY_EMPTY\"]=57]=\"BINARY_EMPTY\"})($o||($o={}));var A;(function(r){r[r[\"CLOSED\"]=1]=\"CLOSED\";r[r[\"COOKIE_WAIT\"]=2]=\"COOKIE_WAIT\";r[r[\"COOKIE_ECHOED\"]=3]=\"COOKIE_ECHOED\";r[r[\"ESTABLISHED\"]=4]=\"ESTABLISHED\";r[r[\"SHUTDOWN_PENDING\"]=5]=\"SHUTDOWN_PENDING\";r[r[\"SHUTDOWN_SENT\"]=6]=\"SHUTDOWN_SENT\";r[r[\"SHUTDOWN_RECEIVED\"]=7]=\"SHUTDOWN_RECEIVED\";r[r[\"SHUTDOWN_ACK_SENT\"]=8]=\"SHUTDOWN_ACK_SENT\"})(A||(A={}));var _r=require(\"node:crypto\");var Er=4;var De=12;var Ji=4;var ld=12;var ht=Ji+ld;var fe=class r{static{a(this,\"Chunk\")}get body(){return this._body}set body(e){this._body=e}static{this.type=-1}constructor(e=0,t=Buffer.from(\"\")){this.flags=e;this._body=t}get type(){return r.type}get bytes(){if(!this.body)throw new Error;const e=Buffer.alloc(Ji);e.writeUInt8(this.type,0);e.writeUInt8(this.flags,1);e.writeUInt16BE(this.body.length+Ji,2);const t=Buffer.concat([e,this.body,...[...Array(It(this.body.length))].map(()=>Buffer.from(\"\\0\"))]);return t}};var Rr=class extends fe{static{a(this,\"BaseInitChunk\")}constructor(e=0,t){super(e,t);this.flags=e;if(t){this.initiateTag=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);this.outboundStreams=t.readUInt16BE(8);this.inboundStreams=t.readUInt16BE(10);this.initialTsn=t.readUInt32BE(12);this.params=pd(t.slice(16))}else{this.initiateTag=0;this.advertisedRwnd=0;this.outboundStreams=0;this.inboundStreams=0;this.initialTsn=0;this.params=[]}}get body(){const e=Buffer.alloc(16);e.writeUInt32BE(this.initiateTag,0);e.writeUInt32BE(this.advertisedRwnd,4);e.writeUInt16BE(this.outboundStreams,8);e.writeUInt16BE(this.inboundStreams,10);e.writeUInt32BE(this.initialTsn,12);return Buffer.concat([e,fd(this.params)])}};var Rt=class r extends Rr{static{a(this,\"InitChunk\")}static{this.type=1}get type(){return r.type}};var ls=class r extends Rr{static{a(this,\"InitAckChunk\")}static{this.type=2}get type(){return r.type}};var Zi=class r extends Rr{static{a(this,\"ReConfigChunk\")}static{this.type=130}get type(){return r.type}};var xt=class r extends fe{static{a(this,\"ForwardTsnChunk\")}static{this.type=192}constructor(e=0,t){super(e,t);this.flags=e;this.streams=[];if(t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;while(s<t.length){this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]);s+=4}}else{this.cumulativeTsn=0}}get type(){return r.type}set body(e){}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return Buffer.concat([e,...this.streams.map(([t,s])=>{const i=Buffer.alloc(4);i.writeUInt16BE(t,0);i.writeUInt16BE(s,2);return i})])}};var Ee=class r extends fe{static{a(this,\"DataChunk\")}static{this.type=0}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.tsn=0;this.streamId=0;this.streamSeqNum=0;this.protocol=0;this.userData=Buffer.from(\"\");this.abandoned=false;this.acked=false;this.misses=0;this.retransmit=false;this.sentCount=0;this.bookSize=0;if(t){this.tsn=t.readUInt32BE(0);this.streamId=t.readUInt16BE(4);this.streamSeqNum=t.readUInt16BE(6);this.protocol=t.readUInt32BE(8);this.userData=t.slice(12)}}get bytes(){const e=ht+this.userData.length;const t=Buffer.alloc(ht);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.tsn,4);t.writeUInt16BE(this.streamId,8);t.writeUInt16BE(this.streamSeqNum,10);t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);if(e%4){s=Buffer.concat([s,...[...Array(It(e))].map(()=>Buffer.from(\"\\0\"))])}return s}};var fs=class r extends fe{static{a(this,\"CookieEchoChunk\")}static{this.type=10}get type(){return r.type}};var ps=class r extends fe{static{a(this,\"CookieAckChunk\")}static{this.type=11}get type(){return r.type}};var kt=class extends fe{static{a(this,\"BaseParamsChunk\")}constructor(e=0,t=void 0){super(e,t);this.flags=e;this.params=[];if(t){this.params=pd(t)}}get body(){return fd(this.params)}};var ms=class r extends kt{static{a(this,\"AbortChunk\")}static{this.type=6}get type(){return r.type}};var vt=class r extends kt{static{a(this,\"ErrorChunk\")}static{this.type=9}static{this.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 r.type}get descriptions(){return this.params.map(([e,t])=>{const s=(Object.entries(r.CODE).find(([,i])=>i===e)||[])[0];return{name:s,body:t}})}};var gs=class r extends kt{static{a(this,\"HeartbeatChunk\")}static{this.type=4}get type(){return r.type}};var xr=class r extends kt{static{a(this,\"HeartbeatAckChunk\")}static{this.type=5}get type(){return r.type}};var Ss=class r extends kt{static{a(this,\"ReconfigChunk\")}static{this.type=130}get type(){return r.type}};var ys=class r extends fe{static{a(this,\"SackChunk\")}static{this.type=3}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.gaps=[];this.duplicates=[];this.cumulativeTsn=0;this.advertisedRwnd=0;if(t){this.cumulativeTsn=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);const s=t.readUInt16BE(8);const i=t.readUInt16BE(10);let n=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(n),t.readUInt16BE(n+2)]);n+=4});[...Array(i)].forEach(()=>{this.duplicates.push(t.readUInt32BE(n));n+=4})}}get bytes(){const e=16+4*(this.gaps.length+this.duplicates.length);const t=Buffer.alloc(16);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.cumulativeTsn,4);t.writeUInt32BE(this.advertisedRwnd,8);t.writeUInt16BE(this.gaps.length,12);t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...this.gaps.map(i=>{const n=Buffer.alloc(4);n.writeUInt16BE(i[0],0);n.writeUInt16BE(i[1],2);return n})]);s=Buffer.concat([s,...this.duplicates.map(i=>{const n=Buffer.alloc(4);n.writeUInt32BE(i,0);return n})]);return s}};var kr=class r extends fe{static{a(this,\"ShutdownChunk\")}static{this.type=7}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.cumulativeTsn=0;if(t){this.cumulativeTsn=t.readUInt32BE(0)}}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return e}};var vr=class r extends fe{static{a(this,\"ShutdownAckChunk\")}static{this.type=8}get type(){return r.type}};var Ir=class r extends fe{static{a(this,\"ShutdownCompleteChunk\")}static{this.type=14}get type(){return r.type}};var nf=[Ee,Rt,ls,ys,gs,xr,ms,kr,vr,vt,fs,ps,Ir,Ss,xt];var of=nf.reduce((r,e)=>{r[e.type]=e;return r},{});function It(r){const e=r%Er;return e?Er-e:0}a(It,\"padL\");function fd(r){let e=Buffer.from(\"\");let t=Buffer.from(\"\");r.forEach(([s,i])=>{const n=i.length+4;const o=Buffer.alloc(4);o.writeUInt16BE(s,0);o.writeUInt16BE(n,2);e=Buffer.concat([e,t,o,i]);t=Buffer.concat([...Array(It(n))].map(()=>Buffer.from(\"\\0\")))});return e}a(fd,\"encodeParams\");function pd(r){const e=[];let t=0;while(t<=r.length-4){const s=r.readUInt16BE(t);const i=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+i)]);t+=i+It(i)}return e}a(pd,\"decodeParams\");function md(r){if(r.length<De)throw new Error(\"SCTP packet length is less than 12 bytes\");const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);const s=r.readUInt32BE(4);const i=r.readUInt32LE(8);let n=ar(r.subarray(0,8));n=ar(af,n);n=ar(r.subarray(De),n);if(i!==n>>>0)throw new Error(\"SCTP packet has invalid checksum\");const o=[];let c=De;while(c+4<=r.length){const d=r.readUInt8(c);const h=r.readUInt8(c+1);const l=r.readUInt16BE(c+2);const u=r.slice(c+4,c+l);const g=of[d.toString()];if(g){o.push(new g(h,u))}else{throw new Error(\"unknown\")}c+=l+It(l)}return[e,t,s,o]}a(md,\"parsePacket\");var af=Buffer.alloc(4);function gd(r,e){if(r instanceof Ee){const t=ht+r.userData.length;return t+It(t)}return e.length}a(gd,\"wireLength\");function Vo(r,e,t,s){const i=s.map(d=>d instanceof Ee?void 0:d.bytes);let n=De;for(let d=0;d<s.length;d++){n+=gd(s[d],i[d])}const o=Buffer.allocUnsafe(n);o.writeUInt16BE(r,0);o.writeUInt16BE(e,2);o.writeUInt32BE(t,4);o.writeUInt32LE(0,8);let c=De;for(let d=0;d<s.length;d++){const h=s[d];const l=i[d];if(l){l.copy(o,c);c+=l.length;continue}const u=h;const g=ht+u.userData.length;o.writeUInt8(u.type,c);o.writeUInt8(u.flags,c+1);o.writeUInt16BE(g,c+2);o.writeUInt32BE(u.tsn,c+4);o.writeUInt16BE(u.streamId,c+8);o.writeUInt16BE(u.streamSeqNum,c+10);o.writeUInt32BE(u.protocol,c+12);u.userData.copy(o,c+ht);const S=It(g);if(S)o.fill(0,c+g,c+g+S);c+=g+S}o.writeUInt32LE(ar(o)>>>0,8);return o}a(Vo,\"serializePackets\");function Sd(r){return gd(r,r instanceof Ee?void 0:r.bytes)}a(Sd,\"chunkWireLength\");function yd(r,e,t,s){return Vo(r,e,t,[s])}a(yd,\"serializePacket\");function Td(r){return r.map((e,t)=>[t,e])}a(Td,\"enumerate\");function wd(r){return r.reduce((e,t)=>{e[t]=new w;return e},{})}a(wd,\"createEventsFromList\");var Ts=class r{static{a(this,\"OutgoingSSNResetRequestParam\")}static{this.type=13}constructor(e,t,s,i){this.requestSequence=e;this.responseSequence=t;this.lastTsn=s;this.streams=i}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(12);e.writeUInt32BE(this.requestSequence,0);e.writeUInt32BE(this.responseSequence,4);e.writeUInt32BE(this.lastTsn,8);return Buffer.concat([e,...this.streams.map(t=>{const s=Buffer.allocUnsafe(2);s.writeUInt16BE(t,0);return s})])}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);const i=e.readUInt32BE(8);const n=[];for(let o=12;o<e.length;o+=2){n.push(e.readUInt16BE(o))}return new r(t,s,i,n)}};var Pr=class r{static{a(this,\"StreamAddOutgoingParam\")}static{this.type=17}constructor(e,t){this.requestSequence=e;this.newStreams=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.requestSequence,0);e.writeUInt16BE(this.newStreams,4);e.writeUInt16BE(0,6);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt16BE(4);return new r(t,s)}};var Ar={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5};var Pt=class r{static{a(this,\"ReconfigResponseParam\")}static{this.type=16}constructor(e,t){this.responseSequence=e;this.result=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.responseSequence,0);e.writeUInt32BE(this.result,4);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);return new r(t,s)}};var Yo={13:Ts,16:Pt,17:Pr};var v=b(\"webrtc/sctp/sctp\");var cf=24;var df=60;var bd=65535;var bs=1191;function Jo(r,e=ht){const t=De+e;if(r<=t)return 0;const s=r-t;return s-s%Er}a(Jo,\"maxPayloadSizeForMtu\");function sn(r){if(!Number.isSafeInteger(r)||r<=0){throw new Error(\"SCTP MTU must be a positive integer\")}if(Jo(r)===0){throw new Error(\"SCTP MTU is too small for a DATA chunk\")}}a(sn,\"validateSctpMtu\");var ws=1;var en=2;var tn=4;var Cd=10;var hf=8;var uf=10;var lf=2;var Ed=1/8;var Rd=1/4;var xd=3;var ff=1;var pf=60;var $e=2**32;var mf=20;var gf=4096;var Sf=30;var kd=135;var vd=7;var Id=32776;var Pd=49152;var yf=[\"new\",\"closed\",\"connected\",\"connecting\"];var Br=class r{static{a(this,\"SCTP\")}get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}constructor(e,t=5e3,s={}){this.transport=e;this.port=t;this.flush=new w;this.stateChanged=wd(yf);this.onReconfigStreams=new w;this.onReceive=new w;this.onSackReceived=async()=>{};this.associationState=A.CLOSED;this.started=false;this.state=\"new\";this.isServer=true;this.isStopping=false;this.isClosed=false;this.hmacKey=(0,_r.randomBytes)(16);this.localPartialReliability=true;this.localVerificationTag=Ci();this.remoteExtensions=[];this.remotePartialReliability=true;this.remoteVerificationTag=0;this.advertisedRwnd=1024*1024;this.lastAdvertisedRwnd=this.advertisedRwnd;this.peerAdvertisedRwnd=this.advertisedRwnd;this.inboundStreams={};this._inboundStreamsCount=0;this._inboundStreamsMax=bd;this.pendingChunks=0;this.sackDuplicates=[];this.sackMisOrdered=new Set;this.sackNeeded=false;this.sackPacketCount=0;this.sackHasNewDataInPacket=false;this.sackImmediate=false;this.fastRecoveryTransmit=false;this.flightSize=0;this.outboundQueue=new fr;this.outboundStreamSeq={};this._outboundStreamsCount=bd;this.localTsn=Number(Ci());this.lastSackedTsn=At(this.localTsn);this.advancedPeerAckTsn=At(this.localTsn);this.partialBytesAcked=0;this.sentQueue=new fr;this.retransmitPending=false;this.transmitting=false;this.transmitRequested=false;this.transmitScheduled=false;this.reconfigRequestSeq=this.localTsn;this.reconfigResponseSeq=0;this.reconfigQueue=[];this.rto=xd;this.timer1Failures=0;this.timer2Failures=0;this.timerReconfigFailures=0;this.heartbeatInterval=Sf;this.send=async(i,n,o,{expiry:c,maxRetransmits:d,ordered:h}={expiry:void 0,maxRetransmits:void 0,ordered:true})=>{const l=h?this.outboundStreamSeq[i]||0:0;const u=Math.ceil(o.length/this.maxPayloadSize);let g=0;const S=[];for(let p=0;p<u;p++){const f=new Ee(0,void 0);f.flags=0;if(!h){f.flags=tn}if(p===0){f.flags|=en}if(p===u-1){f.flags|=ws}f.tsn=this.localTsn;f.streamId=i;f.streamSeqNum=l;f.protocol=n;f.userData=o.subarray(g,g+this.maxPayloadSize);f.bookSize=f.userData.length;f.expiry=c;f.maxRetransmits=d;g+=this.maxPayloadSize;this.localTsn=_t(this.localTsn);S.push(f)}for(const p of S){this.outboundQueue.push(p)}if(h){this.outboundStreamSeq[i]=j(l,1)}this.transmitSoon()};this.timer1Expired=()=>{if(this.isStopped)return;this.timer1Failures++;this.timer1Handle=void 0;if(this.timer1Failures>hf){this.setState(A.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch(i=>{v(\"send timer1 chunk failed\",i.message)})});if(this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};this.timer2Expired=()=>{if(this.isStopped)return;this.timer2Failures++;this.timer2Handle=void 0;if(this.timer2Failures>Cd){this.setState(A.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch(i=>{v(\"send timer2Chunk failed\",i.message)})});if(this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};this.timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0;for(const i of this.sentQueue){if(!this.maybeAbandon(i)){i.retransmit=true;this.retransmitPending=true}}this.updateAdvancedPeerAckPoint();this.fastRecoveryExit=void 0;this.flightSize=0;this.partialBytesAcked=0;this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.maxPayloadSize;this.transmit().catch(i=>v(\"transmit failed\",i))};this.timerReconfigHandleExpired=async()=>{if(this.isStopped)return;this.timerReconfigFailures++;this.rto=Math.ceil(this.rto*1.5);if(this.timerReconfigFailures>Cd){v(\"timerReconfigFailures\",this.timerReconfigFailures);this.setState(A.CLOSED);this.timerReconfigHandle=void 0}else if(this.reconfigRequest){v(\"timerReconfigHandleExpired\",this.timerReconfigFailures,this.rto);await this.sendReconfigParam(this.reconfigRequest);if(this.isStopped)return;this.timerReconfigHandle=setTimeout(ye(this.timerReconfigHandleExpired,i=>v(\"reconfig timer failed\",i)),this.rto*1e3)}};this.timerHeartbeatExpired=async()=>{this.timerHeartbeatHandle=void 0;if(this.associationState!==A.ESTABLISHED)return;if(this.flightSize===0&&this.outboundQueue.length===0){const i=new gs;const n=Buffer.allocUnsafe(4);n.writeUInt32BE(Math.floor(Date.now()/1e3),0);i.params.push([1,n]);await this.sendChunk(i).catch(o=>{v(\"send heartbeat failed\",o.message)})}this.heartbeatStart()};this.mtu=s.mtu??bs;sn(this.mtu);this.maxPayloadSize=Jo(this.mtu);this.cwnd=uf*this.maxPayloadSize;this.localPort=this.port;this.transport.onData=i=>{this.handleData(i).catch(n=>v(\"receive failed\",n))}}get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0){return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}return void 0}static client(e,t=5e3,s={}){const i=new r(e,t,s);i.isServer=false;return i}static server(e,t=5e3,s={}){const i=new r(e,t,s);i.isServer=true;return i}async handleData(e){if(this.isStopped)return;let t;const[,,s,i]=md(e);const n=i.filter(o=>o.type===Rt.type).length;if(n>0){if(i.length!=1){throw new Error}t=0}else{t=this.localVerificationTag}if(s!==t){return}this.sackHasNewDataInPacket=false;for(const o of i){if(o.type===Ee.type)this.receiveDataChunk(o);else await this.receiveChunk(o)}if(this.sackNeeded){if(this.sackHasNewDataInPacket){this.sackPacketCount++}if(this.sackPacketCount>=2){this.sackImmediate=true}await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0;this.sendSack().catch(e=>{v(\"send delayed sack failed\",e.message)})},mf)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;await this.sendChunk(this.takeSack()).catch(e=>{v(\"send sack failed\",e.message)})}takeSack(){const e=[];let t;const s=[...this.sackMisOrdered].sort((n,o)=>(n-this.lastReceivedTsn+$e)%$e-(o-this.lastReceivedTsn+$e)%$e);for(const n of s){const o=(n-this.lastReceivedTsn+$e)%$e;if(n===t){e[e.length-1][1]=o}else{e.push([o,o])}t=_t(n)}const i=new ys(0,void 0);i.cumulativeTsn=this.lastReceivedTsn;i.advertisedRwnd=Math.max(0,this.advertisedRwnd);this.lastAdvertisedRwnd=i.advertisedRwnd;i.duplicates=[...this.sackDuplicates];i.gaps=e;this.sackDuplicates=[];this.sackNeeded=false;this.sackPacketCount=0;this.sackImmediate=false;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}return i}async receiveChunk(e){switch(e.type){case Ee.type:{this.receiveDataChunk(e)}break;case Rt.type:{if(!this.isServer)return;const t=e;v(\"receive init\",t);this.lastReceivedTsn=At(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=At(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new ls;s.initiateTag=this.localVerificationTag;s.advertisedRwnd=this.advertisedRwnd;s.outboundStreams=this._outboundStreamsCount;s.inboundStreams=this._inboundStreamsCount;s.initialTsn=this.localTsn;this.setExtensions(s.params);const i=Math.floor(Date.now()/1e3);const n=Buffer.allocUnsafe(4);n.writeUInt32BE(i,0);let o=n;o=Buffer.concat([o,(0,_r.createHmac)(\"sha1\",this.hmacKey).update(o).digest()]);s.params.push([vd,o]);v(\"send initAck\",s);await this.sendChunk(s).catch(c=>{v(\"send initAck failed\",c.message)})}break;case ls.type:{if(this.associationState!=A.COOKIE_WAIT)return;const t=e;this.timer1Cancel();this.lastReceivedTsn=At(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=At(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new fs;for(const[i,n]of t.params){if(i===vd){s.body=n;break}}await this.sendChunk(s).catch(i=>{v(\"send echo failed\",i.message)});this.timer1Start(s);this.setState(A.COOKIE_ECHOED)}break;case ys.type:{await this.receiveSackChunk(e)}break;case gs.type:{const t=new xr;t.params=e.params;await this.sendChunk(t).catch(s=>{v(\"send heartbeat ack failed\",s.message)})}break;case ms.type:{this.setState(A.CLOSED)}break;case kr.type:{this.timer2Cancel();this.setState(A.SHUTDOWN_RECEIVED);const t=new vr;await this.sendChunk(t).catch(s=>{v(\"send shutdown ack failed\",s.message)});this.t2Start(t);this.setState(A.SHUTDOWN_SENT)}break;case vt.type:{v(\"ErrorChunk\",e.descriptions)}break;case fs.type:{if(!this.isServer)return;const t=e;const s=t.body;const i=(0,_r.createHmac)(\"sha1\",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=cf||!s.slice(4).equals(i)){v(\"x State cookie is invalid\");return}const n=Math.floor(Date.now()/1e3);const o=s.readUInt32BE(0);if(o<n-df||o>n){const d=new vt(0,void 0);d.params.push([vt.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(\"\\0\")))]);await this.sendChunk(d).catch(h=>{v(\"send errorChunk failed\",h.message)});return}const c=new ps;await this.sendChunk(c).catch(d=>{v(\"send cookieAck failed\",d.message)});this.setState(A.ESTABLISHED)}break;case ps.type:{if(this.associationState!=A.COOKIE_ECHOED)return;this.timer1Cancel();this.setState(A.ESTABLISHED)}break;case Ir.type:{if(this.associationState!=A.SHUTDOWN_ACK_SENT)return;this.timer2Cancel();this.setState(A.CLOSED)}break;case Ss.type:{if(this.associationState!=A.ESTABLISHED)return;const t=e;for(const[s,i]of t.params){const n=Yo[s];if(n){await this.receiveReconfigParam(n.parse(i))}}}break;case xt.type:{this.receiveForwardTsnChunk(e)}break}}getExtensions(e){for(const[t,s]of e){if(t===Pd){this.remotePartialReliability=true}else if(t===Id){this.remoteExtensions=[...s]}}}async receiveReconfigParam(e){v(\"receiveReconfigParam\",Yo[e.type]);switch(e.type){case Ts.type:{const t=e;const s=new Pt(t.requestSequence,Ar.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s);await Promise.all(t.streams.map(async i=>{const n=this.inboundStreams[i];if(n){this.pendingChunks-=n.reassembly.length;this.advertisedRwnd+=n.reassembly.reduce((o,c)=>o+c.userData.length,0)}delete this.inboundStreams[i];if(this.outboundStreamSeq[i]){if(!this.reconfigQueue.includes(i)){this.reconfigQueue.push(i)}}}));await this.transmitReconfigRequest();this.onReconfigStreams.execute(t.streams)}break;case Pt.type:{const t=e;if(t.result!==Ar.ReconfigResultSuccessPerformed){v(\"OutgoingSSNResetRequestParam failed\",Object.keys(Ar).find(s=>Ar[s]===t.result))}else if(t.responseSequence===this.reconfigRequest?.requestSequence){const s=this.reconfigRequest.streams.map(i=>{delete this.outboundStreamSeq[i];return i});this.onReconfigStreams.execute(s);this.reconfigRequest=void 0;this.timerReconfigCancel();this.rto=xd;this.timerReconfigFailures=0;if(this.reconfigQueue.length>0){await this.transmitReconfigRequest()}}}break;case Pr.type:{const t=e;this._inboundStreamsCount+=t.newStreams;const s=new Pt(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s)}break}}receiveDataChunk(e){this.sackNeeded=true;if((this.advertisedRwnd<=0||this.pendingChunks>=gf)&&ae(e.tsn,this.highestReceivedTsn)){this.sackImmediate=true;return}if(this.markReceived(e.tsn)){this.sackImmediate=true;return}this.sackHasNewDataInPacket=true;if(this.sackMisOrdered.size>0){this.sackImmediate=true}const t=this.getInboundStream(e.streamId);if((e.flags&(en|ws))===(en|ws)){if(e.flags&tn){this.receive(e.streamId,e.protocol,e.userData);return}if(t.reassembly.length===0&&e.streamSeqNum===t.streamSequenceNumber){t.streamSequenceNumber=j(t.streamSequenceNumber,1);this.receive(e.streamId,e.protocol,e.userData);return}}const s=t.reassembly.length;t.addChunk(e);this.advertisedRwnd-=e.userData.length;for(const i of t.popMessages()){this.advertisedRwnd+=i[2].length;this.receive(...i)}this.pendingChunks+=t.reassembly.length-s}async receiveSackChunk(e){if(ae(this.lastSackedTsn,e.cumulativeTsn))return;const t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;const s=this.flightSize>=this.cwnd;let i=0,n=0;while(this.sentQueue.length>0&&Xt(this.lastSackedTsn,this.sentQueue.at(0).tsn)){const c=this.sentQueue.shift();i++;if(!c?.acked){n+=c.bookSize;this.flightSizeDecrease(c)}if(i===1&&c.sentCount===1){this.updateRto(t-c.sentTime)}}let o=false;if(e.gaps.length>0){const c=new Set;let d;e.gaps.forEach(l=>{for(let u=l[0];u<l[1]+1;u++){d=(e.cumulativeTsn+u)%$e;c.add(d)}});let h=e.cumulativeTsn;for(const l of this.sentQueue){if(ae(l.tsn,d)){break}if(c.has(l.tsn)&&!l.acked){n+=l.bookSize;l.acked=true;this.flightSizeDecrease(l);h=l.tsn}}for(const l of this.sentQueue){if(ae(l.tsn,h)){break}if(!c.has(l.tsn)){l.misses++;if(l.misses===3){l.misses=0;if(!this.maybeAbandon(l)){l.retransmit=true;this.retransmitPending=true}l.acked=false;this.flightSizeDecrease(l);o=true}}}}if(this.fastRecoveryExit===void 0){if(i&&s){if(this.cwnd<=this.ssthresh){this.cwnd+=Math.min(n,lf*this.maxPayloadSize)}else{this.partialBytesAcked+=n;if(this.partialBytesAcked>=this.cwnd){this.partialBytesAcked-=this.cwnd;this.cwnd+=this.maxPayloadSize}}}if(o){this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.ssthresh;this.partialBytesAcked=0;this.fastRecoveryExit=this.sentQueue.at(-1).tsn;this.fastRecoveryTransmit=true}}else if(Xt(e.cumulativeTsn,this.fastRecoveryExit)){this.fastRecoveryExit=void 0}if(this.sentQueue.length===0){this.timer3Cancel()}else if(i>0){this.timer3Restart()}this.peerAdvertisedRwnd=e.advertisedRwnd;this.updateAdvancedPeerAckPoint();await this.onSackReceived();await this.transmit()}receiveForwardTsnChunk(e){this.sackNeeded=true;this.sackImmediate=true;if(Xt(this.lastReceivedTsn,e.cumulativeTsn)){return}const t=a(s=>ae(s,this.lastReceivedTsn),\"isObsolete\");this.lastReceivedTsn=e.cumulativeTsn;this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const s of[...this.sackMisOrdered].sort()){if(s===_t(this.lastReceivedTsn)){this.lastReceivedTsn=s}else{break}}this.sackDuplicates=this.sackDuplicates.filter(t);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const[s,i]of e.streams){const n=this.getInboundStream(s);n.streamSequenceNumber=j(i,1);for(const o of n.popMessages()){this.advertisedRwnd+=o[2].length;this.receive(...o)}}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)});this.pendingChunks=Object.values(this.inboundStreams).reduce((s,i)=>s+i.reassembly.length,0);if(ae(this.lastReceivedTsn,this.highestReceivedTsn))this.highestReceivedTsn=this.lastReceivedTsn}updateRto(e){if(!this.srtt){this.rttvar=e/2;this.srtt=e}else{this.rttvar=(1-Rd)*this.rttvar+Rd*Math.abs(this.srtt-e);this.srtt=(1-Ed)*this.srtt+Ed*e}this.rto=Math.max(ff,Math.min(this.srtt+4*this.rttvar,pf))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){if(!this.inboundStreams[e]){this.inboundStreams[e]=new Qo}return this.inboundStreams[e]}markReceived(e){if(Xt(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e)){this.sackDuplicates.push(e);return true}if(ae(e,this.highestReceivedTsn))this.highestReceivedTsn=e;if(e===_t(this.lastReceivedTsn)){this.lastReceivedTsn=e;while(this.sackMisOrdered.size>0){const t=_t(this.lastReceivedTsn);if(!this.sackMisOrdered.delete(t))break;this.lastReceivedTsn=t}if(this.sackDuplicates.length>0){const t=a(s=>ae(s,this.lastReceivedTsn),\"isObsolete\");this.sackDuplicates=this.sackDuplicates.filter(t)}}else{this.sackMisOrdered.add(e)}return false}holdReceived(e){this.advertisedRwnd-=e}releaseReceived(e){this.advertisedRwnd+=e;if(this.associationState!==A.ESTABLISHED||this.lastReceivedTsn===void 0)return;if(this.lastAdvertisedRwnd*2<this.advertisedRwnd){this.sackNeeded=true;this.sackImmediate=true;this.scheduleSack().catch(t=>v(\"send window update failed\",t.message))}}transmitSoon(){if(this.transmitScheduled)return;this.transmitScheduled=true;queueMicrotask(()=>{this.transmitScheduled=false;this.transmit().catch(e=>v(\"transmit failed\",e))})}async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=true;return}this.transmitting=true;try{do{this.transmitRequested=false;this.transmitOnce()}while(this.transmitRequested)}finally{this.transmitting=false}}transmitOnce(){if(this.isStopped)return;const e=[];let t=De;let s=false;const i=a(()=>{if(e.length===0)return;this.sendChunks(e.splice(0,e.length));t=De},\"flush\");const n=a(h=>{const l=Sd(h);if(e.length>0&&t+l>this.mtu)i();e.push(h);t+=l},\"add\");const o=a(h=>{if(!s&&this.sackNeeded&&this.lastReceivedTsn!==void 0){n(this.takeSack());s=true}n(h)},\"addData\");if(this.forwardTsnChunk){n(this.forwardTsnChunk);this.forwardTsnChunk=void 0;if(!this.timer3Handle){this.timer3Start()}}const c=this.fastRecoveryExit!=void 0?2*this.maxPayloadSize:4*this.maxPayloadSize;const d=Math.min(this.flightSize+c,this.cwnd);if(this.retransmitPending){let h=true;let l=true;for(const u of this.sentQueue){if(u.retransmit){if(this.fastRecoveryTransmit){this.fastRecoveryTransmit=false}else if(this.flightSize>=d){l=false;break}this.flightSizeIncrease(u);u.misses=0;u.retransmit=false;u.sentCount++;o(u);if(h){this.timer3Restart()}}h=false}if(l)this.retransmitPending=false}while(this.outboundQueue.length>0&&this.flightSize<d&&(this.peerRwnd>0||this.flightSize===0)){const h=this.outboundQueue.shift();if(!h)break;if(h.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(h);break}this.sentQueue.push(h);this.flightSizeIncrease(h);h.sentCount++;h.sentTime=Date.now()/1e3;o(h);this.onSent?.(h.streamId,h.protocol,h.userData.length);if(!this.timer3Handle){this.timer3Start()}}i();this.flush.execute()}sendChunks(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){v(\"send chunks failed\",\"invalid remote port\");return}const t=Vo(this.localPort,this.remotePort,this.remoteVerificationTag,e);this.transport.send(t).catch(s=>{v(\"send packet failed\",s.message)})}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===A.ESTABLISHED&&!this.reconfigRequest){const e=[...new Set(this.reconfigQueue)];const t=e.slice(0,kd);this.reconfigQueue=e.slice(kd);const s=new Ts(this.reconfigRequestSeq,this.reconfigResponseSeq,At(this.localTsn),t);this.reconfigRequestSeq=_t(this.reconfigRequestSeq);this.reconfigRequest=s;await this.sendReconfigParam(s);this.timerReconfigHandleStart()}}async sendReconfigParam(e){v(\"sendReconfigParam\",e);const t=new Ss;t.params.push([e.type,e.bytes]);await this.sendChunk(t).catch(s=>{v(\"send reconfig failed\",s.message)})}async sendResetRequest(e){v(\"sendResetRequest\",e);const t=new Ee(0,void 0);t.streamId=e;this.outboundQueue.push(t);if(!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)}timer1Cancel(){if(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)}timer2Cancel(){if(this.timer2Handle){clearTimeout(this.timer2Handle);this.timer2Handle=void 0;this.timer2Chunk=void 0}}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Cancel(){if(this.timer3Handle){clearTimeout(this.timer3Handle);this.timer3Handle=void 0}}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;v(\"timerReconfigHandleStart\",{rto:this.rto});this.timerReconfigFailures=0;this.timerReconfigHandle=setTimeout(ye(this.timerReconfigHandleExpired,e=>v(\"reconfig timer failed\",e)),this.rto*1e3)}timerReconfigCancel(){if(this.timerReconfigHandle){v(\"timerReconfigCancel\");clearTimeout(this.timerReconfigHandle);this.timerReconfigHandle=void 0;this.timerReconfigFailures=0}}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==A.ESTABLISHED){return}this.timerHeartbeatHandle=setTimeout(ye(this.timerHeartbeatExpired,e=>v(\"heartbeat failed\",e)),(this.rto+this.heartbeatInterval)*1e3)}heartbeatRestart(){this.heartbeatCancel();this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle){clearTimeout(this.timerHeartbeatHandle);this.timerHeartbeatHandle=void 0}}setHeartbeatInterval(e){if(e<=0){throw new Error(\"heartbeat interval must be > 0\")}this.heartbeatInterval=e;this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(ae(this.lastSackedTsn,this.advancedPeerAckTsn)){this.advancedPeerAckTsn=this.lastSackedTsn}let e=0;const t={};while(this.sentQueue.length>0&&this.sentQueue.at(0).abandoned){const s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn;e++;if(!(s.flags&tn)){t[s.streamId]=s.streamSeqNum}}if(e){this.forwardTsnChunk=new xt(0,void 0);this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn;this.forwardTsnChunk.streams=Object.entries(t).map(([s,i])=>[Number(s),i])}}maybeAbandon(e){if(e.abandoned)return true;const t=!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3;if(!t)return false;const s=this.sentQueue.findIndex(i=>i===e);for(let i=s;i>=0;i--){const n=this.sentQueue.at(i);n.abandoned=true;n.retransmit=false;if(n.flags&ws){break}}for(let i=s;i<this.sentQueue.length;i++){const n=this.sentQueue.at(i);n.abandoned=true;n.retransmit=false;if(n.flags&ws){break}}return true}static getCapabilities(){return new Xo(65536)}setRemotePort(e){this.remotePort=e}async start(e){if(!this.started){this.started=true;this.setConnectionState(\"connecting\");if(e){this.setRemotePort(e)}if(!this.isServer){await this.init()}}}async init(){const e=new Rt;e.initiateTag=this.localVerificationTag;e.advertisedRwnd=this.advertisedRwnd;e.outboundStreams=this._outboundStreamsCount;e.inboundStreams=this._inboundStreamsMax;e.initialTsn=this.localTsn;this.setExtensions(e.params);v(\"send init\",e);try{await this.sendChunk(e);this.timer1Start(e);this.setState(A.COOKIE_WAIT)}catch(t){v(\"send init failed\",t.message)}}setExtensions(e){const t=[];if(this.localPartialReliability){e.push([Pd,Buffer.from(\"\")]);t.push(xt.type)}t.push(Zi.type);e.push([Id,Buffer.from(t)])}async sendChunk(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){throw new Error(\"invalid remote port\")}const t=yd(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){if(e!=this.associationState){this.associationState=e}if(e===A.ESTABLISHED){this.isStopping=false;this.isClosed=false;this.setConnectionState(\"connected\");this.heartbeatStart()}else if(e===A.CLOSED){this.isClosed=true;this.timer1Cancel();this.timer2Cancel();this.timer3Cancel();this.timerReconfigCancel();this.heartbeatCancel();if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}this.setConnectionState(\"closed\");this.removeAllListeners()}}setConnectionState(e){this.state=e;v(\"setConnectionState\",e);this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(A.CLOSED);return}this.isStopping=true;this.transport.onData=void 0;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}if(this.associationState!==A.CLOSED){await this.abort()}this.setState(A.CLOSED);clearTimeout(this.timer1Handle);clearTimeout(this.timer2Handle);clearTimeout(this.timer3Handle);clearTimeout(this.timerReconfigHandle);clearTimeout(this.timerHeartbeatHandle);clearTimeout(this.sackTimeout)}async abort(){const e=new ms;await this.sendChunk(e).catch(t=>{v(\"send abort failed\",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}};var Qo=class{static{a(this,\"InboundStream\")}constructor(){this.reassembly=[];this.streamSequenceNumber=0}addChunk(e){if(this.reassembly.length===0||ae(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(const[t,s]of Td(this.reassembly)){if(s.tsn===e.tsn)throw new Error(\"duplicate chunk in reassembly\");if(ae(s.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0;let t;let s;let i;while(e<this.reassembly.length){const n=this.reassembly[e];if(t===void 0){i=!(n.flags&tn);if(!(n.flags&en)){if(i){break}else{e++;continue}}if(i&&Ei(n.streamSeqNum,this.streamSequenceNumber)){break}s=n.tsn;t=e}else if(n.tsn!==s){if(i){break}else{t=void 0;e++;continue}}if(n.flags&ws){const o=this.reassembly.slice(t,e+1).map(d=>d.userData);const c=o.length===1?o[0]:Buffer.concat(o);this.reassembly.splice(t,e+1-t);if(i&&n.streamSeqNum===this.streamSequenceNumber){this.streamSequenceNumber=j(this.streamSequenceNumber,1)}e=t;yield[n.streamId,n.protocol,c]}else{e++}s=_t(s)}}pruneChunks(e){let t=-1,s=0;for(const[i,n]of this.reassembly.entries()){if(Xt(e,n.tsn)){t=i;s+=n.userData.length}else{break}}this.reassembly=this.reassembly.slice(t+1);return s}};var Xo=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};function At(r){return(r-1)%$e}a(At,\"tsnMinusOne\");function _t(r){return(r+1)%$e}a(_t,\"tsnPlusOne\");function _(r,e=r){return new DOMException(e,r)}a(_,\"createWebRtcDomException\");function Re(r){return new TypeError(r)}a(Re,\"createWebRtcTypeError\");var Lr=a(()=>({type:\"nack\"}),\"useNACK\");var Bt=a(()=>({type:\"nack\",parameter:\"pli\"}),\"usePLI\");var Dr=a(()=>({type:\"goog-remb\"}),\"useREMB\");var rn=a(()=>({type:\"transport-cc\"}),\"useTWCC\");var Zo=a((r={})=>new re({mimeType:\"video/h264\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],parameters:\"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1\",...r}),\"useH264\");var nn=a((r={})=>new re({mimeType:\"video/VP8\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useVP8\");var ea=a((r={})=>new re({mimeType:\"video/VP9\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useVP9\");var Tf=a((r={})=>new re({mimeType:\"video/AV1X\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useAV1X\");var on=a((r={})=>new re({mimeType:\"audio/OPUS\",clockRate:48e3,channels:2,...r}),\"useOPUS\");var an=a((r={})=>new re({mimeType:\"audio/PCMU\",clockRate:8e3,channels:1,payloadType:0,...r}),\"usePCMU\");function Ad(){return{audio:[on(),an()],video:[nn()]}}a(Ad,\"defaultCodecs\");function _d(r){return new re({mimeType:r.mimeType,clockRate:r.clockRate,...r.channels!=void 0?{channels:r.channels}:{},...r.payloadType!=void 0?{payloadType:r.payloadType}:{},rtcpFeedback:r.rtcpFeedback.map(e=>({...e})),...r.parameters!=void 0?{parameters:r.parameters}:{},direction:r.direction})}a(_d,\"cloneCodecParameters\");var Bd=[Tf(),ea(),nn(),Zo(),on(),an()].map(r=>r.mimeType);var db=Bd.filter(r=>r.toLowerCase().startsWith(\"video/\"));var hb=Bd.filter(r=>r.toLowerCase().startsWith(\"audio/\"));var $u=require(\"node:crypto\");var Vu=require(\"node:net\");var ia=require(\"node:crypto\");var ce={rsa_1:1,ecdsa_3:3};var cn={sha256_4:4};var dn={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199};var Ld=Object.values(dn);var Ve={x25519_29:29,secp256r1_23:23};var hn=Object.values(Ve);var un={named_curve_3:3};var ta={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027};var Dd=[1,64];var ln=[{hash:cn.sha256_4,signature:ce.rsa_1},{hash:cn.sha256_4,signature:ce.ecdsa_3}];var Ye=require(\"node:crypto\");function Qe(r,e){const t=e.length;if(t<128)return Buffer.concat([Buffer.from([r,t]),e]);const s=[];for(let i=t;i>0;i=Math.floor(i/256))s.unshift(i&255);return Buffer.concat([Buffer.from([r,128|s.length,...s]),e])}a(Qe,\"der\");var Lt=a((...r)=>Qe(48,Buffer.concat(r)),\"sequence\");var wf=a((...r)=>Qe(49,Buffer.concat(r)),\"set\");var bf=Buffer.from([5,0]);var Cf=a(r=>Qe(12,Buffer.from(r,\"utf8\")),\"utf8String\");var Ef=a(r=>Qe(3,Buffer.concat([Buffer.from([0]),r])),\"bitString\");var Rf=a((r,e)=>Qe(160|r,e),\"explicit\");function Nd(r){let e=0;while(e<r.length-1&&r[e]===0)e++;const t=r.subarray(e);return Qe(2,t[0]&128?Buffer.concat([Buffer.from([0]),t]):t)}a(Nd,\"integer\");function sa(r){const e=r.split(\".\").map(Number);const t=[e[0]*40+e[1]];for(const s of e.slice(2)){const i=[s&127];for(let n=Math.floor(s/128);n>0;n=Math.floor(n/128))i.unshift(128|n&127);t.push(...i)}return Qe(6,Buffer.from(t))}a(sa,\"oid\");function Md(r){const e=r.toISOString().replace(/[-:T]/g,\"\").slice(0,14);return r.getUTCFullYear()<2050?Qe(23,Buffer.from(`${e.slice(2)}Z`)):Qe(24,Buffer.from(`${e}Z`))}a(Md,\"time\");var xf=a(r=>Lt(wf(Lt(sa(\"2.5.4.3\"),Cf(r)))),\"commonName\");function Od(r=\"ecdsa\",e=\"WebRTC\",t=30){const{privateKey:s,publicKey:i}=r===\"ecdsa\"?(0,Ye.generateKeyPairSync)(\"ec\",{namedCurve:\"prime256v1\"}):(0,Ye.generateKeyPairSync)(\"rsa\",{modulusLength:2048,publicExponent:65537});const n=r===\"ecdsa\"?Lt(sa(\"1.2.840.10045.4.3.2\")):Lt(sa(\"1.2.840.113549.1.1.11\"),bf);const o=new Date(Date.now()-24*60*60*1e3);const c=new Date(o.getTime()+(t+1)*24*60*60*1e3);const d=(0,Ye.randomBytes)(8);d[0]&=127;const h=xf(e);const l=Lt(Rf(0,Nd(Buffer.from([2]))),Nd(d),n,h,Lt(Md(o),Md(c)),h,i.export({type:\"spki\",format:\"der\"}));const u=(0,Ye.sign)(\"sha256\",l,s);const g=Lt(l,n,Ef(u));return{certPem:kf(g,\"CERTIFICATE\"),keyPem:s.export({type:\"pkcs8\",format:\"pem\"})}}a(Od,\"createDtlsCertificate\");function kf(r,e){const t=r.toString(\"base64\").match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----\n${t.join(\"\\n\")}\n-----END ${e}-----\n`}a(kf,\"toPem\");function fn(r){const e=r.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);if(!e)throw new Error(\"no certificate in the PEM text\");return Buffer.from(e[1].replace(/\\s+/g,\"\"),\"base64\")}a(fn,\"certificateDer\");function Ud(r){return(0,Ye.createPrivateKey)(r)}a(Ud,\"privateKeyFromPem\");var pn=require(\"node:crypto\");var xe=require(\"node:crypto\");var Hd=a(()=>{const r=(0,xe.createECDH)(\"prime256v1\");const e=r.generateKeys();return{privateKey:r.getPrivateKey(),publicKey:e}},\"p256Keypair\");var zd=a(({publicKey:r,privateKey:e})=>{const t=(0,xe.createECDH)(\"prime256v1\");t.setPrivateKey(e);return t.computeSecret(r)},\"p256PreMasterSecret\");var qd=Buffer.from(\"302e020100300506032b656e04220420\",\"hex\");var Fd=Buffer.from(\"302a300506032b656e032100\",\"hex\");var Kd=a(()=>{const{privateKey:r,publicKey:e}=(0,xe.generateKeyPairSync)(\"x25519\");return{privateKey:r.export({type:\"pkcs8\",format:\"der\"}).subarray(qd.length),publicKey:e.export({type:\"spki\",format:\"der\"}).subarray(Fd.length)}},\"x25519Keypair\");var Gd=a(({publicKey:r,privateKey:e})=>(0,xe.diffieHellman)({privateKey:(0,xe.createPrivateKey)({key:Buffer.concat([qd,e]),format:\"der\",type:\"pkcs8\"}),publicKey:(0,xe.createPublicKey)({key:Buffer.concat([Fd,r]),format:\"der\",type:\"spki\"})}),\"x25519PreMasterSecret\");function mn(r,e,t){switch(t){case Ve.secp256r1_23:return zd({publicKey:r,privateKey:e});case Ve.x25519_29:return Gd({publicKey:r,privateKey:e});default:throw new Error}}a(mn,\"prfPreMasterSecret\");function jd(r,e,t){const s=(0,pn.createHmac)(r,e);s.update(t);return s.digest()}a(jd,\"hmac\");function Nr(r,e,t,s=\"sha256\"){const i=t;const n=[];let o=e;do{o=jd(s,r,o);const c=jd(s,r,Buffer.concat([o,e]));n.push(c);t-=c.length}while(t>0);return Buffer.concat(n,i)}a(Nr,\"prfPHash\");function gn(r,e,t){const s=Buffer.concat([Buffer.from(\"master secret\"),e,t]);return Nr(r,s,48)}a(gn,\"prfMasterSecret\");function Sn(r,e){const t=$d(\"sha256\",e);const s=\"extended master secret\";return Nr(r,Buffer.concat([Buffer.from(s),t]),48)}a(Sn,\"prfExtendedMasterSecret\");function Wd(r,e,t,s,i,n){const o=n?s:i;const c=n?i:s;const d=Buffer.concat([Buffer.from(r),o,c]);return Nr(t,d,e)}a(Wd,\"exportKeyingMaterial\");function $d(r,e){return(0,pn.createHash)(r).update(e).digest()}a($d,\"hash\");function Vd(r,e,t,s=12){const i=$d(\"sha256\",e);return Nr(r,Buffer.concat([Buffer.from(t),i]),s)}a(Vd,\"prfVerifyData\");function Yd(r,e){return Vd(r,e,\"client finished\")}a(Yd,\"prfVerifyDataClient\");function Qd(r,e){return Vd(r,e,\"server finished\")}a(Qd,\"prfVerifyDataServer\");function Xd(r,e,t,s,i,n,o=\"sha256\"){const c=s*2+i*2;const d=r;const h=Buffer.concat([t,e]);const l=Nr(d,Buffer.concat([Buffer.from(\"key expansion\"),h]),c,o);const u=new x.BinaryReader(l);const g=u.readBuffer(s);const S=u.readBuffer(s);const p=u.readBuffer(i);const f=u.readBuffer(i);const y=Buffer.alloc(n,0);const m=Buffer.alloc(n,0);p.copy(y,0);f.copy(m,0);return{clientWriteKey:g,serverWriteKey:S,clientNonce:y,serverNonce:m}}a(Xd,\"prfEncryptionKeys\");var ie={CLIENT:1,SERVER:2};var Mr=class{static{a(this,\"AbstractCipher\")}constructor(){this.id=0;this.verifyDataLength=12}init(...e){throw new Error(\"not implemented\")}encrypt(...e){throw new Error(\"not implemented\")}decrypt(...e){throw new Error(\"not implemented\")}toString(){return this.name}};var{encode:vf,types:ra}=x;var Xe=class{static{a(this,\"CipherContext\")}constructor(e,t,s,i){this.sessionType=e;this.certPem=t;this.keyPem=s;if(t&&s&&i){this.parseX509(t,s,i)}}static{this.createSelfSignedCertificateWithKey=async(e,t)=>{const{certPem:s,keyPem:i}=Od(e.signature===ce.rsa_1?\"rsa\":\"ecdsa\");return{certPem:s,keyPem:i,signatureHash:e}}}encryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const i=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});e.fragment=i;e.recordLayerHeader.contentLen=i.length;return e}decryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const i=this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return i}verifyData(e){if(this.sessionType===ie.CLIENT)return Yd(this.masterSecret,e);else return Qd(this.masterSecret,e)}signatureData(e,t){return(0,ia.sign)(t,e,this.localPrivateKey)}generateKeySignature(e){const t=this.sessionType===ie.CLIENT?this.localRandom:this.remoteRandom;const s=this.sessionType===ie.SERVER?this.localRandom:this.remoteRandom;const i=this.valueKeySignature(t.serialize(),s.serialize(),this.localKeyPair.publicKey,this.namedCurve);return(0,ia.sign)(e,i,this.localPrivateKey)}parseX509(e,t,s){this.localCert=fn(e);this.localPrivateKey=Ud(t);this.signatureHashAlgorithm=s}valueKeySignature(e,t,s,i){const n=vf({type:un.named_curve_3,curve:i,len:s.length},{type:ra.uint8,curve:ra.uint16be,len:ra.uint8});return Buffer.concat([e,t,n,s])}};var Je=class{static{a(this,\"SrtpContext\")}static findMatchingSRTPProfile(e,t){for(const s of t){if(e.includes(s))return s}}};var Or=a(r=>\"0x\"+r.toString(\"hex\").replace(/(.)(.)/g,\"$1$2 \").split(\" \").filter(e=>e!=void 0&&e.length>0).join(\",0x\"),\"dumpBuffer\");var yn=a(r=>Object.entries({...r}).reduce((e,[t,s])=>{if(typeof s===\"number\"||typeof s===\"string\"){e[t]=s}if(Buffer.isBuffer(s)){e[t]=Or(s)}return e},{}),\"getObjectSummary\");var{decode:If,encode:Pf,types:Cs}=x;var O=class r{static{a(this,\"FragmentedHandshake\")}static{this.spec={msg_type:Cs.uint8,length:Cs.uint24be,message_seq:Cs.uint16be,fragment_offset:Cs.uint24be,fragment_length:Cs.uint24be,fragment:Cs.buffer(e=>e.current.fragment_length)}}constructor(e,t,s,i,n,o){this.msg_type=e;this.length=t;this.message_seq=s;this.fragment_offset=i;this.fragment_length=n;this.fragment=o}get summary(){return yn(this)}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(If(e,r.spec)))}serialize(){return Pf(this,r.spec)}chunk(e){let t=0;const s=this.fragment.length;if(s===0)return[new r(this.msg_type,s,this.message_seq,t,0,this.fragment)];const i=[];if(!e){e=1280-(20+8)-(1+3+2+3+3)}while(t<s){const n=Math.min(e,s-t);const o=Buffer.from(this.fragment.slice(t,t+n));if(o.length<=0){throw new Error(`Zero or less bytes processed while fragmenting handshake message.`)}i.push(new r(this.msg_type,s,this.message_seq,t,o.length,o));t+=o.length}return i}static assemble(e){if(!e?.length){throw new Error(\"cannot reassemble handshake from empty array\")}e=e.sort((s,i)=>s.fragment_offset-i.fragment_offset);const t=Buffer.alloc(e[0].length);for(const s of e){s.fragment.copy(t,s.fragment_offset)}return new r(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){const s=e.find(i=>i.msg_type===t);if(!s)return[];if(!e?.length)return[];return e.filter(i=>{return i.msg_type===s.msg_type&&i.message_seq===s.message_seq&&i.length===s.length})}};var{types:Af}=x;var{uint16be:Tn,uint24be:_f,buffer:Jd,array:Bf,uint8:Ur,string:Lf}=Af;var Df={type:Tn,data:Jd(Tn)};var Hr=Bf(Df,Tn,\"bytes\");var Zd=Jd(_f);var eh=Ur;var th=Lf(Tn);var sh={hash:Ur,signature:Ur};var Es={major:Ur,minor:Ur};var R;(function(r){r[r[\"hello_request_0\"]=0]=\"hello_request_0\";r[r[\"client_hello_1\"]=1]=\"client_hello_1\";r[r[\"server_hello_2\"]=2]=\"server_hello_2\";r[r[\"hello_verify_request_3\"]=3]=\"hello_verify_request_3\";r[r[\"certificate_11\"]=11]=\"certificate_11\";r[r[\"server_key_exchange_12\"]=12]=\"server_key_exchange_12\";r[r[\"certificate_request_13\"]=13]=\"certificate_request_13\";r[r[\"server_hello_done_14\"]=14]=\"server_hello_done_14\";r[r[\"certificate_verify_15\"]=15]=\"certificate_verify_15\";r[r[\"client_key_exchange_16\"]=16]=\"client_key_exchange_16\";r[r[\"finished_20\"]=20]=\"finished_20\"})(R||(R={}));var ih=require(\"node:crypto\");var{decode:Nf,encode:Mf,types:rh}=x;var ne=class r{static{a(this,\"DtlsRandom\")}static{this.spec={gmt_unix_time:rh.uint32be,random_bytes:rh.buffer(28)}}constructor(e=Math.floor(Date.now()/1e3),t=(0,ih.randomBytes)(28)){this.gmt_unix_time=e;this.random_bytes=t}static deSerialize(e){return new r(...Object.values(Nf(e,r.spec)))}static from(e){return new r(...Object.values(e))}serialize(){return Mf(this,r.spec)}};var{decode:Of,encode:Uf,types:pe}=x;var Rs=class r{static{a(this,\"ClientHello\")}static{this.spec={clientVersion:{major:pe.uint8,minor:pe.uint8},random:ne.spec,sessionId:pe.buffer(pe.uint8),cookie:pe.buffer(pe.uint8),cipherSuites:pe.array(pe.uint16be,pe.uint16be,\"bytes\"),compressionMethods:pe.array(pe.uint8,pe.uint8,\"bytes\"),extensions:Hr}}constructor(e,t,s,i,n,o,c){this.clientVersion=e;this.random=t;this.sessionId=s;this.cookie=i;this.cipherSuites=n;this.compressionMethods=o;this.extensions=c;this.msgType=R.client_hello_1;this.messageSeq=0}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(Of(e,r.spec)))}serialize(){return Uf(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var oh=require(\"node:timers/promises\");var{decode:Hf,encode:zf,types:wn}=x;var bn=class r{static{a(this,\"MACHeader\")}static{this.spec={epoch:wn.uint16be,sequenceNumber:wn.uint48be,contentType:wn.uint8,protocolVersion:Es,contentLen:wn.uint16be}}constructor(e,t,s,i,n){this.epoch=e;this.sequenceNumber=t;this.contentType=s;this.protocolVersion=i;this.contentLen=n}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(Hf(e,r.spec)))}serialize(){return zf(this,r.spec)}};var xs=class r{static{a(this,\"DtlsPlaintext\")}constructor(e,t){this.recordLayerHeader=e;this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:Or(this.fragment)}}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){if(e.length<13){throw new Error(\"Invalid DTLS record: buffer is too short\")}const t=e.readUInt8(0);const s=e.readUInt8(1);const i=e.readUInt8(2);const n=e.readUInt16BE(3);const o=e.slice(5,11).readUIntBE(0,6);const c=e.readUInt16BE(11);if(e.length<13+c){throw new Error(\"Invalid DTLS record: fragment length exceeds buffer\")}const d=e.slice(13,13+c);const h=new r({contentType:t,protocolVersion:{major:s,minor:i},epoch:n,sequenceNumber:o,contentLen:c},d);return h}serialize(){const e=this.fragment.length;const t=13+e;const s=Buffer.alloc(t);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);return s}computeMACHeader(){return new bn(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}};var Cn=a(r=>e=>{r.lastFlight=e;return e.flatMap(t=>{t.messageSeq=r.sequenceNumber++;const s=t.toFragment();const i=s.chunk();return i})},\"createFragments\");var Ne=a(r=>(e,t)=>{return e.map(s=>{const i=new xs({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment);return i})},\"createPlaintext\");var H;(function(r){r[r[\"changeCipherSpec\"]=20]=\"changeCipherSpec\";r[r[\"alert\"]=21]=\"alert\";r[r[\"handshake\"]=22]=\"handshake\";r[r[\"applicationData\"]=23]=\"applicationData\"})(H||(H={}));var zr;(function(r){r[r[\"CloseNotify\"]=0]=\"CloseNotify\";r[r[\"UnexpectedMessage\"]=10]=\"UnexpectedMessage\";r[r[\"BadRecordMac\"]=20]=\"BadRecordMac\";r[r[\"DecryptionFailed\"]=21]=\"DecryptionFailed\";r[r[\"RecordOverflow\"]=22]=\"RecordOverflow\";r[r[\"DecompressionFailure\"]=30]=\"DecompressionFailure\";r[r[\"HandshakeFailure\"]=40]=\"HandshakeFailure\";r[r[\"NoCertificate\"]=41]=\"NoCertificate\";r[r[\"BadCertificate\"]=42]=\"BadCertificate\";r[r[\"UnsupportedCertificate\"]=43]=\"UnsupportedCertificate\";r[r[\"CertificateRevoked\"]=44]=\"CertificateRevoked\";r[r[\"CertificateExpired\"]=45]=\"CertificateExpired\";r[r[\"CertificateUnknown\"]=46]=\"CertificateUnknown\";r[r[\"IllegalParameter\"]=47]=\"IllegalParameter\";r[r[\"UnknownCa\"]=48]=\"UnknownCa\";r[r[\"AccessDenied\"]=49]=\"AccessDenied\";r[r[\"DecodeError\"]=50]=\"DecodeError\";r[r[\"DecryptError\"]=51]=\"DecryptError\";r[r[\"ExportRestriction\"]=60]=\"ExportRestriction\";r[r[\"ProtocolVersion\"]=70]=\"ProtocolVersion\";r[r[\"InsufficientSecurity\"]=71]=\"InsufficientSecurity\";r[r[\"InternalError\"]=80]=\"InternalError\";r[r[\"UserCanceled\"]=90]=\"UserCanceled\";r[r[\"NoRenegotiation\"]=100]=\"NoRenegotiation\";r[r[\"UnsupportedExtension\"]=110]=\"UnsupportedExtension\"})(zr||(zr={}));var qf=b(\"webrtc/dtls/flight/flight:warn\");var nh=b(\"webrtc/dtls/flight/flight:err\");var me=class r{static{a(this,\"Flight\")}static{this.RetransmitCount=10}constructor(e,t,s,i){this.transport=e;this.dtls=t;this.flight=s;this.nextFlight=i;this.state=\"PREPARING\";this.send=n=>Promise.all(n.map(o=>this.transport.send(o)))}createPacket(e){const t=Cn(this.dtls)(e);this.dtls.bufferHandshakeCache(t,true,this.flight);const s=Ne(this.dtls)(t.map(i=>({type:H.handshake,fragment:i.serialize()})),++this.dtls.recordSequenceNumber);return s}async transmit(e){const t=this.transport.closing.signal;let s=0;for(;s<=r.RetransmitCount;s++){if(t.aborted)return;this.setState(\"SENDING\");this.send(e).catch(i=>{nh(\"fail to send\",i)});this.setState(\"WAITING\");if(this.nextFlight===void 0){this.setState(\"FINISHED\");break}try{await(0,oh.setTimeout)(1e3*((s+1)/2),void 0,{signal:t})}catch{return}if(this.dtls.flight>=this.nextFlight){this.setState(\"FINISHED\");break}else{qf(this.dtls.sessionId,\"retransmit\",s,this.dtls.flight)}}if(s>r.RetransmitCount){nh(this.dtls.sessionId,\"retransmit failed\",s);throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}}setState(e){this.state=e}};var En=class extends me{static{a(this,\"Flight1\")}constructor(e,t,s){super(e,t,1,3);this.cipher=s}async exec(e){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;const t=new Rs({major:255-1,minor:255-2},new ne,Buffer.from([]),Buffer.from([]),Ld,[0],e);this.dtls.version=t.clientVersion;this.cipher.localRandom=ne.from(t.random);const s=this.createPacket([t]);const i=Buffer.concat(s.map(n=>n.serialize()));await this.transmit([i])}};var Ff=b(\"webrtc/dtls/flight/client/flight3:log\");var Rn=class extends me{static{a(this,\"Flight3\")}constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3;this.dtls.handshakeCache=[];const[t]=this.dtls.lastFlight;Ff(\"dtls version\",t.clientVersion);t.cookie=e.cookie;this.dtls.cookie=e.cookie;const s=this.createPacket([t]);const i=Buffer.concat(s.map(n=>n.serialize()));await this.transmit([i])}};var xn={NULL:0,ECDHE:1};var qr={NULL:0,RSA:1,ECDSA:2,PSK:3};var Fr={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5};var Dt=class{static{a(this,\"KeyExchange\")}constructor(){this.id=0}toString(){return this.name}};function ah(){const r=new Dt;r.id=Fr.RSA;r.name=\"RSA\";r.keyType=qr.RSA;return r}a(ah,\"createRSAKeyExchange\");function ch(){const r=new Dt;r.id=Fr.ECDHE_RSA;r.name=\"ECDHE_RSA\";r.signType=xn.ECDHE;r.keyType=qr.RSA;return r}a(ch,\"createECDHERSAKeyExchange\");function dh(){const r=new Dt;r.id=Fr.ECDHE_ECDSA;r.name=\"ECDHE_ECDSA\";r.signType=xn.ECDHE;r.keyType=qr.ECDSA;return r}a(dh,\"createECDHEECDSAKeyExchange\");function hh(){const r=new Dt;r.id=Fr.PSK;r.name=\"PSK\";r.signType=xn.NULL;r.keyType=qr.PSK;return r}a(hh,\"createPSKKeyExchange\");function uh(){const r=new Dt;r.id=Fr.ECDHE_PSK;r.name=\"ECDHE_PSK\";r.signType=xn.ECDHE;r.keyType=qr.PSK;return r}a(uh,\"createECDHEPSKKeyExchange\");var kn=require(\"node:crypto\");var Kf=b(\"webrtc/dtls/cipher/suites/aead:err\");var Kr=class extends Mr{static{a(this,\"AEADCipher\")}constructor(){super();this.keyLength=0;this.nonceLength=0;this.ivLength=0;this.authTagLength=0;this.nonceImplicitLength=0;this.nonceExplicitLength=0}get summary(){return yn(this)}init(e,t,s){const i=Xd(e,s,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=i.clientWriteKey;this.serverWriteKey=i.serverWriteKey;this.clientNonce=i.clientNonce;this.serverNonce=i.serverNonce}encrypt(e,t,s){const i=e===ie.CLIENT;const n=i?this.clientNonce:this.serverNonce;const o=i?this.clientWriteKey:this.serverWriteKey;if(!n||!o)throw new Error;n.writeUInt16BE(s.epoch,this.nonceImplicitLength);n.writeUIntBE(s.sequenceNumber,this.nonceImplicitLength+2,6);const c=n.slice(this.nonceImplicitLength);const d=this.encodeAdditionalBuffer(s,t.length);const h=(0,kn.createCipheriv)(this.blockAlgorithm,o,n,{authTagLength:this.authTagLength});h.setAAD(d,{plaintextLength:t.length});const l=h.update(t);const u=h.final();const g=h.getAuthTag();return Buffer.concat([c,l,u,g])}encodeAdditionalBuffer(e,t){const s=Buffer.alloc(13);s.writeUInt16BE(e.epoch,0);s.writeUintBE(e.sequenceNumber,2,6);s.writeUInt8(e.type,8);s.writeUInt16BE(e.version,9);s.writeUInt16BE(t,11);return s}decrypt(e,t,s){const i=e===ie.CLIENT;const n=i?this.serverNonce:this.clientNonce;const o=i?this.serverWriteKey:this.clientWriteKey;if(!n||!o)throw new Error;const c=t.subarray(0,this.nonceExplicitLength);c.copy(n,this.nonceImplicitLength);const d=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength);const h=t.subarray(t.length-this.authTagLength);const l=this.encodeAdditionalBuffer(s,d.length);const u=(0,kn.createDecipheriv)(this.blockAlgorithm,o,n,{authTagLength:this.authTagLength});u.setAuthTag(h);u.setAAD(l,{plaintextLength:d.length});const g=u.update(d);try{const S=u.final();return S.length>0?Buffer.concat([g,S]):g}catch(S){Kf(\"decrypt failed\",S,e,Or(t),s,this.summary);throw S}}};var G={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};var Gr={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var jr={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var lh=ah();var fh=ch();var ph=dh();var mh=hh();var gh=uh();function vn(r){switch(r){case G.TLS_RSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_RSA_WITH_AES_128_GCM_SHA256,\"TLS_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",lh,Gr);case G.TLS_RSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_RSA_WITH_AES_256_GCM_SHA384,\"TLS_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",lh,jr,\"sha384\");case G.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",fh,Gr);case G.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",fh,jr,\"sha384\");case G.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",ph,Gr);case G.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",ph,jr,\"sha384\");case G.TLS_PSK_WITH_AES_128_GCM_SHA256:return Me(G.TLS_PSK_WITH_AES_128_GCM_SHA256,\"TLS_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",mh,Gr,\"sha256\");case G.TLS_PSK_WITH_AES_256_GCM_SHA384:return Me(G.TLS_PSK_WITH_AES_256_GCM_SHA384,\"TLS_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",mh,jr,\"sha384\");case G.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",gh,Gr,\"sha256\");case G.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",gh,jr,\"sha384\");default:break}return null}a(vn,\"createCipher\");function Me(r,e,t,s,i,n=\"sha256\"){const o=new Kr;o.id=r;o.name=e;o.blockAlgorithm=t;o.kx=s;o.hashAlgorithm=n;o.keyLength=i.K_LEN;o.nonceLength=i.N_MAX;o.nonceImplicitLength=4;o.nonceExplicitLength=8;o.ivLength=o.nonceImplicitLength;o.authTagLength=16;return o}a(Me,\"createAEADCipher\");function In(r){switch(r){case Ve.secp256r1_23:{const{privateKey:e,publicKey:t}=Hd();return{curve:r,privateKey:e,publicKey:t}}case Ve.x25519_29:{const{privateKey:e,publicKey:t}=Kd();return{curve:r,privateKey:e,publicKey:t}}default:throw new Error}}a(In,\"generateKeyPair\");var Oe=class{static{a(this,\"ExtendedMasterSecret\")}static{this.type=23}};var{decode:Gf,encode:jf,types:Sh}=x;var Ue=class r{static{a(this,\"RenegotiationIndication\")}static{this.type=65281}static{this.spec={type:Sh.uint16be,data:Sh.uint8}}constructor(e={}){this.type=r.type;this.data=0;Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(Gf(e,r.spec))}serialize(){return jf(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:Wf,encode:$f,types:na}=x;var ge=class r{static{a(this,\"UseSRTP\")}static{this.type=14}static{this.spec={type:na.uint16be,data:na.buffer(na.uint16be)}}constructor(e={}){this.type=r.type;this.data=Buffer.from([]);this.profiles=[];this.mki=Buffer.from([0]);Object.assign(this,e)}static create(e,t){const s=new r({profiles:e,mki:t});return s}static deSerialize(e){const t=new r(Wf(e,r.spec));const s=t.data.readUInt16BE();const i=new Array(s/2);for(let n=0;n<i.length;n++){i[n]=t.data.readUInt16BE(n*2+2)}t.profiles=i;t.mki=t.data.slice(s+2);return t}serialize(){const e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);const t=Buffer.concat([e,...this.profiles.map(s=>{const i=Buffer.alloc(2);i.writeUInt16BE(s);return i}),this.mki]);this.data=t;return $f(this,r.spec)}static fromData(e){const t=Buffer.alloc(4);t.writeUInt16BE(r.type);t.writeUInt16BE(e.length,2);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}};var{decode:Vf,encode:Yf,types:yh}=x;var Ze=class r{static{a(this,\"Certificate\")}static{this.spec={certificateList:yh.array(Zd,yh.uint24be,\"bytes\")}}constructor(e){this.certificateList=e;this.msgType=R.certificate_11}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(...Object.values(Vf(e,r.spec)))}serialize(){return Yf(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:Qf,encode:Xf,types:Jf}=x;var ks=class r{static{a(this,\"ChangeCipherSpec\")}static{this.spec={type:Jf.uint8}}constructor(e=1){this.type=e}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(Qf(e,r.spec)))}serialize(){return Xf(this,r.spec)}};var{decode:Zf,encode:ep,types:oa}=x;var vs=class r{static{a(this,\"CertificateVerify\")}static{this.spec={algorithm:oa.uint16be,signature:oa.buffer(oa.uint16be)}}constructor(e,t){this.algorithm=e;this.signature=t;this.msgType=R.certificate_verify_15}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){const t=Zf(e,r.spec);return new r(...Object.values(t))}serialize(){return ep(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:tp,encode:sp,types:Th}=x;var Is=class r{static{a(this,\"ClientKeyExchange\")}static{this.spec={publicKey:Th.buffer(Th.uint8)}}constructor(e){this.publicKey=e;this.msgType=R.client_key_exchange_16}static createEmpty(){return new r(void 0)}static deSerialize(e){const t=tp(e,r.spec);return new r(...Object.values(t))}serialize(){return sp(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Nt=class r{static{a(this,\"Finished\")}constructor(e){this.verifyData=e;this.msgType=R.finished_20}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(e)}serialize(){return this.verifyData}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:rp,encode:ip,types:Ps}=x;var As=class r{static{a(this,\"ServerCertificateRequest\")}static{this.spec={certificateTypes:Ps.array(eh,Ps.uint8,\"bytes\"),signatures:Ps.array(sh,Ps.uint16be,\"bytes\"),authorities:Ps.array(th,Ps.uint16be,\"bytes\")}}constructor(e,t,s){this.certificateTypes=e;this.signatures=t;this.authorities=s;this.msgType=R.certificate_request_13}static createEmpty(){return new r(void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(rp(e,r.spec)))}serialize(){return ip(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:wh,encode:bh,types:Pn}=x;var _s=class r{static{a(this,\"ServerHello\")}static{this.spec={serverVersion:Es,random:ne.spec,sessionId:Pn.buffer(Pn.uint8),cipherSuite:Pn.uint16be,compressionMethod:Pn.uint8}}constructor(e,t,s,i,n,o){this.serverVersion=e;this.random=t;this.sessionId=s;this.cipherSuite=i;this.compressionMethod=n;this.extensions=o;this.msgType=R.server_hello_2}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=wh(e,r.spec);const s=new r(...Object.values(t));const i=s.serialize();if(i.length<e.length){return new r(...Object.values(wh(e,{...r.spec,extensions:Hr})))}return s}serialize(){return this.extensions===void 0?bh(this,r.spec):bh(this,{...r.spec,extensions:Hr})}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:np,encode:op}=x;var Bs=class r{static{a(this,\"ServerHelloDone\")}constructor(){this.msgType=R.server_hello_done_14}static{this.spec={}}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(np(e,r.spec)))}serialize(){return op(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{encode:ap}=x;function Ch(r,e){return ap(r,e)}a(Ch,\"encodeBuffer\");var{decode:cp,types:ut}=x;var Ls=class r{static{a(this,\"ServerKeyExchange\")}static{this.spec={ellipticCurveType:ut.uint8,namedCurve:ut.uint16be,publicKeyLength:ut.uint8,publicKey:ut.buffer(e=>e.current.publicKeyLength),hashAlgorithm:ut.uint8,signatureAlgorithm:ut.uint8,signatureLength:ut.uint16be,signature:ut.buffer(e=>e.current.signatureLength)}}constructor(e,t,s,i,n,o,c,d){this.ellipticCurveType=e;this.namedCurve=t;this.publicKeyLength=s;this.publicKey=i;this.hashAlgorithm=n;this.signatureAlgorithm=o;this.signatureLength=c;this.signature=d;this.msgType=R.server_key_exchange_12}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=cp(e,r.spec);return new r(...Object.values(t))}serialize(){const e=Ch(this,r.spec);return e}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var X=b(\"webrtc/dtls/flight/client/flight5:log\");var An=class extends me{static{a(this,\"Flight5\")}constructor(e,t,s,i){super(e,t,5,7);this.cipher=s;this.srtp=i}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,4);const t=(()=>{switch(e.msg_type){case R.server_hello_2:return _s.deSerialize(e.fragment);case R.certificate_11:return Ze.deSerialize(e.fragment);case R.server_key_exchange_12:return Ls.deSerialize(e.fragment);case R.certificate_request_13:return As.deSerialize(e.fragment);case R.server_hello_done_14:return Bs.deSerialize(e.fragment)}})();if(t){Ds[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}}async exec(){if(this.dtls.flight===5){X(this.dtls.sessionId,\"flight5 twice\");this.send(this.dtls.lastMessage).catch(s=>X(\"send failed\",s));return}this.dtls.flight=5;const e=this.dtls.requestedCertificateTypes.length>0;X(this.dtls.sessionId,\"send flight5\",e);const t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(s=>s);this.dtls.lastMessage=t;await this.transmit(t)}sendCertificate(){const e=new Ze([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;const e=new Is(this.cipher.localKeyPair.publicKey);const t=this.createPacket([e]);const s=Buffer.concat(t.map(d=>d.serialize()));const i=this.cipher.localKeyPair;const n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error(\"not exist\");const o=mn(n.publicKey,i.privateKey,i.curve);X(this.dtls.sessionId,\"extendedMasterSecret\",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);const c=Buffer.concat(this.dtls.sortedHandshakeCache.map(d=>d.serialize()));this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?Sn(o,c):gn(o,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize());this.cipher.cipher=vn(this.cipher.cipherSuite);this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize());X(this.dtls.sessionId,\"cipher\",this.cipher.cipher.summary);return s}sendCertificateVerify(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(c=>c.serialize()));const t=this.cipher.signatureData(e,\"sha256\");const s=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case ce.ecdsa_3:return ta.ecdsa_secp256r1_sha256;case ce.rsa_1:return ta.rsa_pkcs1_sha256}})();if(!s)throw new Error;X(this.dtls.sessionId,\"signatureScheme\",this.cipher.signatureHashAlgorithm?.signature,s);const i=new vs(s,t);const n=this.createPacket([i]);const o=Buffer.concat(n.map(c=>c.serialize()));return o}sendChangeCipherSpec(){const e=ks.createEmpty().serialize();const t=Ne(this.dtls)([{type:H.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Nt(t);this.dtls.epoch=1;const[i]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const n=this.cipher.encryptPacket(i).serialize();X(this.dtls.sessionId,\"finished\",this.cipher.cipher.summary);return n}};var Ds={};Ds[R.server_hello_2]=({cipher:r,srtp:e,dtls:t})=>s=>{X(t.sessionId,\"serverHello\",s.cipherSuite);r.remoteRandom=ne.from(s.random);r.cipherSuite=s.cipherSuite;X(t.sessionId,\"selected cipherSuite\",r.cipherSuite);if(s.extensions){s.extensions.forEach(i=>{switch(i.type){case ge.type:{const n=ge.fromData(i.data);const o=Je.findMatchingSRTPProfile(n.profiles,t.options.srtpProfiles||[]);X(t.sessionId,\"selected srtp profile\",o);if(o==void 0)return;e.srtpProfile=o}break;case Oe.type:t.remoteExtendedMasterSecret=true;break;case Ue.type:X(t.sessionId,\"RenegotiationIndication\");break}})}};Ds[R.certificate_11]=({cipher:r,dtls:e})=>t=>{X(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Ds[R.server_key_exchange_12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;X(e.sessionId,\"ServerKeyExchange\",t);X(e.sessionId,\"selected curve\",t.namedCurve);r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey};r.localKeyPair=In(t.namedCurve)};Ds[R.certificate_request_13]=({dtls:r})=>e=>{X(r.sessionId,\"certificate_request\",e);r.requestedCertificateTypes=e.certificateTypes;r.requestedSignatureAlgorithms=e.signatures};Ds[R.server_hello_done_14]=({dtls:r})=>e=>{X(r.sessionId,\"server_hello_done\",e)};var{decode:dp,encode:hp,types:Eh}=x;var Ns=class r{static{a(this,\"ServerHelloVerifyRequest\")}static{this.spec={serverVersion:Es,cookie:Eh.buffer(Eh.uint8)}}constructor(e,t){this.serverVersion=e;this.cookie=t;this.msgType=R.hello_verify_request_3}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){return new r(...Object.values(dp(e,r.spec)))}serialize(){return hp(this,r.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Ah=require(\"node:timers/promises\");var up=b(\"webrtc/dtls/context/dtls:log\");var Wr=class{static{a(this,\"DtlsContext\")}constructor(e,t){this.options=e;this.sessionType=t;this.version={major:255-1,minor:255-2};this.lastFlight=[];this.lastMessage=[];this.recordSequenceNumber=0;this.sequenceNumber=0;this.epoch=0;this.flight=0;this.handshakeCache={};this.requestedCertificateTypes=[];this.requestedSignatureAlgorithms=[];this.remoteExtendedMasterSecret=false;this.checkHandshakesExist=s=>!s.find(i=>this.sortedHandshakeCache.find(n=>n.msg_type===i)==void 0)}get sessionId(){return this.cookie?this.cookie.toString(\"hex\").slice(0,10):\"\"}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((t,s)=>t.message_seq-s.message_seq))}bufferHandshakeCache(e,t,s){if(!this.handshakeCache[s]){this.handshakeCache[s]={data:[],isLocal:t,flight:s}}const i=e.filter(n=>{const o=this.handshakeCache[s].data.find(c=>c.msg_type===n.msg_type);if(o){up(this.sessionId,\"exist\",o.summary,t,s);return false}return true});this.handshakeCache[s].data=[...this.handshakeCache[s].data,...i]}};var _n=class{static{a(this,\"TransportContext\")}constructor(e){this.socket=e;this.closing=new AbortController;this.send=(t,s)=>{return this.socket.send(t,s)}}close(){this.closing.abort()}};var{decode:Rh,encode:lp,types:Bn}=x;var Mt=class r{static{a(this,\"EllipticCurves\")}static{this.type=10}static{this.spec={type:Bn.uint16be,data:Bn.array(Bn.uint16be,Bn.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){return new r}static fromData(e){return new r({type:r.type,data:Rh(e,r.spec.data)})}static deSerialize(e){return new r(Rh(e,r.spec))}serialize(){return lp(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:fp,encode:pp,types:$r}=x;var Ot=class r{static{a(this,\"Signature\")}static{this.type=13}static{this.spec={type:$r.uint16be,data:$r.array({hash:$r.uint8,signature:$r.uint8},$r.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(fp(e,r.spec))}serialize(){return pp(this,r.spec)}static fromData(e){const t=Buffer.alloc(2);t.writeUInt16BE(r.type);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:mp,encode:gp,types:xh}=x;var Vr=class r{static{a(this,\"Alert\")}static{this.spec={level:xh.uint8,description:xh.uint8}}constructor(e,t){this.level=e;this.description=t}static deSerialize(e){return new r(...Object.values(mp(e,r.spec)))}serialize(){return gp(this,r.spec)}};var kh=b(\"webrtc/dtls/record/receive:log\");var aa=b(\"webrtc/dtls/record/receive:err\");var vh=a(r=>{let e=0;const t=[];while(r.length>e){const s=r.readUInt16BE(e+11);if(r.length<e+(12+s)){break}const i=xs.deSerialize(r.subarray(e));t.push(i);e+=13+s}return t},\"parsePacket\");var Ih=a((r,e)=>t=>{const s=t.recordLayerHeader.contentType;switch(s){case H.changeCipherSpec:{kh(r.sessionId,\"change cipher spec\");return[{type:H.changeCipherSpec,data:void 0}]}case H.handshake:{let i=t.fragment;try{if(t.recordLayerHeader.epoch>0){kh(r.sessionId,\"decrypt handshake\");i=e.decryptPacket(t)}}catch(n){aa(r.sessionId,\"decrypt failed\",n);throw n}try{let n=0;const o=[];while(i.length>n){const c=O.deSerialize(i.subarray(n));o.push({type:H.handshake,data:c});n+=c.fragment_length+12}return o}catch(n){aa(r.sessionId,\"decSerialize failed\",n,i);throw n}}case H.applicationData:{return[{type:H.applicationData,data:e.decryptPacket(t)}]}case H.alert:{let i=Vr.deSerialize(t.fragment);if(zr[i.description]==void 0){const n=e.decryptPacket(t);i=Vr.deSerialize(n)}aa(r.sessionId,\"ContentType.alert\",i,zr[i.description],\"flight\",r.flight,\"lastFlight\",r.lastFlight);if(i.level>1){throw new Error(\"alert fatal error\")}return[{type:H.alert,data:void 0}]}default:{return[{type:H.alert,data:void 0}]}}},\"parsePlainText\");var{decode:Sp,types:Ln}=x;var ca=b(\"webrtc/dtls/socket:log\");var Ph=b(\"webrtc/dtls/socket:err\");var Ut=class{static{a(this,\"DtlsSocket\")}constructor(e,t){this.options=e;this.sessionType=t;this.onConnect=new w;this.onData=new w;this.onError=new w;this.onClose=new w;this.srtp=new Je;this.connected=false;this.extensions=[];this.bufferFragmentedHandshakes=[];this.udpOnMessage=s=>{const i=vh(s);for(const n of i){try{const o=Ih(this.dtls,this.cipher)(n);for(const c of o){switch(c.type){case H.handshake:{const d=c.data;const h=this.handleFragmentHandshake([d]);const l=Object.values(h.reduce((u,g)=>{if(!u[g.msg_type])u[g.msg_type]=[];u[g.msg_type].push(g);return u},{})).map(u=>O.assemble(u)).sort((u,g)=>u.msg_type-g.msg_type);this.onHandleHandshakes(l).catch(u=>{Ph(this.dtls.sessionId,\"onHandleHandshakes error\",u);this.onError.execute(u)})}break;case H.applicationData:{this.onData.execute(c.data)}break;case H.alert:this.onClose.execute();break}}}catch(o){Ph(this.dtls.sessionId,\"catch udpOnMessage error\",o)}}};this.waitForReady=async s=>{for(let i=0;i<10;i++){if(s())return;await(0,Ah.setTimeout)(100*i)}throw new Error(\"waitForReady timeout\")};this.send=async(s,i)=>{const n=Ne(this.dtls)([{type:H.applicationData,fragment:s}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(n).serialize(),i)};this.dtls=new Wr(this.options,this.sessionType);this.cipher=new Xe(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.transport=new _n(this.options.transport);this.setupExtensions();this.transport.socket.onData=this.udpOnMessage}renegotiation(){ca(\"renegotiation\",this.sessionType);this.connected=false;this.cipher=new Xe(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.dtls=new Wr(this.options,this.sessionType);this.srtp=new Je;this.extensions=[];this.bufferFragmentedHandshakes=[]}setupExtensions(){ca(this.dtls.sessionId,\"support srtpProfiles\",this.options.srtpProfiles);if(this.options.srtpProfiles&&this.options.srtpProfiles.length>0){const e=ge.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{const e=Mt.createEmpty();e.data=hn;this.extensions.push(e.extension)}{const e=Ot.createEmpty();e.data=ln;this.extensions.push(e.extension)}if(this.options.extendedMasterSecret){this.extensions.push({type:Oe.type,data:Buffer.alloc(0)})}{const e=Ue.createEmpty();this.extensions.push(e.extension)}}handleFragmentHandshake(e){let t=e.filter(s=>{if(s.fragment_length!==s.length){this.bufferFragmentedHandshakes.push(s);return false}return true});if(this.bufferFragmentedHandshakes.length>1){const[s]=this.bufferFragmentedHandshakes.slice(-1);if(s.fragment_offset+s.fragment_length===s.length){t=[...this.bufferFragmentedHandshakes,...t];this.bufferFragmentedHandshakes=[]}}return t}close(){this.transport.close();K(()=>this.transport.socket.close(),e=>ca(\"close failed\",e))}extractSessionKeys(e,t){const s=this.exportKeyingMaterial(\"EXTRACTOR-dtls_srtp\",e*2+t*2);const{clientKey:i,serverKey:n,clientSalt:o,serverSalt:c}=Sp(s,{clientKey:Ln.buffer(e),serverKey:Ln.buffer(e),clientSalt:Ln.buffer(t),serverSalt:Ln.buffer(t)});if(this.sessionType===ie.CLIENT){return{localKey:i,localSalt:o,remoteKey:n,remoteSalt:c}}else{return{localKey:n,localSalt:c,remoteKey:i,remoteSalt:o}}}exportKeyingMaterial(e,t){return Wd(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===ie.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}};var da=b(\"webrtc/dtls/client:log\");var Ms=class extends Ut{static{a(this,\"DtlsClient\")}constructor(e){super(e,ie.CLIENT);this.handleHandshakes=async t=>{da(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case R.hello_verify_request_3:{const i=Ns.deSerialize(s.fragment);await new Rn(this.transport,this.dtls).exec(i)}break;case R.server_hello_2:{if(this.connected)return;this.flight5=new An(this.transport,this.dtls,this.cipher,this.srtp);this.flight5.handleHandshake(s)}break;case R.certificate_11:case R.server_key_exchange_12:case R.certificate_request_13:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s)}break;case R.server_hello_done_14:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s);const i=[11,12,this.options.certificateRequest&&13].filter(n=>typeof n===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(i));await this.flight5?.exec()}break;case R.finished_20:{this.dtls.flight=7;this.connected=true;this.onConnect.execute();da(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;da(this.dtls.sessionId,\"start client\")}async connect(){await new En(this.transport,this.dtls,this.cipher).exec(this.extensions)}};var _h=require(\"node:crypto\");var ke=b(\"webrtc/dtls/flight/server/flight2:log\");var Bh=a((r,e,t,s)=>i=>{ke(\"dtls version\",i.clientVersion);e.flight=2;e.recordSequenceNumber=0;e.sequenceNumber=0;i.extensions.forEach(u=>{switch(u.type){case Mt.type:{const g=Mt.fromData(u.data).data;ke(e.sessionId,\"curves\",g);const S=g.filter(p=>hn.includes(p))[0];t.namedCurve=S;ke(e.sessionId,\"curve selected\",t.namedCurve)}break;case Ot.type:{if(!t.signatureHashAlgorithm)throw new Error(\"need to set certificate\");const g=Ot.fromData(u.data).data;ke(e.sessionId,\"hash,signature\",g);const S=g.find(f=>f.signature===t.signatureHashAlgorithm?.signature)?.signature;const p=g.find(f=>f.hash===t.signatureHashAlgorithm?.hash)?.hash;if(S==void 0||p==void 0){throw new Error(\"invalid signatureHash\")}}break;case ge.type:{if(!e.options?.srtpProfiles)return;if(e.options.srtpProfiles.length===0)return;const g=ge.fromData(u.data);ke(e.sessionId,\"srtp profiles\",g.profiles);const S=Je.findMatchingSRTPProfile(g.profiles,e.options?.srtpProfiles);if(!S){throw new Error}s.srtpProfile=S;ke(e.sessionId,\"srtp profile selected\",s.srtpProfile)}break;case Oe.type:{e.remoteExtendedMasterSecret=true}break;case Ue.type:{ke(e.sessionId,\"RenegotiationIndication\",u.data)}break;case 43:{const g=u.data.subarray(1);const S=[...g].map(p=>p.toString(10));ke(\"dtls supported version\",S)}break}});t.localRandom=new ne;t.remoteRandom=ne.from(i.random);const n=i.cipherSuites;ke(e.sessionId,\"cipher suites\",n);const o=(()=>{switch(t.signatureHashAlgorithm?.signature){case ce.ecdsa_3:return dn.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case ce.rsa_1:return dn.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!n.includes(o)){throw new Error(\"dtls cipher suite negotiation failed\")}t.cipherSuite=o;ke(e.sessionId,\"selected cipherSuite\",t.cipherSuite);t.localKeyPair=In(t.namedCurve);e.cookie||=(0,_h.randomBytes)(20);const c=new Ns({major:255-1,minor:255-2},e.cookie);const d=Cn(e)([c]);const h=Ne(e)(d.map(u=>({type:H.handshake,fragment:u.serialize()})),++e.recordSequenceNumber);const l=h.map(u=>u.serialize());for(const u of l){r.send(u).catch(g=>ke(\"send failed\",g))}},\"flight2\");var ha=b(\"webrtc/dtls/flight/server/flight4:log\");var Dn=class extends me{static{a(this,\"Flight4\")}constructor(e,t,s,i){super(e,t,4,6);this.cipher=s;this.srtp=i}async exec(e,t=false){if(this.dtls.flight===4){ha(this.dtls.sessionId,\"flight4 twice\");this.send(this.dtls.lastMessage).catch(i=>ha(\"send failed\",i));return}this.dtls.flight=4;this.dtls.sequenceNumber=1;this.dtls.bufferHandshakeCache([e],false,4);const s=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(i=>i);this.dtls.lastMessage=s;await this.transmit(s)}sendServerHello(){const e=[];if(this.srtp.srtpProfile){e.push(ge.create([this.srtp.srtpProfile],Buffer.from([0])).extension)}if(this.dtls.options.extendedMasterSecret){e.push({type:Oe.type,data:Buffer.alloc(0)})}const t=Ue.createEmpty();e.push(t.extension);const s=new _s(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e);const i=this.createPacket([s]);return Buffer.concat(i.map(n=>n.serialize()))}sendCertificate(){const e=new Ze([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerKeyExchange(){const e=this.cipher.generateKeySignature(\"sha256\");if(!this.cipher.signatureHashAlgorithm)throw new Error(\"not exist\");const t=new Ls(un.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e);const s=this.createPacket([t]);return Buffer.concat(s.map(i=>i.serialize()))}sendCertificateRequest(){const e=new As(Dd,ln,[]);ha(this.dtls.sessionId,\"sendCertificateRequest\",e);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerHelloDone(){const e=new Bs;const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}};var Ht=b(\"webrtc/dtls/flight/server/flight6\");var Nn=class extends me{static{a(this,\"Flight6\")}constructor(e,t,s){super(e,t,6);this.cipher=s}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,5);const t=(()=>{switch(e.msg_type){case R.certificate_11:return Ze.deSerialize(e.fragment);case R.certificate_verify_15:return vs.deSerialize(e.fragment);case R.client_key_exchange_16:return Is.deSerialize(e.fragment);case R.finished_20:return Nt.deSerialize(e.fragment)}})();if(t){const s=Yr[t.msgType];if(!s){return}s({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){Ht(this.dtls.sessionId,\"flight6 twice\");this.send(this.dtls.lastMessage).catch(t=>Ht(\"send failed\",t));return}this.dtls.flight=6;const e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e;await this.transmit(e)}sendChangeCipherSpec(){const e=ks.createEmpty().serialize();const t=Ne(this.dtls)([{type:H.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Nt(t);this.dtls.epoch=1;const[i]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const n=this.cipher.encryptPacket(i).serialize();return n}};var Yr={};Yr[R.client_key_exchange_16]=({cipher:r,dtls:e})=>t=>{r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey};if(!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error(\"not exist\");const s=mn(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);Ht(e.sessionId,\"extendedMasterSecret\",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);const i=Buffer.concat(e.sortedHandshakeCache.map(n=>n.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?Sn(s,i):gn(s,r.remoteRandom.serialize(),r.localRandom.serialize());r.cipher=vn(r.cipherSuite);r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize());Ht(e.sessionId,\"setup cipher\",r.cipher.summary)};Yr[R.certificate_11]=({cipher:r,dtls:e})=>t=>{Ht(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Yr[R.certificate_verify_15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate){throw new Error(\"client certificate missing before certificate verify\")}Ht(e.sessionId,\"certificate_verify\",t.algorithm)};Yr[R.finished_20]=({dtls:r})=>e=>{Ht(r.sessionId,\"finished\",e)};var Os=b(\"webrtc/dtls/server:log\");var Qr=class extends Ut{static{a(this,\"DtlsServer\")}constructor(e){super(e,ie.SERVER);this.handleHandshakes=async t=>{Os(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case R.client_hello_1:{if(this.connected){this.renegotiation()}const i=Rs.deSerialize(s.fragment);if(i.cookie.length===0){Os(this.dtls.sessionId,\"send flight2\");Bh(this.transport,this.dtls,this.cipher,this.srtp)(i)}else if(this.dtls.cookie&&i.cookie.equals(this.dtls.cookie)){Os(this.dtls.sessionId,\"send flight4\");await new Dn(this.transport,this.dtls,this.cipher,this.srtp).exec(s,this.options.certificateRequest)}else{Os(\"wrong state\",{dtlsCookie:this.dtls.cookie?.toString(\"hex\").slice(10),helloCookie:i.cookie.toString(\"hex\").slice(10)})}}break;case R.certificate_11:case R.certificate_verify_15:case R.client_key_exchange_16:{if(this.connected)return;this.flight6=new Nn(this.transport,this.dtls,this.cipher);this.flight6.handleHandshake(s)}break;case R.finished_20:{await this.waitForReady(()=>!!this.flight6);this.flight6?.handleHandshake(s);const i=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(n=>typeof n===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(i));await this.flight6?.exec();this.connected=true;this.onConnect.execute();Os(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;Os(this.dtls.sessionId,\"start server\")}};var ua=2;var la=3;var Lh=0;var Us=50;var fa=51;var pa=53;var On=56;var Un=57;var ma=\"0.0.0.0\";var ga=9;var Mn={auto:\"actpass\",client:\"active\",server:\"passive\"};var Sa=Object.keys(Mn).reduce((r,e)=>{const t=Mn[e];r[t]=e;return r},{});var Dh=[\"apt\",\"max-fr\",\"max-fs\",\"maxplaybackrate\",\"minptime\",\"packetization-mode\",\"level-asymmetry-allowed\",\"stereo\",\"useinbandfec\"];var ya=[\"cname\",\"msid\",\"mslabel\",\"label\"];var Ta={SRTP_AES128_CM_HMAC_SHA1_80:ts,SRTP_AEAD_AES_128_GCM:ct};var zt=[\"sendonly\",\"sendrecv\"];var Nh=[\"sendrecv\",\"recvonly\"];var Hs=554869826;var Mh=8;var Oh=1398035790;var et=20;var wa=24;var ba=1;var Ca=2;var Uh=6;var Hh=50;var B;(function(r){r[r[\"REQUEST\"]=0]=\"REQUEST\";r[r[\"INDICATION\"]=16]=\"INDICATION\";r[r[\"RESPONSE\"]=256]=\"RESPONSE\";r[r[\"ERROR\"]=272]=\"ERROR\"})(B||(B={}));var Y;(function(r){r[r[\"BINDING\"]=1]=\"BINDING\";r[r[\"SHARED_SECRET\"]=2]=\"SHARED_SECRET\";r[r[\"ALLOCATE\"]=3]=\"ALLOCATE\";r[r[\"REFRESH\"]=4]=\"REFRESH\";r[r[\"SEND\"]=6]=\"SEND\";r[r[\"DATA\"]=7]=\"DATA\";r[r[\"CREATE_PERMISSION\"]=8]=\"CREATE_PERMISSION\";r[r[\"CHANNEL_BIND\"]=9]=\"CHANNEL_BIND\"})(Y||(Y={}));function zh(r){if(r.length<et){return false}if((r[0]&192)!==0){return false}if(r.readUInt32BE(4)!==Hs){return false}const e=r.readUInt16BE(2);if(e%4!==0){return false}return r.length===et+e}a(zh,\"isStunMessage\");var qh=3e3;function Fh(r){const e=Buffer.alloc(2);e.writeUInt16BE(r.length,0);return Buffer.concat([e,r])}a(Fh,\"encodeTcpFrame\");function Kh(r){const e=[];let t=0;while(r.length-t>=2){const s=r.readUInt16BE(t);if(r.length-t<s+2){break}e.push(r.subarray(t+2,t+2+s));t+=2+s}return{frames:e,rest:r.subarray(t)}}a(Kh,\"splitTcpFrames\");var $n=require(\"node:net\");var ei=require(\"node:crypto\");var zs=require(\"node:net\");function Ea(r){if((0,zs.isIPv4)(r)){const i=Buffer.allocUnsafe(4);const n=r.split(\".\");for(let o=0;o<4;o++){i[o]=Number(n[o])&255}return i}if(!(0,zs.isIPv6)(r)){throw new Error(`Invalid ip address: ${r}`)}const e=r.split(\":\",8);for(let i=0;i<e.length;i++){let n;if((0,zs.isIPv4)(e[i])){n=Ea(e[i]);e[i]=n.subarray(0,2).toString(\"hex\")}if(n&&++i<8){e.splice(i,0,n.subarray(2,4).toString(\"hex\"))}}if(e[0]===\"\"){while(e.length<8)e.unshift(\"0\")}else if(e[e.length-1]===\"\"){while(e.length<8)e.push(\"0\")}else if(e.length<8){let i=0;for(;i<e.length&&e[i]!==\"\";i++);const n=[];for(let o=9-e.length;o>0;o--){n.push(\"0\")}e.splice(i,1,...n)}const t=Buffer.allocUnsafe(16);let s=0;for(const i of e){const n=Number.parseInt(i,16)||0;t[s++]=n>>8&255;t[s++]=n&255}return t}a(Ea,\"ipAddressToBuffer\");function Ra(r){if(r.length===4){return`${r[0]}.${r[1]}.${r[2]}.${r[3]}`}if(r.length!==16){throw new Error(`Invalid ip address buffer length: ${r.length}`)}const e=[];for(let s=0;s<16;s+=2){e.push(r.readUInt16BE(s).toString(16))}let t=e.join(\":\");t=t.replace(/(^|:)0(:0)*:0(:|$)/,\"$1::$3\");t=t.replace(/:{3,4}/,\"::\");return t}a(Ra,\"bufferToIpAddress\");function Gh(r){return(0,zs.isIPv4)(r)}a(Gh,\"isIpV4Address\");function qt(r){const[e]=r;const t=Gh(e)?ba:Ca;const s=Buffer.alloc(4);s.writeUInt8(0,0);s.writeUInt8(t,1);s.writeUInt16BE(r[1],2);return Buffer.concat([s,Ea(e)])}a(qt,\"packAddress\");function yp(r){if(r.length<4){throw new Error(\"STUN error code is less than 4 bytes\")}const e=r.readUInt8(2);const t=r.readUInt8(3);const s=r.slice(4).toString(\"utf8\");return[e*100+t,s]}a(yp,\"unpackErrorCode\");function Ft(r){if(r.length<4){throw new Error(\"STUN address length is less than 4 bytes\")}const e=r.readUInt8(1);const t=r.readUInt16BE(2);const s=r.slice(4);switch(e){case ba:if(s.length!==4){throw new Error(\"STUN address has invalid length for IPv4\")}return[Ra(s),t];case Ca:if(s.length!==16){throw new Error(\"STUN address has invalid length for IPv6\")}return[Ra(s),t];default:throw new Error(\"STUN address has unknown protocol\")}}a(Ft,\"unpackAddress\");var xa=Buffer.alloc(6);xa.writeUInt16BE(Hs>>16,0);xa.writeUInt32BE(Hs,2);function $h(r,e){const t=[...xa,...e];let s=r.slice(0,2);for(let i=2;i<r.length;i++){const n=r[i]^t[i-2];const o=Buffer.alloc(1);o.writeUIntBE(n,0,1);s=Buffer.concat([s,o])}return s}a($h,\"xorAddress\");function Xr(r,e){return Ft($h(r,e))}a(Xr,\"unpackXorAddress\");function Tp(r){const e=Buffer.alloc(4);e.writeUInt16BE(0,0);e.writeUInt8(Math.floor(r[0]/100),2);e.writeUInt8(r[0]%100,3);const t=Buffer.from(r[1],\"utf8\");return Buffer.concat([e,t])}a(Tp,\"packErrorCode\");function wp(r){const e=Buffer.alloc(r.length*2);r.forEach((t,s)=>{e.writeUInt16BE(t,s*2)});return e}a(wp,\"packUnknownAttributes\");function bp(r){if(r.length%2!==0){throw new Error(\"UNKNOWN-ATTRIBUTES must have an even length\")}const e=[];for(let t=0;t<r.length;t+=2){e.push(r.readUInt16BE(t))}return e}a(bp,\"unpackUnknownAttributes\");function Jr(r,e){return $h(qt(r),e)}a(Jr,\"packXorAddress\");var qs=a(r=>{const e=Buffer.alloc(4);e.writeUInt32BE(r,0);return e},\"packUnsigned\");var Fs=a(r=>r.readUInt32BE(0),\"unpackUnsigned\");var Cp=a(r=>{const e=Buffer.alloc(4);e.writeUInt16BE(r,0);return e},\"packUnsignedShort\");var Ep=a(r=>r.readUInt16BE(0),\"unpackUnsignedShort\");var jh=a(r=>{const e=Buffer.allocUnsafe(8);e.writeBigUInt64BE(r,0);return e},\"packUnsigned64\");var Wh=a(r=>r.readBigUInt64BE(0),\"unpackUnsigned64\");var zn=a(r=>Buffer.from(r,\"utf8\"),\"packString\");var Hn=a(r=>r.toString(\"utf8\"),\"unpackString\");var Rp=a(r=>{if([...r].length>=128){throw new Error(\"SOFTWARE must be shorter than 128 characters\")}return zn(r)},\"packSoftware\");var tt=a(r=>r,\"packBytes\");var st=a(r=>r,\"unpackBytes\");var xp=a(()=>Buffer.alloc(0),\"packNone\");var kp=a(()=>null,\"unpackNone\");var Vh=[[1,\"MAPPED-ADDRESS\",qt,Ft],[3,\"CHANGE-REQUEST\",qs,Fs],[4,\"SOURCE-ADDRESS\",qt,Ft],[5,\"CHANGED-ADDRESS\",qt,Ft],[6,\"USERNAME\",zn,Hn],[8,\"MESSAGE-INTEGRITY\",tt,st],[9,\"ERROR-CODE\",Tp,yp],[10,\"UNKNOWN-ATTRIBUTES\",wp,bp],[12,\"CHANNEL-NUMBER\",Cp,Ep],[13,\"LIFETIME\",qs,Fs],[18,\"XOR-PEER-ADDRESS\",Jr,Xr],[19,\"DATA\",tt,st],[20,\"REALM\",zn,Hn],[21,\"NONCE\",tt,st],[22,\"XOR-RELAYED-ADDRESS\",Jr,Xr],[23,\"REQUESTED-ADDRESS-FAMILY\",qs,Fs],[24,\"EVEN-PORT\",tt,st],[25,\"REQUESTED-TRANSPORT\",qs,Fs],[28,\"MESSAGE-INTEGRITY-SHA256\",tt,st],[29,\"PASSWORD-ALGORITHM\",tt,st],[30,\"USERHASH\",tt,st],[32,\"XOR-MAPPED-ADDRESS\",Jr,Xr],[34,\"RESERVATION-TOKEN\",tt,st],[36,\"PRIORITY\",qs,Fs],[37,\"USE-CANDIDATE\",xp,kp],[32770,\"PASSWORD-ALGORITHMS\",tt,st],[32771,\"ALTERNATE-DOMAIN\",zn,Hn],[32802,\"SOFTWARE\",Rp,Hn],[32803,\"ALTERNATE-SERVER\",qt,Ft],[32808,\"FINGERPRINT\",qs,Fs],[32809,\"ICE-CONTROLLED\",jh,Wh],[32810,\"ICE-CONTROLLING\",jh,Wh],[32811,\"RESPONSE-ORIGIN\",qt,Ft],[32812,\"OTHER-ADDRESS\",qt,Ft]];var Zr=class{static{a(this,\"AttributeRepository\")}constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){const s=this.attributes.find(i=>i[0]===e);if(s){s[1]=t}else{this.attributes.push([e,t])}return this}getAttributeValue(e){const t=this.attributes.find(s=>s[0]===e);return t?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}removeAttribute(e){this.attributes=this.attributes.filter(t=>t[0]!==e);return this}clear(){this.attributes=[]}};var Yh=Vh.reduce((r,e)=>{r[e[0]]=e;return r},{});var Qh=Vh.reduce((r,e)=>{r[e[1]]=e;return r},{});function ve(r,e){if(!zh(r)){return void 0}const t=r.readUInt16BE(0);const s=Buffer.from(r.slice(et-12,et));const i=new Zr;const n=[];let o=false;for(let c=et;c<r.length;){if(c+4>r.length){return void 0}const d=r.readUInt16BE(c);const h=r.readUInt16BE(c+2);const l=c+4;const u=l+h;if(u>r.length){return void 0}const g=r.slice(l,u);const S=Ks(h);if(u+S>r.length){return void 0}const p=Yh[d];if(p){const[,f,,y]=p;let m;try{m=y.name===Xr.name?y(g,s):y(g)}catch{return void 0}i.setAttribute(f,m);if(f===\"FINGERPRINT\"){const T=Xh(r.slice(0,c));if(i.getAttributeValue(\"FINGERPRINT\")!==T){return void 0}}else if(f===\"MESSAGE-INTEGRITY\"&&e){const T=Ip(r.slice(0,c),e);const C=i.getAttributeValue(\"MESSAGE-INTEGRITY\");if(!T.equals(C)){return void 0}o=true}}else{n.push({type:d,length:h,value:Buffer.from(g)})}c=u+S}if(e&&!o){return void 0}return new Q(t&16111,t&272,s,i.getAttributes(),n)}a(ve,\"parseMessage\");var Q=class extends Zr{static{a(this,\"Message\")}constructor(e,t,s=(0,ei.randomBytes)(12),i=[],n=[]){super(i);this.messageMethod=e;this.messageClass=t;this.transactionId=s;this.rawAttributes=n}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(\"hex\")}appendRawAttribute(e,t){this.rawAttributes.push({type:e,value:Buffer.from(t)});return this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){const e=Buffer.concat(this.serializedAttributes.map(s=>vp(s.type,s.value)));const t=Buffer.alloc(8);t.writeUInt16BE(this.messageMethod|this.messageClass,0);t.writeUInt16BE(e.length,2);t.writeUInt32BE(Hs,4);return Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){this.removeAttribute(\"FINGERPRINT\").removeAttribute(\"MESSAGE-INTEGRITY\");this.setAttribute(\"MESSAGE-INTEGRITY\",this.messageIntegrity(e));return this}messageIntegrity(e){const t=ka(this.bytes,this.bytes.length-et+wa);return Buffer.from((0,ei.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}addFingerprint(){this.removeAttribute(\"FINGERPRINT\");this.setAttribute(\"FINGERPRINT\",Xh(this.bytes));return this}get serializedAttributes(){const e=[];for(const t of this.attributesKeys){const s=this.getAttributeValue(t);const[i,,n]=Qh[t];const o=n.name===Jr.name?n(s,this.transactionId):n(s);e.push({type:i,value:o})}e.push(...this.rawAttributes.map(t=>({type:t.type,value:Buffer.from(t.value)})));return e}};function vp(r,e){const t=e.length;const s=Ks(t);const i=Buffer.alloc(4);i.writeUInt16BE(r,0);i.writeUInt16BE(t,2);return Buffer.concat([i,e,Buffer.alloc(s)])}a(vp,\"serializeAttribute\");var ka=a((r,e)=>{const t=Buffer.alloc(r.length);r.copy(t,0,0,2);t.writeUInt16BE(e,2);r.copy(t,4,4);return t},\"setBodyLength\");function Xh(r){const e=ka(r,r.length-et+Mh);return(Ec(e)^Oh)>>>0}a(Xh,\"messageFingerprint\");function Ip(r,e){const t=ka(r,r.length-et+wa);return Buffer.from((0,ei.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}a(Ip,\"messageIntegrity\");function Ks(r){const e=r%4;return e===0?0:4-e}a(Ks,\"paddingLength\");var Zh=require(\"node:dns\");var va=require(\"node:net\");var qn=class extends Error{static{a(this,\"TransactionError\")}};var Gs=class extends qn{static{a(this,\"TransactionFailed\")}constructor(e,t){super();this.response=e;this.addr=t}get str(){let e=\"STUN transaction failed\";const t=this.response.getAttributeValue(\"ERROR-CODE\");if(t){const[s,i]=t;e+=` (${s} - ${i})`}return e}};var ti=class extends qn{static{a(this,\"TransactionTimeout\")}get str(){return\"STUN transaction timed out\"}};var Fn=class extends Error{static{a(this,\"AddressFamilyMismatch\")}constructor(e,t){super(`cannot reach ${e[0]}:${e[1]} from an IPv${t} socket`);this.addr=e;this.socketFamily=t}};var si=b(\"webrtc/ice/stun/transaction\");async function it(r,e=0){const t=(0,va.isIP)(r[0]);if(t){if(e!==0&&t!==e){throw new Fn(r,e)}return r}const s=await Zh.promises.lookup(r[0],{family:e});return[s.address,r[1]]}a(it,\"resolveRequestAddress\");function eu(r,e){if(r!==null&&typeof r===\"object\"){return r}const t=typeof r===\"number\"?r:void 0;return{retransmissions:t,onRequestSent:e}}a(eu,\"normalizeTransactionOptions\");function Ia(r,e){return r[1]===e[1]&&Jh(r[0])===Jh(e[0])}a(Ia,\"addressEquals\");function Jh(r){if((0,va.isIP)(r)!==6)return r;return new URL(`http://[${r.split(\"%\")[0]}]/`).hostname.slice(1,-1)}a(Jh,\"canonicalHost\");var rt=class{static{a(this,\"Transaction\")}constructor(e,t,s,i,n){this.request=e;this.addr=t;this.protocol=s;this.ended=false;this.tries=0;this.onResponse=new w;this.responseReceived=(c,d)=>{if(this.ended||this.onResponse.length===0){return}if(!Ia(this.expectedAddr,d)){si(\"ignore STUN response from unexpected address\",d,\"expected\",this.expectedAddr);return}if(this.integrityKey){const h=c.attributesKeys.includes(\"MESSAGE-INTEGRITY\")||c.attributesKeys.includes(\"MESSAGE-INTEGRITY-SHA256\");if(!h&&!Pa(c)){si(\"ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)\");return}}if(c.messageClass===B.RESPONSE){this.onResponse.execute(c,d);this.onResponse.complete()}else{this.onResponse.error(new Gs(c,d))}};this.run=async()=>{try{if(this.signal?.aborted){throw new ti}this.attachAbortListener();this.retry().catch(d=>{si(\"retry failed\",d)});const c=await this.onResponse.asPromise();return c}finally{this.cancel()}};this.retry=async()=>{while(this.tries<this.triesMax&&!this.ended){this.onRequestSent?.(this.tries);this.protocol.sendStun(this.request,this.addr).catch(c=>{si(\"send stun failed\",c);if(this.failOnSendError){this.fail(c)}});await this.wait(this.timeoutDelay);if(this.ended){break}this.timeoutDelay*=2;this.tries++}if(this.tries>=this.triesMax&&!this.ended){si(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);this.failWithTimeout()}};const o=eu(i,n);this.triesMax=1+(o.retransmissions??Uh);this.timeoutDelay=o.responseTimeout??Hh;this.onRequestSent=o.onRequestSent;this.signal=o.signal;this.failOnSendError=o.failOnSendError??false;this.expectedAddr=t;this.integrityKey=o.integrityKey}attachAbortListener(){if(!this.signal){return}this.onAbort=()=>{this.failWithTimeout()};this.signal.addEventListener(\"abort\",this.onAbort,{once:true})}failWithTimeout(){this.fail(new ti)}fail(e){if(this.ended){return}this.ended=true;this.clearWait();if(this.onResponse.length>0){this.onResponse.error(e)}}clearWait(){if(this.waitTimer!==void 0){clearTimeout(this.waitTimer);this.waitTimer=void 0}const e=this.waitResolve;this.waitResolve=void 0;e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t;this.waitTimer=setTimeout(()=>{this.waitTimer=void 0;this.waitResolve=void 0;t()},e)})}cancel(){this.ended=true;this.clearWait();if(this.signal&&this.onAbort){this.signal.removeEventListener(\"abort\",this.onAbort);this.onAbort=void 0}}};function Pa(r){if(r.messageClass!==B.ERROR||!r.getAttributeValue(\"NONCE\")){return false}const[e]=r.getAttributeValue(\"ERROR-CODE\")??[];return e===401||e===438}a(Pa,\"isChallenge\");function Kt(r,e,t){const s=eu(e,t);if(r&&!s.integrityKey){s.integrityKey=r}return s}a(Kt,\"buildTransactionOptions\");var Kn=b(\"webrtc/ice/stun/tcpProtocol\");function ri(r){return`${r[0]}:${r[1]}`}a(ri,\"socketKey\");function Pp(r){return r.destroyed||r.writableEnded}a(Pp,\"isSocketClosed\");function su(r){if(!r.remoteAddress||!r.remotePort){return}return[r.remoteAddress,r.remotePort]}a(su,\"addressFromSocket\");async function tu(r,e,t){return await new Promise((s,i)=>{const n=a(c=>{r.off(\"listening\",o);i(c)},\"onError\");const o=a(()=>{r.off(\"error\",n);s()},\"onListening\");r.once(\"error\",n);r.once(\"listening\",o);r.listen({host:e,port:t??0,exclusive:true})})}a(tu,\"waitForListening\");var Gn=class r{static{a(this,\"BaseTcpProtocol\")}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new w;this.onDataReceived=new w;this.onConnectionClosed=new w;this.sockets=new Map}static{this.type=\"tcp\"}rememberSocket(e){const t=e.remoteAddr;if(!t){return}this.sockets.set(ri(t),e)}forgetSocket(e){const t=e.remoteAddr;if(!t){return false}const s=ri(t);if(this.sockets.get(s)!==e){return false}this.sockets.delete(s);return true}getOpenSocket(e){const t=this.sockets.get(ri(e));if(!t){return}if(Pp(t.socket)){this.dropSocket(t);return}return t}dropSocket(e){e.socket.destroy();if(this.forgetSocket(e)&&e.remoteAddr){this.onConnectionClosed.execute(e.remoteAddr)}}registerSocket(e,t){const s={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};if(t){this.rememberSocket(s)}e.on(\"data\",i=>{s.buffer=Buffer.concat([s.buffer,i]);const{frames:n,rest:o}=Kh(s.buffer);s.buffer=o;const c=s.remoteAddr??su(e);if(!s.remoteAddr&&c){s.remoteAddr=c;this.rememberSocket(s)}if(!c){return}for(const d of n){if(d.length===0){continue}this.handleFrame(d,c)}});e.on(\"close\",()=>{if(this.forgetSocket(s)&&s.remoteAddr){this.onConnectionClosed.execute(s.remoteAddr)}});e.on(\"error\",i=>{Kn(\"tcp socket error\",i)});return s}handleFrame(e,t){try{const s=ve(e);if(!s){this.onDataReceived.execute(e);return}if((s.messageClass===B.RESPONSE||s.messageClass===B.ERROR)&&this.transactions[s.transactionIdHex]){const i=this.transactions[s.transactionIdHex];const n=i.integrityKey?ve(e,i.integrityKey):s;if(!n){Kn(\"STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}else if(s.messageClass===B.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Kn(\"tcp frame parse error\",s)}}async sendFrame(e,t){const s=await this.getSocket(t);try{await new Promise((i,n)=>{s.socket.write(Fh(e),o=>{if(o){n(o);return}i()})})}catch(i){Kn(\"tcp write failed\",t,i);this.dropSocket(s);throw i}}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,s,i,n){if(this.transactions[e.transactionIdHex]){throw new Error(\"already requested\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t);const c={failOnSendError:true,...Kt(s,i,n)};const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(const[t,s]of this.sockets.entries()){if(e&&t===ri(e)){continue}s.socket.destroy();this.sockets.delete(t)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.pruneForSelection();this.onRequestReceived.complete();this.onDataReceived.complete();this.onConnectionClosed.complete()}};var jn=class extends Gn{static{a(this,\"TcpActiveProtocol\")}constructor(){super(...arguments);this.pendingSockets=new Map}async connectionMade(e){this.localIp=e}async getSocket(e){const t=ri(e);const s=this.getOpenSocket(e);if(s){return s}const i=this.pendingSockets.get(t);if(i){return await i}const n=new Promise((o,c)=>{const d=(0,$n.connect)({host:e[0],port:e[1],localAddress:this.localIp});const h=this.registerSocket(d,e);const l=a(g=>{d.off(\"connect\",u);c(g)},\"onError\");const u=a(()=>{d.off(\"error\",l);o(h)},\"onConnect\");d.once(\"error\",l);d.once(\"connect\",u)});this.pendingSockets.set(t,n);try{return await n}finally{this.pendingSockets.delete(t)}}};var Wn=class extends Gn{static{a(this,\"TcpPassiveProtocol\")}constructor(){super(...arguments);this.server=(0,$n.createServer)(e=>{this.registerSocket(e,su(e))})}async connectionMade(e,t){this.localIp=e;if(t){let s;for(let i=t[0];i<=t[1];i++){try{await tu(this.server,e,i);return}catch(n){s=n}}throw s??new Error(\"tcp port not found\")}await tu(this.server,e)}async getSocket(e){const t=this.getOpenSocket(e);if(!t){throw new Error(\"tcp passive connection not established\")}return t}get listeningPort(){const e=this.server.address();if(!e||typeof e===\"string\"){throw new Error(\"tcp passive protocol is not listening\")}return e.port}async close(){await super.close();await new Promise(e=>{this.server.close(()=>e())})}};var Aa=b(\"webrtc/ice/stun/protocol\");var Gt=class r{static{a(this,\"StunProtocol\")}static{this.type=\"stun\"}get transactionsKeys(){return Object.keys(this.transactions)}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new w;this.onDataReceived=new w;this.connectionMade=async(e,t,s)=>{if(e){this.transport=await yt.init(\"udp4\",{portRange:t,interfaceAddresses:s})}else{this.transport=await yt.init(\"udp6\",{portRange:t,interfaceAddresses:s})}this.transport.onData=(i,n)=>{this.datagramReceived(i,n)}}}datagramReceived(e,t){try{const s=ve(e);if(!s){if(this.localCandidate){this.onDataReceived.execute(e)}return}if((s.messageClass===B.RESPONSE||s.messageClass===B.ERROR)&&this.transactionsKeys.includes(s.transactionIdHex)){const i=this.transactions[s.transactionIdHex];const n=i.integrityKey?ve(e,i.integrityKey):s;if(!n){Aa(\"STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}else if(s.messageClass===B.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Aa(\"datagramReceived error\",s)}}getExtraInfo(){const{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed){return}const s=e.bytes;await this.transport.send(s,t).catch(()=>{Aa(\"sendStun failed\",t,e)})}async sendData(e,t){if(this.transport.closed){return}await this.transport.send(e,t)}connectTo(e){this.transport?.connectTo(e)}disconnect(){this.transport?.disconnect()}async request(e,t,s,i,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error(\"already request ed\");if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t,this.transport.addressFamily);const c=Kt(s,i,n);const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}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()}};var uu=require(\"node:net\");var lu=require(\"node:timers/promises\");var ru=require(\"node:crypto\");function iu(r,e,t){return(0,ru.createHash)(\"md5\").update(Buffer.from([r,e,t].join(\":\"))).digest()}a(iu,\"makeTurnIntegrityKey\");var _a=require(\"node:crypto\");function js(r){return(0,_a.randomBytes)(r).toString(\"hex\").substring(0,r)}a(js,\"randomString\");function nu(){return(0,_a.randomBytes)(12)}a(nu,\"randomTransactionId\");var ii=class{static{a(this,\"PQueue\")}constructor(){this.queue=[];this.wait=new w}put(e){this.queue.push(e);if(this.queue.length===1){this.wait.execute(e)}}get(){const e=this.queue.shift();if(!e){return new Promise(t=>{this.wait.subscribe(s=>{void this.queue.shift();t(s)})})}return e}};var ni=a(r=>{let e;let t;const s=new Promise((n,o)=>{e=n;t=o});s.then(()=>{i.execute(void 0);i.complete()}).catch(n=>{i.execute(n??new Error);i.complete()});const i=new w;r(e,t,i).catch(()=>{});return{awaitable:s,resolve:e,reject:t}},\"cancelable\");function Vn(r){return r.length>=4&&(r[0]&192)===64}a(Vn,\"isChannelData\");function ou(r,e){const t=Buffer.alloc(4);t.writeUInt16BE(r,0);t.writeUInt16BE(e.length,2);return Buffer.concat([t,e])}a(ou,\"encodeChannelData\");function au(r){if(!Vn(r)||r.length<4){return void 0}const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);if(r.length<4+t){return void 0}return{channelNumber:e,data:r.subarray(4,4+t)}}a(au,\"decodeChannelData\");function cu(r){const e=Ks(r.length);return e>0?Buffer.concat([r,Buffer.alloc(e)]):r}a(cu,\"padTurnFrame\");function du(r){const e=[];let t=0;let s=false;while(r.length-t>=4){let i;if(Vn(r.subarray(t))){const n=r.readUInt16BE(t+2);i=4+n+Ks(n)}else if((r[t]&192)===0){if(r.length-t<20){break}const n=r.readUInt16BE(t+2);i=20+n+Ks(n)}else{s=true;break}if(r.length-t<i){break}e.push(r.subarray(t,t+i));t+=i}return{frames:e,malformed:s,rest:r.subarray(t)}}a(du,\"splitTurnTcpFrames\");var $=b(\"webrtc/ice/turn/protocol\");var Ap=500;var _p=1e3;var Bp=600;var Lp=285212672;function Yn(r){return r.type===\"tcp\"||r.type===\"tls\"}a(Yn,\"isStreamTransport\");function Dp(r){return r[0]}a(Dp,\"permissionKey\");function hu(r){return JSON.stringify(r)}a(hu,\"channelKey\");var Ba=class r{static{a(this,\"StunOverTurnProtocol\")}static{this.type=\"turn\"}constructor(e){this.turn=e;this.type=r.type;this.disposer=new Ii;this.onRequestReceived=new w;this.onDataReceived=new w;this.handleStunMessage=(t,s)=>{try{const i=ve(t);if(!i){this.onDataReceived.execute(t);return}if(i.messageClass===B.RESPONSE||i.messageClass===B.ERROR){const n=this.turn.transactions[i.transactionIdHex];if(n){const o=n.integrityKey?ve(t,n.integrityKey):i;if(!o){$(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(o,s)}}else if(i.messageClass===B.REQUEST){this.onRequestReceived.execute(i,s,t)}}catch(i){$(\"datagramReceived error\",i)}};e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}async request(e,t,s,i,n){if(this.turn.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t);const c=Kt(s,i,n);const d=new rt(e,o,this,c);this.turn.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){this.disposer.dispose();return this.turn.close()}};var La=class r{static{a(this,\"TurnProtocol\")}static{this.type=\"turn\"}constructor(e,t,s,i,n,o={}){this.server=e;this.username=t;this.password=s;this.lifetime=i;this.transport=n;this.options=o;this.type=r.type;this.onData=new w;this.onRequestReceived=new w;this.onDataReceived=new w;this.transactions={};this.expiresAt=0;this.channelNumber=16384;this.channelByAddr={};this.addrByChannel={};this.channelBindQueue=Promise.resolve();this.channelBindingByAddr=new Map;this.tcpBuffer=Buffer.alloc(0);this.permissionByAddr={};this.permissionQueue=Promise.resolve();this.creatingPermissionByAddr=new Map;this.refresh=c=>{this.refreshHandle=ni(async(d,h,l)=>{const u=new AbortController;l.once(()=>{u.abort()});while(!u.signal.aborted){const g=5/6*c*1e3;$(\"refresh delay\",g,{exp:c});try{await(0,lu.setTimeout)(g,void 0,{signal:u.signal})}catch(p){if(u.signal.aborted){return}throw p}if(u.signal.aborted){return}const S=new Q(Y.REFRESH,B.REQUEST);S.setAttribute(\"LIFETIME\",c);try{const[p]=await this.requestWithRetry(S,this.server,u.signal);c=p.getAttributeValue(\"LIFETIME\");$(\"refresh\",{exp:c});this.expiresAt=Date.now()+c*1e3}catch(p){if(u.signal.aborted){return}$(\"refresh error\",p)}}})};this.channelRefreshTime=this.options.channelRefreshTime??Ap}async connectionMade(){this.transport.onData=(i,n)=>{this.dataReceived(i,n)};const e=new Q(Y.ALLOCATE,B.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime).setAttribute(\"REQUESTED-TRANSPORT\",Lp);const[t]=await this.requestWithRetry(e,this.server).catch(i=>{$(\"connect error\",i);throw i});this.relayedAddress=t.getAttributeValue(\"XOR-RELAYED-ADDRESS\");this.mappedAddress=t.getAttributeValue(\"XOR-MAPPED-ADDRESS\");const s=t.getAttributeValue(\"LIFETIME\");$(\"connect\",this.relayedAddress,this.mappedAddress,{exp:s});this.expiresAt=Date.now()+s*1e3;this.refresh(s)}handleChannelData(e){const t=au(e);const s=t&&this.addrByChannel[t.channelNumber];if(s&&t){this.onData.execute(t.data,s)}}handleSTUNMessage(e,t){try{const s=ve(e);if(!s){throw new Error(\"not stun message\")}if(s.messageClass===B.RESPONSE||s.messageClass===B.ERROR){const i=this.transactions[s.transactionIdHex];if(i){const n=i.integrityKey&&!Pa(s)?ve(e,i.integrityKey):s;if(!n){$(\"TURN STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}}else if(s.messageClass===B.REQUEST){this.onData.execute(e,t)}if(s.getAttributeValue(\"DATA\")){const i=s.getAttributeValue(\"DATA\");const n=s.getAttributeValue(\"XOR-PEER-ADDRESS\")??t;this.onData.execute(i,n)}}catch(s){$(\"parse error\",e.toString())}}dataReceived(e,t){const s=a((i,n)=>{if(i.length>=4&&Vn(i)){this.handleChannelData(i)}else{this.handleSTUNMessage(i,n)}},\"datagramReceived\");if(Yn(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);const{frames:i,rest:n}=du(this.tcpBuffer);this.tcpBuffer=n;for(const o of i){s(o,t)}}else{s(e,t)}}async send(e,t){if(this.transport.closed){return}await this.transport.send(Yn(this.transport)?cu(e):e,t)}async createPermission(e){const t=new Q(Y.CREATE_PERMISSION,B.REQUEST);t.setAttribute(\"XOR-PEER-ADDRESS\",e).setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce);await this.requestWithRetry(t,this.server)}async request(e,t,s,i,n){if(this.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(this.integrityKey){e.setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint()}const o=await this.resolveRequestTarget(t);const c=Kt(this.integrityKey,i,n);const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.transactions[e.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(e){if(Yn(this.transport)||Ia(e,this.server)){return this.selectServerEndpoint()}return it(e,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){this.serverEndpointSelection??=this.resolveServerEndpoint().then(e=>{this.pinnedServerEndpoint=e;return e},e=>{this.serverEndpointSelection=void 0;throw e});return this.serverEndpointSelection}async resolveServerEndpoint(){const e=this.transport;if(!Yn(e)){return it(this.server,e.addressFamily??0)}if(e.remoteAddress){return e.remoteAddress}if(e instanceof cr||e instanceof dr){throw new Error(`${e.type} transport has no remote address`)}return it(this.server)}async requestWithRetry(e,t,s){let i,n;try{[i,n]=await this.request(e,t,void 0,{signal:s})}catch(o){if(o instanceof Gs==false){$(\"requestWithRetry error\",o);throw o}const[c]=o.response.getAttributeValue(\"ERROR-CODE\");const d=o.response.getAttributeValue(\"NONCE\");const h=o.response.getAttributeValue(\"REALM\");if((c===401&&h||c===438&&this.realm)&&d){$(\"retry with nonce\",c);this.nonce=d;if(c===401){this.realm=h}this.integrityKey=Op(this.username,this.realm,this.password);e.transactionId=nu();[i,n]=await this.request(e,this.server,void 0,{signal:s})}else{throw o}}return[i,n]}async sendData(e,t){let s;try{s=await this.getChannel(t)}catch(i){$(\"channelBind error; falling back to Send Indication\",i)}if(!s){await this.getPermission(t);const i=new Q(Y.SEND,B.INDICATION).setAttribute(\"DATA\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);await this.sendStun(i,await this.serverDestination());return}await this.send(ou(s.number,e),await this.serverDestination())}async getPermission(e){const t=Dp(e);if(this.permissionByAddr[t]){return}const s=this.creatingPermissionByAddr.get(t);if(s){return s}const i=this.permissionQueue.then(async()=>{if(this.permissionByAddr[t]){return}await this.createPermission(e);this.permissionByAddr[t]=true});this.permissionQueue=i.then(()=>void 0,()=>void 0);this.creatingPermissionByAddr.set(t,i);try{await i}catch(n){$(\"createPermission error\",n);throw n}finally{if(this.creatingPermissionByAddr.get(t)===i){this.creatingPermissionByAddr.delete(t)}}}async getChannel(e){const t=hu(e);const s=this.channelBindingByAddr.get(t);if(s){return s}const i=this.channelByAddr[t];const n=at(Date.now()/1e3);if(i&&i.refreshAt>n){return i}const o=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=o.then(()=>void 0,()=>void 0);this.channelBindingByAddr.set(t,o);try{return await o}catch(c){$(\"channelBind error\",c);throw c}finally{if(this.channelBindingByAddr.get(t)===o){this.channelBindingByAddr.delete(t)}}}async ensureChannel(e){const t=hu(e);const s=at(Date.now()/1e3);let i=this.channelByAddr[t];if(i&&i.refreshAt>s){return i}const n=!i;if(!i){i={number:this.channelNumber++,address:e,refreshAt:0};this.channelByAddr[t]=i;this.addrByChannel[i.number]=e}try{await this.channelBind(i.number,e);i.refreshAt=at(Date.now()/1e3)+this.channelRefreshTime;$(n?\"channelBind\":\"channelBind refresh\",i);return i}catch(o){if(n){delete this.channelByAddr[t];delete this.addrByChannel[i.number]}throw o}}async channelBind(e,t){const s=new Q(Y.CHANNEL_BIND,B.REQUEST);s.setAttribute(\"CHANNEL-NUMBER\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);const[i]=await this.requestWithRetry(s,this.server);if(i.messageMethod!==Y.CHANNEL_BIND){throw new Error(\"should be CHANNEL_BIND\")}}async sendStun(e,t){await this.send(e.bytes,t)}async refreshAllocation(){if(!this.expiresAt||this.transport.closed){return false}const e=new Q(Y.REFRESH,B.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime);try{const[t]=await this.requestWithRetry(e,this.server);this.expiresAt=Date.now()+t.getAttributeValue(\"LIFETIME\")*1e3;return true}catch(t){$(\"refresh failed\",t);this.expiresAt=0;return false}}async close(){this.refreshHandle?.resolve?.();if(this.expiresAt>Date.now()&&!this.transport.closed){this.expiresAt=0;const e=new Q(Y.REFRESH,B.REQUEST);e.setAttribute(\"LIFETIME\",0);await this.requestWithRetry(e,this.server,AbortSignal.timeout(_p)).catch(t=>{$(\"delete allocation\",t)})}await this.transport.close()}};function Np(r,e){const t=(0,uu.isIP)(r[0]);if(t===4||t===6){if(e&&e!==t){$(\"udpFamily ignored for IP literal TURN server\",{address:r,udpFamily:e,literalFamily:t})}return t===6?\"udp6\":\"udp4\"}return(e??4)===6?\"udp6\":\"udp4\"}a(Np,\"selectTurnUdpSocketType\");async function Mp({address:r,username:e,password:t},{lifetime:s,portRange:i,interfaceAddresses:n,ssl:o,tlsOptions:c,transport:d,connectTimeoutMs:h,udpFamily:l}={}){s??=Bp;d??=o?\"tls\":\"udp\";const u=d===\"udp\"?await yt.init(Np(r,l),{portRange:i,interfaceAddresses:n}):d===\"tcp\"?await cr.init(r,{connectTimeoutMs:h}):await dr.init(r,c,{connectTimeoutMs:h});const g=new La(r,e,t,s,u);try{await g.connectionMade()}catch(S){try{await g.close()}catch(p){$(\"failed to close TURN client after allocation failure\",p)}throw S}return g}a(Mp,\"createTurnClient\");async function fu(r,e={}){const t=await Mp(r,e);const s=new Ba(t);return s}a(fu,\"createStunOverTurnClient\");function Op(r,e,t){return iu(r,e,t)}a(Op,\"makeIntegrityKey\");var oi=require(\"node:crypto\");var Da=require(\"node:net\");var te=class r{static{a(this,\"Candidate\")}constructor(e,t,s,i,n,o,c,d,h,l,u,g){this.foundation=e;this.component=t;this.transport=s;this.priority=i;this.host=n;this.port=o;this.type=c;this.relatedAddress=d;this.relatedPort=h;this.tcptype=l;this.generation=u;this.ufrag=g;this.id=(0,oi.randomUUID)().toString()}refreshId(){this.id=(0,oi.randomUUID)().toString()}static fromSdp(e){const t=e.split(\" \");if(t.length<8){throw new Error(\"SDP does not have enough properties\")}const s={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let u=8,g=t.length-1;u<g;u+=2){if(t[u]===\"raddr\"){s[\"related_address\"]=t[u+1]}else if(t[u]===\"rport\"){s[\"related_port\"]=Number(t[u+1])}else if(t[u]===\"tcptype\"){s[\"tcptype\"]=t[u+1]}else if(t[u]===\"generation\"){s[\"generation\"]=Number(t[u+1])}else if(t[u]===\"ufrag\"){s[\"ufrag\"]=t[u+1]}}const{foundation:i,component:n,transport:o,priority:c,host:d,port:h,type:l}=s;return new r(i,n,o,c,d,h,l,s[\"related_address\"],s[\"related_port\"],s[\"tcptype\"],s[\"generation\"],s[\"ufrag\"])}canPairWith(e){const t=(0,Da.isIPv4)(this.host);const s=(0,Da.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&Fp(this,e)&&t===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)e+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=void 0)e+=` rport ${this.relatedPort}`;if(this.tcptype)e+=` tcptype ${this.tcptype}`;if(this.generation!=void 0)e+=` generation ${this.generation}`;if(this.ufrag!=void 0)e+=` ufrag ${this.ufrag}`;return e}};var Up={host:126,prflx:110,srflx:100,relay:0};var Hp={host:105,prflx:90,srflx:80,relay:0};var zp={active:6,passive:4,so:2};var qp={active:4,passive:2,so:6};function Qn(r){return r?.toLowerCase()??\"udp\"}a(Qn,\"normalizeTransport\");function Na(r){switch(r){case\"active\":case\"passive\":case\"so\":return r;default:return void 0}}a(Na,\"normalizeTcpType\");function Fp(r,e){if(Qn(r.transport)!==\"tcp\"){return true}const t=Na(r.tcptype);const s=Na(e.tcptype);if(!t||!s){return false}return t===\"active\"&&s===\"passive\"||t===\"passive\"&&s===\"active\"||t===\"so\"&&s===\"so\"}a(Fp,\"canPairTcpCandidates\");function Kp({candidateType:r,transport:e=\"udp\",tcptype:t,otherPreference:s=8191}){if(Qn(e)!==\"tcp\"){return s}const i=Na(t)??\"active\";const n=r===\"srflx\"||r===\"prflx\"?qp[i]:zp[i];return(1<<13)*n+s}a(Kp,\"candidateLocalPreference\");function Gp(r,e=\"udp\"){const t=Qn(e)===\"tcp\"?Hp:Up;return t[r]??0}a(Gp,\"candidateTypePreference\");function jt(r,e,t,s){const i=s===void 0?`${r}|${e}|${t}`:`${r}|${e}|${t}|${s}`;return(0,oi.createHash)(\"md5\").update(i,\"ascii\").digest(\"hex\").slice(7)}a(jt,\"candidateFoundation\");function lt(r,e=65535){const t=1;const s=typeof e===\"number\"?\"udp\":Qn(e.transport);const i=typeof e===\"number\"?e:e.localPreference??Kp({candidateType:r,transport:s,tcptype:e.tcptype,otherPreference:e.otherPreference});const n=Gp(r,s);return(1<<24)*n+(1<<8)*i+(256-t)}a(lt,\"candidatePriority\");function pu(r){switch(r){case\"passive\":return\"active\";case\"active\":return\"passive\";default:return\"so\"}}a(pu,\"remoteTcpTypeForIncoming\");var Bu=require(\"node:crypto\");var Ua=require(\"node:net\");var Lu=bi(require(\"node:timers/promises\"),1);var yu=require(\"node:dgram\");var Tu=require(\"node:events\");var mu=\"224.0.0.251\";var gu=5353;var ai={A:1,AAAA:28};function jp(r){const e=r.replace(/\\.$/,\"\").split(\".\").map(t=>{const s=Buffer.from(t,\"utf8\");return Buffer.concat([Buffer.from([s.length]),s])});return Buffer.concat([...e,Buffer.from([0])])}a(jp,\"encodeName\");function Su(r,e){const t=[];let s=e;let i=-1;for(let n=0;n<64;n++){const o=r[s];if(o===void 0)throw new Error(\"truncated name\");if(o===0){s++;break}if((o&192)===192){if(i<0)i=s+2;s=(o&63)<<8|r[s+1];continue}t.push(r.toString(\"utf8\",s+1,s+1+o));s+=1+o}return[t.join(\".\"),i<0?s:i]}a(Su,\"decodeName\");function Wp(r,e){if(r===ai.A&&e.length===4)return Array.from(e).join(\".\");if(r===ai.AAAA&&e.length===16){const t=[];for(let s=0;s<16;s+=2)t.push(e.readUInt16BE(s).toString(16));return t.join(\":\")}return e}a(Wp,\"formatAddress\");function $p(r){try{if(r.length<12||!(r[2]&128))return void 0;const e=r.readUInt16BE(4);const t=r.readUInt16BE(6)+r.readUInt16BE(8)+r.readUInt16BE(10);let s=12;for(let n=0;n<e;n++)s=Su(r,s)[1]+4;const i=[];for(let n=0;n<t;n++){const[o,c]=Su(r,s);const d=r.readUInt16BE(c);const h=r.readUInt32BE(c+4);const l=r.readUInt16BE(c+8);const u=r.subarray(c+10,c+10+l);s=c+10+l;const g=d===ai.A?\"A\":d===ai.AAAA?\"AAAA\":void 0;i.push({name:o,type:g??d,ttl:h,data:Wp(d,u)})}return i}catch{return void 0}}a($p,\"parseMdnsResponse\");function Vp(r,e){const t=Buffer.alloc(12);t.writeUInt16BE(1,4);const s=Buffer.alloc(4);s.writeUInt16BE(ai[e],0);s.writeUInt16BE(1,2);return Buffer.concat([t,jp(r),s])}a(Vp,\"encodeMdnsQuery\");var Xn=class extends Tu.EventEmitter{static{a(this,\"MulticastDns\")}#e;#t;constructor(){super();this.#e=(0,yu.createSocket)({type:\"udp4\",reuseAddr:true});this.#e.on(\"error\",e=>void this.emit(\"error\",e));this.#e.on(\"message\",(e,t)=>{const s=$p(e);if(s?.length)this.emit(\"response\",s,t)});this.#t=new Promise(e=>{this.#e.bind(gu,()=>{try{this.#e.addMembership(mu);this.#e.setMulticastTTL(255);this.#e.setMulticastLoopback(true)}catch(t){this.emit(\"error\",t)}e()})})}async query(e,t=\"A\"){await this.#t;await new Promise((s,i)=>{this.#e.send(Vp(e,t),gu,mu,n=>n?i(n):s())})}destroy(){try{this.#e.close()}catch{}}};var Jn=class{static{a(this,\"MdnsLookup\")}constructor(){this.cache=new Map;this.mdnsInstance=new Xn;this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,s)=>{const i=a(()=>{this.mdnsInstance.removeListener(\"response\",o);clearTimeout(n)},\"cleanup\");const n=setTimeout(()=>{i();s(new Error(\"No mDNS response\"))},1e4);const o=a(c=>{const d=c.find(h=>h.type===\"A\"&&h.name.toLowerCase()===e.toLowerCase());if(!d){return}i();t(d.data)},\"l\");this.mdnsInstance.on(\"response\",o);this.mdnsInstance.query(e,\"A\").catch(c=>{i();s(c)})})}close(){this.mdnsInstance.destroy()}};var wu=require(\"node:crypto\");var Yp=b(\"webrtc/ice/iceBase:log\");var ci=class{static{a(this,\"CandidatePair\")}get state(){return this._state}toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}constructor(e,t,s){this.protocol=e;this.remoteCandidate=t;this.iceControlling=s;this.id=(0,wu.randomUUID)().toString();this.nominated=false;this.remoteNominated=false;this._state=L.FROZEN;this.packetsSent=0;this.packetsReceived=0;this.bytesSent=0;this.bytesReceived=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.requestsReceived=0;this.requestsSent=0;this.responsesReceived=0;this.responsesSent=0;this.retransmissionsReceived=0;this.retransmissionsSent=0;this.consentRequestsSent=0;this.requestTransactionIds=new Set}updateState(e){this._state=e}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 Ma(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){const t=this.requestTransactionIds.has(e);if(!t){this.requestTransactionIds.add(e);return false}this.retransmissionsReceived++;return true}};var di=1;var Ws=2;var bu=5;var Cu=30;var Qp=1e3;var Xp=500;function Eu(r){if(r===void 0||!Number.isFinite(r)||r<=0){return Qp}return Math.max(Xp,Math.round(r*1e3*2+200))}a(Eu,\"consentResponseTimeoutMs\");var L;(function(r){r[r[\"FROZEN\"]=0]=\"FROZEN\";r[r[\"WAITING\"]=1]=\"WAITING\";r[r[\"IN_PROGRESS\"]=2]=\"IN_PROGRESS\";r[r[\"SUCCEEDED\"]=3]=\"SUCCEEDED\";r[r[\"FAILED\"]=4]=\"FAILED\"})(L||(L={}));var Ru={iceLite:false,useTcp:false,useIpv4:true,useIpv6:true};function Oa(r){if(![\"host\",\"relay\",\"srflx\"].includes(r.type))throw new Error(`Unexpected candidate type \"${r.type}\"`);return r}a(Oa,\"validateRemoteCandidate\");function xu(r,e){return r.sort((t,s)=>Ma(t.localCandidate,t.remoteCandidate,e)-Ma(s.localCandidate,s.remoteCandidate,e)).reverse()}a(xu,\"sortCandidatePairs\");function Ma(r,e,t){const s=t&&r.priority||e.priority;const i=t&&e.priority||r.priority;return(1<<32)*Math.min(s,i)+2*Math.max(s,i)+(s>i?1:0)}a(Ma,\"candidatePairPriority\");async function ku(r,e){const t=new Q(Y.BINDING,B.REQUEST);try{const[s]=await r.request(t,e);const i=r.localCandidate;if(!i){throw new Error(\"not exist\")}const n=new te(jt(\"srflx\",i.transport,i.host,e[0]),i.component,i.transport,lt(\"srflx\",{transport:i.transport,tcptype:i.tcptype}),s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[0],s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[1],\"srflx\",i.host,i.port,i.tcptype);return n}catch(s){Yp(\"error serverReflexiveCandidate\",s)}}a(ku,\"serverReflexiveCandidate\");function Zn(r){if(r&&Number.isNaN(r[1])){return[r[0],443]}return r}a(Zn,\"validateAddress\");var Pu=bi(require(\"node:os\"),1);function vu(r,e,t={},s){const i=[\"ipsec\",\"tun\",\"utun\",\"tap\"];const n=[\"vmnet\",\"veth\"];const{useLinkLocalAddress:o}=t;const c=Object.keys(r).map(d=>{for(const l of[...i,...n]){if(d.startsWith(l)){return{nic:d,addresses:[]}}}const h=(r[d]??[]).filter(l=>St(l.family)===e&&!l.internal&&(o?true:!s(l)));return{nic:d,addresses:h.map(l=>l.address)}}).filter(d=>!!d);c.sort((d,h)=>d.nic.localeCompare(h.nic));return Object.values(c).flatMap(d=>d.addresses)}a(vu,\"selectAddressesFromInterfaces\");var Jp=b(\"webrtc/ice/utils\");function Zp(r){return St(r.family)===4&&r.address?.startsWith(\"169.254.\")||St(r.family)===6&&r.address?.startsWith(\"fe80::\")}a(Zp,\"isLinkLocalAddress\");function Iu(r,{useLinkLocalAddress:e}={}){const t=Pu.networkInterfaces();Jp(t);return vu(t,r,{useLinkLocalAddress:e},Zp)}a(Iu,\"nodeIpAddress\");function Au(r,e,t={}){const s=[];if(r){s.push(...Iu(4,t))}if(e){s.push(...Iu(6,t))}return s}a(Au,\"getHostAddresses\");var I=b(\"webrtc/ice/ice:log\");var em=1e3;var tm=3e4;var sm={udp:65535,tcp:49151,tls:32767};function rm(r){const e=[];if(r.turnServer&&r.turnUsername&&r.turnPassword){e.push({address:r.turnServer,username:r.turnUsername,password:r.turnPassword,transport:r.turnTransport})}e.push(...r.turnServers??[]);const t=new Map;for(const s of e){const i=Zn(s.address);if(!i||!s.username||!s.password)continue;const n=i[0].toLowerCase();let o=t.get(n);if(!o){o={key:n,attempts:[]};t.set(n,o)}const c=s.transport===void 0||s.transport===\"udp\"?[\"udp\",\"tcp\"]:[s.transport];for(const d of c){const h=o.attempts.some(l=>l.transport===d&&l.address[1]===i[1]&&l.username===s.username&&l.password===s.password);if(!h)o.attempts.push({address:i,transport:d,username:s.username,password:s.password})}}return[...t.values()]}a(rm,\"relayServersOf\");function im(r){const e=[];for(const t of[r.stunServer,...r.stunServers??[]]){const s=Zn(t);if(s&&!e.some(([i,n])=>i===s[0]&&n===s[1]))e.push(s)}return e}a(im,\"stunServersOf\");var eo=class{static{a(this,\"Connection\")}constructor(e,t){this._iceControlling=e;this.localUsername=js(4);this.localPassword=js(22);this.remoteIsLite=false;this.remotePassword=\"\";this.remoteUsername=\"\";this.checkList=[];this.localCandidates=[];this.stunServers=[];this.relayServers=[];this.relays=new Map;this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.generation=-1;this.userHistory={};this.tieBreaker=(0,Bu.randomBytes)(8).readBigUInt64BE(0);this.state=\"new\";this._remoteCandidates=[];this.nominating=false;this.checkListDone=false;this.checkListState=new ii;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;this.protocols=[];this.consentFresh=false;this.consentSessionId=0;this.resolvingRemoteCandidates=0;this.noPairDeadline=0;this.onData=new w;this.stateChanged=new w;this.onIceCandidate=new w;this.queryConsent=()=>{if(this.iceLite){return}this.stopConsentLifecycle();const s=this.consentSessionId;this.consentFresh=true;const i=ni(async(n,o,c)=>{let d=false;const h=new AbortController;const l=a(()=>{if(this.consentExpiryTimer===void 0){return}clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0},\"clearConsentExpiry\");const u=a(()=>{if(d||s!==this.consentSessionId){return}l();this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0;if(d||s!==this.consentSessionId){return}if(this.state===\"closed\"||this.state===\"failed\"){return}I(\"Consent to send expired\");this.consentFresh=false;this.consentSessionId++;this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;if(this.queryConsentHandle===i){this.queryConsentHandle=void 0}d=true;h.abort();this.setState(\"failed\")},Cu*1e3)},\"refreshConsentExpiry\");c.once(()=>{d=true;if(s===this.consentSessionId){l();this.consentRequestAbort?.abort();this.consentRequestAbort=void 0}h.abort();if(this.queryConsentHandle===i){this.queryConsentHandle=void 0}});u();const g=a(()=>bu*(.8+.4*Math.random())*1e3,\"randomizedConsentInterval\");let S=Date.now()+g();const p=a(()=>this.state===\"closed\"||this.state===\"failed\",\"isTerminalState\");try{while(!p()&&!d&&s===this.consentSessionId){await this.abortableDelay(Math.max(0,S-Date.now()),h.signal);if(d||p()||s!==this.consentSessionId){break}S=Date.now()+g();const f=this.nominated;if(!f){break}const y=f.id;const m=this.generation;const T=this.remotePassword;const{localUsername:C,remoteUsername:E,iceControlling:P}=this;const de=this.buildRequest({nominate:this.shouldNominateConsentRequest(f),localUsername:C,remoteUsername:E,iceControlling:P,localCandidate:f.localCandidate});this.consentRequestAbort?.abort();const q=new AbortController;this.consentRequestAbort=q;f.consentRequestsSent++;f.requestsSent++;const pt=Eu(f.rtt);const mt=performance.now();f.protocol.request(de,f.remoteAddr,Buffer.from(T,\"utf8\"),{retransmissions:0,responseTimeout:pt,signal:q.signal,onRequestSent:a(He=>{if(He>0){f.retransmissionsSent++}},\"onRequestSent\")}).then(()=>{if(s!==this.consentSessionId||d){return}const He=this.state;if(He===\"closed\"||He===\"failed\"){return}if(this.nominated?.id!==y){return}if(this.generation!==m){return}if(this.remotePassword!==T){return}const Sc=(performance.now()-mt)/1e3;f.rtt=Sc;f.totalRoundTripTime+=Sc;f.roundTripTimeMeasurements++;f.responsesReceived++;this.consentFresh=true;u();if(He===\"disconnected\"){this.setState(\"connected\")}}).catch(He=>{if(s===this.consentSessionId&&this.nominated?.id===y){I(\"no stun response\",He)}})}}catch(f){}finally{if(s===this.consentSessionId){l()}}});this.queryConsentHandle=i};this.send=async s=>{if(!this.canSendApplicationData()){return}const i=this.nominated;await i.protocol.sendData(s,i.remoteAddr);i.packetsSent++;i.bytesSent+=s.length};this.checkStart=s=>ni(async i=>{I(\"check start\",s.toJSON());s.updateState(L.IN_PROGRESS);const n={};const{remotePassword:o,remoteUsername:c,generation:d}=this;const h=s.localCandidate.ufrag??this.localUsername;const l=false;const u=this.buildRequest({nominate:l,localUsername:h,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});const g=performance.now();try{s.requestsSent++;const[S,p]=await s.protocol.request(u,s.remoteAddr,Buffer.from(o,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++;const f=performance.now();const y=(f-g)/1e3;s.rtt=y;s.totalRoundTripTime+=y;s.roundTripTimeMeasurements++;I(\"response received\",u.toJSON(),S.toJSON(),p,{localUsername:h,remoteUsername:c,remotePassword:o,generation:d,rtt:y});n.response=S;n.addr=p}catch(S){const p=S;I(\"failure case\",u.toJSON(),p.response?JSON.stringify(p.response.toJSON(),null,2):S,{localUsername:h,remoteUsername:c,remotePassword:o,generation:d},s.remoteAddr);if(p.response?.getAttributeValue(\"ERROR-CODE\")[0]===487){if(u.attributesKeys.includes(\"ICE-CONTROLLED\")){this.switchRole(true)}else if(u.attributesKeys.includes(\"ICE-CONTROLLING\")){this.switchRole(false)}await this.checkStart(s).awaitable;i();return}if(p.response?.getAttributeValue(\"ERROR-CODE\")[0]===401){I(\"retry 401\",s.toJSON());await this.checkStart(s).awaitable;i();return}else{I(\"checkStart CandidatePairState.FAILED\",s.toJSON());s.updateState(L.FAILED);this.checkComplete(s);i();return}}if(n.addr[0]!==s.remoteAddr[0]||n.addr[1]!==s.remoteAddr[1]){s.updateState(L.FAILED);this.checkComplete(s);i();return}if(l||s.remoteNominated){s.nominated=true}else if(this.usesTcpRegularNomination(s)){}else if(this.iceControlling&&!this.nominating&&!this.nominated){this.nominating=true;const S=this.buildRequest({nominate:true,localUsername:h,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});try{s.requestsSent++;await s.protocol.request(S,s.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++}catch(p){this.nominating=false;s.updateState(L.FAILED);this.checkComplete(s);return}s.nominated=true}s.updateState(L.SUCCEEDED);this.checkComplete(s);i()});this.pairRemoteCandidate=s=>{for(const i of this.protocols){this.tryPair(i,s)}};this.options={...Ru,...t};if(this.iceLite){this._iceControlling=false}this.applyStunTurnServersFromOptions();this.restart().catch(s=>I(\"restart failed\",s));I(\"new Connection\",this.options)}setIceServers(e){this.options={...this.options,stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:e.turnTransport,stunServers:e.stunServers,turnServers:e.turnServers};if(e.forceTurn!==void 0){this.options.forceTurn=e.forceTurn}if(e.useTcp!==void 0){this.options.useTcp=e.useTcp}if(e.turnTlsOptions!==void 0){this.options.turnTlsOptions=e.turnTlsOptions}if(e.turnUdpFamily!==void 0){this.options.turnUdpFamily=e.turnUdpFamily}this.applyStunTurnServersFromOptions();I(\"Connection ice servers updated\",this.options)}applyStunTurnServersFromOptions(){this.stunServers=im(this.options);this.relayServers=rm(this.options);this.stunServer=this.stunServers[0];this.turnServer=Zn(this.options.turnServer)??this.relayServers[0]?.attempts[0]?.address}get iceControlling(){return this._iceControlling}set iceControlling(e){if(this.iceLite){e=false}if(this.nominated){return}this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++;this.localUsername=js(4);this.localPassword=js(22);if(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=false;this.localCandidatesEnd=false;this.state=\"new\";this.lookup?.close?.();this.lookup=void 0;this.nominated=void 0;this.nominating=false;this.checkList=[];this.checkListDone=false;this.checkListState=new ii;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;for(const e of this.protocols){e.disconnect?.();if(e.localCandidate){e.localCandidate.refreshId();e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername}}this.stopConsentLifecycle()}resetNominatedPair(){I(\"resetNominatedPair\");for(const e of this.protocols)e.disconnect?.();this.nominated=void 0;this.nominating=false;this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:s}){I(\"setRemoteParams\",{iceLite:e,usernameFragment:t,password:s});this.remoteIsLite=e;this.remoteUsername=t;this.remotePassword=s}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=true;const e=[...this.relays.values()];for(const n of this.protocols){if(n.localCandidate&&!e.includes(n)){n.localCandidate.generation=this.generation;n.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(n.localCandidate)}}let t=Au(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress});const{interfaceAddresses:s}=this.options;if(s){const n=t.filter(o=>Object.values(s).includes(o));if(n.length){t=n}}if(this.options.additionalHostAddresses){t=Array.from(new Set([...this.options.additionalHostAddresses,...t]))}const i=this.getCandidatePromises(t,this.options.stunGatherTimeout);await Promise.allSettled(i);this.localCandidatesEnd=true}this.setState(\"completed\")}appendLocalCandidate(e){this.localCandidates.push(e);this.onIceCandidate.execute(e)}isRedundant(e){const t=a(s=>s.type===\"host\"?`${s.host}|${s.port}`:`${s.relatedAddress}|${s.relatedPort}`,\"baseOf\");return this.localCandidates.some(s=>s.transport===e.transport&&s.host===e.host&&s.port===e.port&&s.type!==\"relay\"&&t(s)===t(e))}gatherRelayCandidates(e){for(const[t,s]of this.relays){if(!e.some(i=>i.key===t))this.dropRelay(t,s)}return e.map(async t=>{const s=this.relays.get(t.key);if(s){if(await s.turn.refreshAllocation()){if(this.relays.get(t.key)!==s)return;s.localCandidate.generation=this.generation;s.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(s.localCandidate);return s.localCandidate}this.dropRelay(t.key,s)}const{protocol:i,attempt:n}=await this.allocateRelay(t);if(this.state===\"closed\"||this.relays.has(t.key)){await i.close();return}this.ensureProtocol(i);this.protocols.push(i);this.relays.set(t.key,i);const o=i.turn.relayedAddress;const c=i.turn.mappedAddress;I(\"turn candidateAddress\",o);i.localCandidate=new te(jt(\"relay\",\"udp\",o[0],`${t.key}|${n.transport}`),1,\"udp\",lt(\"relay\",sm[n.transport]),o[0],o[1],\"relay\",c[0],c[1],void 0,this.generation,this.localUsername);this.appendLocalCandidate(i.localCandidate);return i.localCandidate}).map(t=>t.catch(s=>{I(\"query TURN server\",s)}))}allocateRelay(e){return new Promise((t,s)=>{let i=0;let n=0;let o=false;let c;const d=a(()=>{clearTimeout(c);if(o||i>=e.attempts.length)return;const h=e.attempts[i++];n++;c=setTimeout(d,em);fu({address:h.address,username:h.username,password:h.password},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:h.transport,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3,udpFamily:this.options.turnUdpFamily}).then(l=>{n--;if(o){l.close().catch(u=>I(\"close TURN relay\",u));return}o=true;clearTimeout(c);t({protocol:l,attempt:h})},l=>{n--;I(\"TURN allocation failed\",h.transport,h.address,l);if(o)return;if(i<e.attempts.length){d()}else if(!n){o=true;s(l)}})},\"start\");d()})}dropRelay(e,t){this.relays.delete(e);this.protocols=this.protocols.filter(s=>s!==t);t.close().catch(s=>I(\"close TURN relay\",s))}ensureProtocol(e){e.onRequestReceived.subscribe((t,s)=>{if(t.messageMethod!==Y.BINDING){this.respondError(t,s,e,[400,\"Bad Request\"]);return}const i=t.getAttributeValue(\"USERNAME\");const{remoteUsername:n}=_u(i);const o=this.userHistory[n]??this.localPassword;const{iceControlling:c}=this;if(c&&t.attributesKeys.includes(\"ICE-CONTROLLING\")){if(this.tieBreaker>=t.getAttributeValue(\"ICE-CONTROLLING\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(false)}}else if(!c&&t.attributesKeys.includes(\"ICE-CONTROLLED\")){if(this.iceLite||this.tieBreaker<t.getAttributeValue(\"ICE-CONTROLLED\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(true);return}}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,s,e)){return}const d=new Q(Y.BINDING,B.RESPONSE,t.transactionId);d.setAttribute(\"XOR-MAPPED-ADDRESS\",s).addMessageIntegrity(Buffer.from(o,\"utf8\")).addFingerprint();e.sendStun(d,s).catch(h=>{I(\"sendStun error\",h)});if(this.checkList.length===0&&!this.earlyChecksDone){this.earlyChecks.push([t,s,e])}else{this.checkIncoming(t,s,e)}});e.onDataReceived.subscribe(t=>{try{const s=this.nominated;if(s&&s.protocol===e){s.packetsReceived++;s.bytesReceived+=t.length}this.onData.execute(t)}catch(s){I(\"dataReceived\",s)}});e.onConnectionClosed?.subscribe(t=>{this.handleConnectionClosed(e,t)})}handleConnectionClosed(e,t){const s=this.nominated;if(!s||s.protocol!==e||s.remoteAddr[0]!==t[0]||s.remoteAddr[1]!==t[1]){return}if(this.state===\"closed\"||this.state===\"failed\"){return}I(\"selected tcp connection closed\",s.toJSON());this.stopConsentLifecycle();this.setState(\"failed\")}getCandidatePromises(e,t=5){const s=[];const{stunServers:i,relayServers:n}=this;const o=this.iceLite;const c=!o&&this.options.forceTurn&&n.length>0;const d=this.protocols.filter(l=>l instanceof Gt&&!!l.localCandidate);e=e.filter(l=>{if(this.protocols.find(u=>u.localIp===l)){return false}return true});const h=c?[]:e.map(async l=>{const u=new Gt;this.ensureProtocol(u);try{await u.connectionMade((0,Ua.isIPv4)(l),this.options.portRange,this.options.interfaceAddresses);u.localIp=l;this.protocols.push(u);I(\"protocol\",u.localIp);const g=[l,u.getExtraInfo()[1]];u.localCandidate=new te(jt(\"host\",\"udp\",g[0]),1,\"udp\",lt(\"host\",{transport:\"udp\"}),g[0],g[1],\"host\",void 0,void 0,void 0,this.generation,this.localUsername);this.pairLocalProtocol(u);this.appendLocalCandidate(u.localCandidate);return u}catch(g){I(\"error protocol STUN\",g)}});if(!c){s.push(...h.map(l=>l.then(u=>u?.localCandidate)))}if(!c&&this.options.useTcp){const l=e.map(async u=>{if(this.options.tcpPassive!==false){const g=new Wn;this.ensureProtocol(g);await g.connectionMade(u,this.options.portRange);g.localIp=u;g.localCandidate=new te(jt(\"host\",\"tcp\",u),1,\"tcp\",lt(\"host\",{transport:\"tcp\",tcptype:\"passive\"}),u,g.listeningPort,\"host\",void 0,void 0,\"passive\",this.generation,this.localUsername);this.protocols.push(g);this.appendLocalCandidate(g.localCandidate)}if(!o){const g=new jn;this.ensureProtocol(g);await g.connectionMade(u);g.localIp=u;g.localCandidate=new te(jt(\"host\",\"tcp\",u),1,\"tcp\",lt(\"host\",{transport:\"tcp\",tcptype:\"active\"}),u,9,\"host\",void 0,void 0,\"active\",this.generation,this.localUsername);this.protocols.push(g);this.pairLocalProtocol(g);this.appendLocalCandidate(g.localCandidate)}});s.push(...l)}if(!o&&!c&&i.length){const l=[...d.map(g=>Promise.resolve(g)),...h];const u=l.flatMap(g=>i.map(async S=>{const p=await g;if(!p)return;const f=this.generation;const y=(async()=>{const C=p.localCandidate?.host;if(!C||!(0,Ua.isIPv4)(C))return;const E=await ku(p,S).catch(P=>{I(\"error\",P)});if(!E||f!==this.generation||this.isRedundant(E))return;E.generation=this.generation;E.ufrag=this.localUsername;this.appendLocalCandidate(E);return E})();let m;const T=new Promise((C,E)=>{m=setTimeout(()=>E(new Error(\"STUN query timeout\")),t*1e3)});return Promise.race([y,T]).finally(()=>clearTimeout(m)).catch(C=>{I(\"query STUN server\",C)})}));s.push(...u)}if(!o){s.push(...this.gatherRelayCandidates(n))}return s}async connect(){I(\"start connect ice\");if(!this.localCandidatesEnd){if(!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(const t of this.remoteCandidates){this.pairRemoteCandidate(t)}this.sortCheckList();if(!this.iceLite){this.unfreezeInitial()}I(\"earlyChecks\",this.localPassword,this.earlyChecks.length);for(const t of this.earlyChecks){this.checkIncoming(...t)}this.earlyChecks=[];this.earlyChecksDone=true;if(this.iceLite){if(!this.nominated){let t=Ws;while(!this.checkListDone&&this.state!==\"closed\"){t=await this.checkListState.get();I(\"checkListState\",t);if(t===di){break}}if(t!==di&&!this.nominated){throw new Error(\"ICE negotiation failed\")}}this.setState(\"connected\");return}this.noPairDeadline=Date.now()+tm;for(;;){if(this.state===\"closed\")break;if(!this.schedulingChecks())break;await Lu.setTimeout(20)}let e=Ws;while(this.checkList.length>0&&e===Ws&&this.state!==\"closed\"){e=await this.checkListState.get();I(\"checkListState\",e)}for(const t of this.checkList){t.handle?.resolve?.()}if(e!==di){throw new Error(\"ICE negotiation failed\")}this.queryConsent();this.setState(\"connected\")}unfreezeInitial(){const[e]=this.checkList;if(!e)return;if(e.state===L.FROZEN){e.updateState(L.WAITING)}const t=new Set(e.localCandidate.foundation);for(const s of this.checkList){if(s.component===e.component&&!t.has(s.localCandidate.foundation)&&s.state===L.FROZEN){s.updateState(L.WAITING);t.add(s.localCandidate.foundation)}}}schedulingChecks(){if(this.nominating&&!this.nominated)return true;{const e=this.checkList.filter(t=>{if(this.options.forceTurn&&t.protocol.type===Gt.type)return false;return true}).find(t=>t.state===L.WAITING);if(e){e.handle=this.checkStart(e);return true}}{const e=this.checkList.find(t=>t.state===L.FROZEN);if(e){e.handle=this.checkStart(e);return true}}if(!this.remoteCandidatesEnd||this.resolvingRemoteCandidates>0||!this.checkList.length&&Date.now()<this.noPairDeadline){return!this.checkListDone}return false}stopConsentLifecycle(){this.consentSessionId++;this.consentFresh=false;if(this.consentExpiryTimer!==void 0){clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0}this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;const e=this.queryConsentHandle;this.queryConsentHandle=void 0;e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){if(!this.nominated){return false}if(this.state===\"closed\"||this.state===\"failed\"){return false}if(this.iceLite){return true}return this.consentFresh}abortableDelay(e,t){return new Promise((s,i)=>{if(t.aborted){i(new DOMException(\"The operation was aborted\",\"AbortError\"));return}const n=setTimeout(()=>{t.removeEventListener(\"abort\",o);s()},e);const o=a(()=>{clearTimeout(n);i(new DOMException(\"The operation was aborted\",\"AbortError\"))},\"onAbort\");t.addEventListener(\"abort\",o,{once:true})})}async close(){this.setState(\"closed\");this.stopConsentLifecycle();if(this.checkList&&!this.checkListDone){this.checkListState.put(new Promise(t=>{t(Ws)}))}this.nominated=void 0;const e=this.protocols;this.protocols=[];this.relays.clear();await Promise.all(e.map(async t=>{await t.close?.()}));this.localCandidates=[];this.lookup?.close?.();this.lookup=void 0}setState(e){this.state=e;this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=true;return}if(e.host.includes(\".local\")){void this.resolveRemoteCandidate(e);return}this.addResolvedRemoteCandidate(e)}async resolveRemoteCandidate(e){const t=this.generation;this.resolvingRemoteCandidates++;try{if(!this.lookup){this.lookup=new Jn}e.host=await this.lookup.lookup(e.host)}catch{return}finally{this.resolvingRemoteCandidates--}if(t!==this.generation||this.state===\"closed\")return;this.addResolvedRemoteCandidate(e)}addResolvedRemoteCandidate(e){try{Oa(e)}catch(t){return}if(this._remoteCandidates.some(t=>t.host===e.host&&t.port===e.port&&t.component===e.component&&t.type===e.type&&t.transport.toLowerCase()===e.transport.toLowerCase())){return}I(\"addRemoteCandidate\",e);this._remoteCandidates.push(e);this.pairRemoteCandidate(e);this.sortCheckList()}getDefaultCandidate(){const e=this.localCandidates.sort((s,i)=>s.priority-i.priority);const[t]=e;return t}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw new Error(\"Cannot set remote candidates after end-of-candidates.\");this._remoteCandidates=[];for(const t of e){try{Oa(t)}catch(s){continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=true}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){xu(this.checkList,this.iceControlling)}findPair(e,t){const s=this.checkList.find(i=>i.protocol===e&&i.remoteCandidate===t);return s}applyIceControlling(e){this._iceControlling=e;for(const t of this.checkList){t.iceControlling=e}}switchRole(e){I(\"switch role\",e);if(this.iceLite){e=false}this.applyIceControlling(e);this.sortCheckList()}checkComplete(e){e.handle=void 0;if(e.state===L.SUCCEEDED){if(e.nominated&&(e.remoteCandidate.ufrag==void 0||e.remoteCandidate.ufrag===this.remoteUsername)&&this.nominated==void 0){I(\"nominated\",e.toJSON());this.nominated=e;this.nominating=false;this.pruneTcpConnections(e);e.protocol.connectTo?.(e.remoteAddr);if(!this.iceLite&&(this.state===\"connected\"||this.state===\"completed\")){this.queryConsent()}for(const t of this.checkList){if(t.component===e.component&&[L.WAITING,L.FROZEN].includes(t.state)){t.updateState(L.FAILED)}}}if(this.nominated){if(!this.checkListDone){I(\"ICE completed\");this.checkListState.put(new Promise(t=>t(di)));this.checkListDone=true}return}I(\"not completed\",e.toJSON());for(const t of this.checkList){if(t.localCandidate.foundation===e.localCandidate.foundation&&t.state===L.FROZEN){t.updateState(L.WAITING)}}}this.nominateTcpPairIfReady();if(this.nominating){return}{const t=[L.SUCCEEDED,L.FAILED];if(this.checkList.find(({state:s})=>!t.includes(s))){return}}if(!this.iceControlling){const t=L.SUCCEEDED;if(this.checkList.find(({state:s})=>s===t)){return}}if(!this.checkListDone){I(\"ICE failed\");this.checkListState.put(new Promise(t=>{t(Ws)}))}}isTcpPair(e){return e.localCandidate.transport.toLowerCase()===\"tcp\"}usesTcpRegularNomination(e){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(e)}checkRequestOptions(e){const t=a(s=>{if(s>0){e.retransmissionsSent++}},\"onRequestSent\");if(this.isTcpPair(e)){return{retransmissions:0,responseTimeout:qh,onRequestSent:t}}return{retransmissions:4,onRequestSent:t}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating){return}for(const e of this.checkList){if(!this.isTcpPair(e)){continue}if(e.state===L.SUCCEEDED){this.nominateTcpPair(e);return}if(e.state!==L.FAILED){return}}}nominateTcpPair(e){this.nominating=true;const{generation:t}=this;const s=this.buildRequest({nominate:true,localUsername:e.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:e.localCandidate});e.requestsSent++;e.protocol.request(s,e.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(e)).then(()=>{if(this.isStaleNomination(e,t)){return}e.responsesReceived++;e.nominated=true;this.nominating=false;this.checkComplete(e)},i=>{if(this.isStaleNomination(e,t)){return}I(\"tcp nomination failed\",e.toJSON(),i);this.nominating=false;e.updateState(L.FAILED);this.checkComplete(e)})}isStaleNomination(e,t){return this.state===\"closed\"||this.generation!==t||!this.checkList.includes(e)}addPair(e){this.checkList.push(e);this.sortCheckList()}checkIncoming(e,t,s){const i=e.getAttributeValue(\"USERNAME\");const{remoteUsername:n}=_u(i);let o;const[c,d]=t;for(const l of this.remoteCandidates){if(l.host===c&&l.port===d){o=l;break}}if(!o){o=new te(js(10),1,s.localCandidate?.transport??\"udp\",e.getAttributeValue(\"PRIORITY\"),c,d,\"prflx\",void 0,void 0,s.localCandidate?.transport===\"tcp\"?pu(s.localCandidate.tcptype):void 0,void 0,void 0);this._remoteCandidates.push(o)}let h=this.findPair(s,o);if(!h){h=new ci(s,o,this.iceControlling);h.updateState(L.WAITING);this.addPair(h)}h.noteIncomingRequest(e.transactionIdHex);h.requestsReceived++;h.responsesSent++;h.localCandidate.ufrag=n;I(\"Triggered Checks\",e.toJSON(),h.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation});if(this.iceLite){if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){h.remoteNominated=true;h.nominated=true;h.updateState(L.SUCCEEDED);this.checkComplete(h)}return}if([L.WAITING,L.FAILED].includes(h.state)){h.handle=this.checkStart(h)}if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){h.remoteNominated=true;if(h.state===L.SUCCEEDED){h.nominated=true;this.checkComplete(h)}}}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&!(e.localCandidate.transport.toLowerCase()===\"tcp\"&&e.localCandidate.tcptype===\"passive\"&&t.type!==\"prflx\")&&!this.findPair(e,t)){const s=new ci(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(s)){return}s.updateState(L.WAITING);this.addPair(s)}}pairLocalProtocol(e){for(const t of this.remoteCandidates){this.tryPair(e,t)}}buildRequest({nominate:e,remoteUsername:t,localUsername:s,iceControlling:i,localCandidate:n}){const o=nm({remoteUsername:t,localUsername:s});const c=new Q(Y.BINDING,B.REQUEST);c.setAttribute(\"USERNAME\",o).setAttribute(\"PRIORITY\",lt(\"prflx\",{transport:n?.transport,tcptype:n?.tcptype}));if(i){c.setAttribute(\"ICE-CONTROLLING\",this.tieBreaker);if(e){c.setAttribute(\"USE-CANDIDATE\",null)}}else{c.setAttribute(\"ICE-CONTROLLED\",this.tieBreaker)}return c}pruneTcpConnections(e){for(const t of this.protocols){if(t.localCandidate?.transport.toLowerCase()!==\"tcp\"){continue}if(\"pruneForSelection\"in t&&typeof t.pruneForSelection===\"function\"){void t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}}}respondError(e,t,s,i){const n=new Q(e.messageMethod,B.ERROR,e.transactionId);n.setAttribute(\"ERROR-CODE\",i).addMessageIntegrity(Buffer.from(this.localPassword,\"utf8\")).addFingerprint();s.sendStun(n,t).catch(o=>{I(\"sendStun error\",o)})}};var nm=a(({remoteUsername:r,localUsername:e})=>{return`${r}:${e}`},\"encodeTxUsername\");var _u=a(r=>{const[e,t]=r.split(\":\");return{remoteUsername:e,localUsername:t}},\"decodeTxUsername\");var Zs=require(\"node:crypto\");var to=class extends Map{static{a(this,\"RTCStatsReport\")}constructor(e){super();if(e){for(const t of e){this.set(t.id,t)}}}};function D(r,...e){const t=e.filter(s=>s!==void 0);return`${r}_${t.join(\"_\")}`}a(D,\"generateStatsId\");function $s(r,e,t){return D(\"codec\",r,e,t)}a($s,\"generateCodecStatsId\");function J(){return performance.timeOrigin+performance.now()}a(J,\"getStatsTimestamp\");function om(r){const e=[];for(const[t,s]of Object.entries(r)){if(t===\"id\"){continue}if(t.endsWith(\"Id\")){if(typeof s===\"string\"){e.push(s)}continue}if(t.endsWith(\"Ids\")&&Array.isArray(s)){for(const i of s){if(typeof i===\"string\"){e.push(i)}}}}return e}a(om,\"getReferencedStatsIds\");function Wt(r,e){const t=new Map;for(const n of r){t.set(n.id,n)}if(!e){return new to([...t.values()])}const s=new Set;const i=[...new Set(Array.from(e))];while(i.length>0){const n=i.shift();if(!n||s.has(n)){continue}const o=t.get(n);if(!o){continue}s.add(n);i.push(...om(o))}return new to([...s].map(n=>t.get(n)).filter(n=>!!n))}a(Wt,\"buildStatsReport\");var Gu=require(\"node:crypto\");var Mu=require(\"node:crypto\");var Fa=require(\"node:perf_hooks\");var Du=require(\"node:crypto\");var so=class{static{a(this,\"RTCRtpTransceiver\")}set codecs(e){this._codecs=e}get codecs(){return this._codecs}get codecPreferences(){return this._codecPreferences}setCodecPreferences(e){if(!Array.isArray(e)){throw Re(\"codecs must be an array\")}const t=e.length===0?void 0:e.map(_d);if(am(this._codecPreferences,t))return;this._codecPreferences=t;this.codecPreferencesNeedResolution=true;this._codecs=[];this.onCodecPreferencesChanged.execute()}constructor(e,t,s,i,n){this.kind=e;this.receiver=s;this.sender=i;this._direction=n;this.id=(0,Du.randomUUID)().toString();this.onTrack=new w;this.mid=null;this.usedForSender=false;this._codecs=[];this.headerExtensions=[];this.onCodecPreferencesChanged=new w;this.codecPreferencesNeedResolution=false;this.options={};this.stopping=false;this.stopped=false;this.rejected=false;this.pendingRejection=false;this.firedReceiving=false;this.addedByAddTrack=false;this.onStopRequested=new w;this.onRelease=new w;this.onDirectionChanged=new w;if(t){this.setDtlsTransport(t)}}get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){const t=e!==this._direction;this.setDirection(e);if(t)this.onDirectionChanged.execute()}setDirection(e){this._direction=e;if(this._currentDirection&&this._currentDirection!==\"stopped\"&&zt.includes(this._currentDirection)){this.usedForSender=true}}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e;if(e&&e!==\"stopped\"&&zt.includes(e)&&this.sender.track){this.usedForSender=true}}setDtlsTransport(e){this.receiver.setDtlsTransport(e);this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){const t=this.receiver.addTrack(e);if(t){this.onTrack.execute(e,this)}}get associated(){return this.mid!=null&&this.mLineIndex!=void 0}stop(){if(this.stopping){return}this.stopping=true;this.releaseMedia();if(!this.associated){this.markStopped()}this.onStopRequested.execute()}commitStopped({rejected:e}){if(e&&!this.stopping){this.rejected=true}this.pendingRejection=false;this.stopping=true;this.releaseMedia();this.markStopped()}markStopped(){this.stopped=true;this.setCurrentDirection(\"stopped\")}releaseMedia(){this.sender.stop({keepTrack:true});this.receiver.stop();this.receiver.endTracks();this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped){return}this.stopping=true;this.stopped=true;this.setCurrentDirection(\"stopped\");this.receiver.stop();this.sender.stop();this.onRelease.execute()}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){const e=J();return this.collectCodecStats(e)}collectCodecStats(e){const t=[];if(!this.dtlsTransport){return t}const s=D(\"transport\",this.dtlsTransport.id);for(const i of this.codecs){const n={type:\"codec\",id:$s(s,i.payloadType,this.id),timestamp:e,payloadType:i.payloadType,transportId:s,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,sdpFmtpLine:i.parameters};t.push(n)}return t}};function am(r,e){if(r===e)return true;if(r==void 0||e==void 0||r.length!==e.length){return false}return ro(r)===ro(e)}a(am,\"sameCodecPreferences\");function ro(r){if(Array.isArray(r)){return`[${r.map(ro).join(\",\")}]`}if(r!=void 0&&typeof r===\"object\"){const e=Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[s])=>t.localeCompare(s));return`{${e.map(([t,s])=>`${JSON.stringify(t)}:${ro(s)}`).join(\",\")}}`}return JSON.stringify(r)??\"undefined\"}a(ro,\"stableCodecValue\");var cm=\"inactive\";var Ha=\"sendonly\";var za=\"recvonly\";var qa=\"sendrecv\";var io=[cm,Ha,za,qa];var dm=b(\"webrtc/peer/utils\");function Ka(r,e){const t=a(n=>n.toUpperCase(),\"upper\");const s=a(n=>n.match(/(.{2})/g).join(\":\"),\"colon\");const i=(0,Mu.createHash)(e).update(r).digest(\"hex\");return s(t(i))}a(Ka,\"fingerprint\");var hm={sha1:\"sha1\",\"sha-1\":\"sha1\",sha224:\"sha224\",\"sha-224\":\"sha224\",sha256:\"sha256\",\"sha-256\":\"sha256\",sha384:\"sha384\",\"sha-384\":\"sha384\",sha512:\"sha512\",\"sha-512\":\"sha512\"};function Ga(r){return hm[r.trim().toLowerCase()]}a(Ga,\"normalizeFingerprintAlgorithm\");function no(r){return r.replace(/[^0-9a-f]/gi,\"\").toLowerCase()}a(no,\"normalizeFingerprintValue\");function Ou(r){const e=r[0];return e>19&&e<64}a(Ou,\"isDtls\");var oo=a((r,e)=>io[io.indexOf(r)&io.indexOf(e)],\"andDirection\");function Uu(r){if(r===\"sendonly\")return\"recvonly\";if(r===\"recvonly\")return\"sendonly\";return r}a(Uu,\"reverseDirection\");var Vs=Date.now;var um=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n;var Hu=a(()=>{return um+process.hrtime.bigint()/1000n},\"microTime\");var Ys=a(()=>Date.now()/1e3,\"timestampSeconds\");var ja=Date.UTC(1900,0,1);var zu=a((r=Fa.performance.timeOrigin+Fa.performance.now())=>{const e=r-ja;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);return BigInt(t)<<32n|BigInt(s)},\"ntpTime\");var Wa=a(r=>{const e=r-ja;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);const i=Buffer.allocUnsafe(3);i.writeUIntBE((t&63)<<18|s>>>14,0,3);return i},\"absSendTimeOf\");var qu=a(r=>{const e=Number(r>>32n);const t=Number(r&0xffffffffn);return e*1e3+t/2**32*1e3+ja},\"ntpTimeToEpochMs\");var ao=a(r=>{return Number(r>>16n&0xffffffffn)},\"compactNtp\");function Fu(r){const e={stunServers:[],turnServers:[]};for(const t of r){const s=Array.isArray(t.urls)?t.urls:[t.urls];for(const i of s){const n=lm(i);if(!n){continue}if(n.kind===\"stun\"){e.stunServer??=n.address;e.stunServers.push(n.address)}if(n.kind===\"turn\"){if(!e.turnServer){e.turnServer=n.address;e.turnTransport=n.transport;e.turnUsername=t.username;e.turnPassword=t.credential}if(t.username&&t.credential){e.turnServers.push({address:n.address,username:t.username,password:t.credential,transport:n.transport})}}}}dm(\"iceOptions\",e);return e}a(Fu,\"parseIceServers\");function $a({configuredTurnTransport:r,forceTurnTCP:e,parsedTurnTransport:t}){if(t){return t}if(r){return r}if(e){return\"tcp\"}return void 0}a($a,\"resolveTurnTransport\");function lm(r){const e=/^(stun|stuns|turn|turns):(.+)$/i.exec(r.trim());if(!e){return}const[,t,s]=e;const i=t.toLowerCase();const[n]=s.split(\"?\",1);const[,o=\"\"]=s.split(\"?\");const c=mm(n,pm(i));if(!c){return}if(i===\"stun\"||i===\"stuns\"){return{kind:\"stun\",address:c}}const d=new URLSearchParams(o);const h=d.get(\"transport\");const l=fm({scheme:i,transportParam:h});if(l===\"invalid\"){return}return{kind:\"turn\",address:c,transport:l}}a(lm,\"parseIceServerUrl\");function fm({scheme:r,transportParam:e}){if(e==null){return r===\"turns\"?\"tls\":void 0}if(e===\"udp\"){return r===\"turns\"?\"invalid\":\"udp\"}if(e===\"tcp\"){return r===\"turns\"?\"tls\":\"tcp\"}return\"invalid\"}a(fm,\"resolveParsedTurnTransport\");function pm(r){if(r===\"stuns\"||r===\"turns\"){return 5349}return 3478}a(pm,\"defaultPort\");function mm(r,e){const t=r.startsWith(\"//\")?r.slice(2):r;if(!t){return}if(t.startsWith(\"[\")){const n=t.indexOf(\"]\");if(n===-1){return}const o=t.slice(1,n);const c=Nu(t.slice(n+1),e);return[o,c]}const s=t.indexOf(\":\");const i=t.lastIndexOf(\":\");if(s!==-1&&s===i){return[t.slice(0,s),Nu(t.slice(s+1),e)]}return[t,e]}a(mm,\"parseAddress\");function Nu(r,e){const t=r.startsWith(\":\")?r.slice(1):r;const s=Number.parseInt(t,10);return Number.isFinite(s)?s:e}a(Nu,\"parsePort\");var Xv=Xe.createSelfSignedCertificateWithKey;var Ku=a((r,e)=>{if(!r||typeof r!==\"object\"){if(e!==null&&typeof e===\"object\"){return e}else{return r}}if(!e||typeof e!==\"object\"){if(e==void 0){return r}return e}for(const t in e){if(Object.prototype.hasOwnProperty.call(e,t)){const s=e[t];if(s!=void 0){r[t]=s}}}return r},\"deepMerge\");var gm=b(\"webrtc/peer/media/receiver/receiverTwcc\");var Sm=100;var ym=500;var Tm=1<<15;function wm(r){const e=[];let t=0;while(t<r.length){let s=1;while(t+s<r.length&&r[t+s]===r[t]&&s<8191)s++;if(s>=7){e.push(new rs({packetStatus:r[t],runLength:s}));t+=s;continue}const i=r.slice(t,t+14);const n=i.includes(z.TypeTCCPacketReceivedLargeDelta)?r.slice(t,t+7):i;const o=n===i?14:7;e.push(new Sr({type:dt.TypeTCCStatusVectorChunk,symbolSize:o===14?0:1,symbolList:[...n,...Array(o-n.length).fill(z.TypeTCCPacketNotReceived)]}));t+=o}return e}a(wm,\"packetChunksOf\");var co=class{static{a(this,\"ReceiverTWCC\")}constructor(e){this.dtlsTransport=e;this.arrivals=new Map;this.fbPktCount=0;this.rtcpSsrc=(0,Gu.randomBytes)(4).readUInt32BE();this.mediaSourceSsrc=0}handleTWCC(e,t,s=Number(Hu())){const i=this.unwrap(e);if(this.nextSequenceNumber!==void 0&&i<this.nextSequenceNumber)return;if(!this.arrivals.has(i))this.arrivals.set(i,s);if(this.arrivals.size>Tm){let n=i;for(const o of this.arrivals.keys())n=Math.min(n,o);this.arrivals.delete(n);this.nextSequenceNumber=n+1}this.mediaSourceSsrc=t;if(!this.timer){this.timer=setInterval(()=>this.sendTWCC(),Sm);this.timer.unref()}}stop(){clearInterval(this.timer);this.timer=void 0;this.arrivals.clear()}sendTWCC(){if(this.arrivals.size===0)return;let e=this.nextSequenceNumber??Infinity;if(e===Infinity){for(const s of this.arrivals.keys())e=Math.min(e,s)}const t=this.highestSequenceNumber;while(e<=t){const{feedback:s,next:i}=this.buildFeedback(e,t);this.dtlsTransport.sendRtcp([new Z({feedback:s})]).catch(n=>gm(n));e=i}this.arrivals.clear();this.nextSequenceNumber=t+1}unwrap(e){if(this.highestSequenceNumber===void 0){this.highestSequenceNumber=e;return e}let t=e-this.highestSequenceNumber&65535;if(t>=32768)t-=65536;const s=this.highestSequenceNumber+t;if(s>this.highestSequenceNumber)this.highestSequenceNumber=s;return s}buildFeedback(e,t){let s=e;while(!this.arrivals.has(s))s++;const i=Math.floor(this.arrivals.get(s)/64e3);let n=i*64e3;const o=[];const c=[];let d=e;for(;d<=t&&o.length<ym;d++){const l=this.arrivals.get(d);if(l===void 0){o.push(z.TypeTCCPacketNotReceived);continue}const u=Math.round((l-n)/250);if(u<-32768||u>32767)break;const g=u>=0&&u<=255?z.TypeTCCPacketReceivedSmallDelta:z.TypeTCCPacketReceivedLargeDelta;o.push(g);c.push(new bt({type:g,delta:u*250}));n+=u*250}const h=new je({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:e&65535,packetStatusCount:o.length,referenceTime:i&16777215,fbPktCount:this.fbPktCount,packetChunks:wm(o),recvDeltas:c});this.fbPktCount=Rc(this.fbPktCount,1);return{feedback:h,next:d}}};var ho=class{static{a(this,\"CumulativeResult\")}constructor(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}addPacket(e,t,s){if(this.numPackets===0){this.firstPacketSentAtMs=t;this.firstPacketReceivedAtMs=s;this.lastPacketSentAtMs=t;this.lastPacketReceivedAtMs=s}else{if(t<this.firstPacketSentAtMs)this.firstPacketSentAtMs=t;if(s<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=s;if(t>this.lastPacketSentAtMs)this.lastPacketSentAtMs=t;if(s>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=s}this.numPackets++;this.totalSize+=e}reset(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}get receiveBitrate(){const e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;const t=this.totalSize/e*8*1e3;return ss(t)}get sendBitrate(){const e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;const t=this.totalSize/e*8*1e3;return ss(t)}};var Qs=20;var bm=10;var Cm=8192;var uo=class{static{a(this,\"SenderBandwidthEstimator\")}get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e;this.onCongestionScore.execute(e)}get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e;this.onAvailableBitrate.execute(e)}constructor(){this.congestion=false;this.onAvailableBitrate=new w;this.onCongestion=new w;this.onCongestionScore=new w;this.congestionCounter=0;this.cumulativeResult=new ho;this.sentInfos=new Map;this._congestionScore=1;this._availableBitrate=0}receiveTWCC(e){const t=Vs();const s=this.cumulativeResult.numPackets?t-this.cumulativeResult.firstPacketSentAtMs:0;if(s>1e3){this.cumulativeResult.reset();if(this.congestionCounter<Qs){this.congestionCounter++}else if(this.congestionScore<bm){this.congestionScore++}if(this.congestionCounter>=Qs&&!this.congestion){this.congestion=true;this.onCongestion.execute(this.congestion)}}for(const i of e.packetResults){if(!i.received)continue;const n=i.sequenceNumber;const o=this.sentInfos.get(n);if(!o)continue;if(!i.receivedAtMs)continue;this.cumulativeResult.addPacket(o.size,o.sendingAtMs,i.receivedAtMs)}if(s>=100&&this.cumulativeResult.numPackets>=20){this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate);this.cumulativeResult.reset();if(this.congestionCounter>-Qs){const i=ss(Qs/2)+1;const n=ss(Qs/4)+1;const o=i-(i-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-o}if(this.congestionCounter<=-Qs){if(this.congestionScore>1){this.congestionScore--;this.onCongestion.execute(false)}this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion){this.congestion=false;this.onCongestion.execute(this.congestion)}}}rtpPacketSent(e){this.sentInfos.delete(e.wideSeq-Cm&65535);this.sentInfos.set(e.wideSeq,e)}};var Se=b(\"webrtc/peer/transport/dtls\");var Em=a(()=>void 0,\"ignoreSendFailure\");function Rm(r){if(!r){return}if(r.major===254&&r.minor===253){return\"DTLS 1.2\"}if(r.major===254&&r.minor===255){return\"DTLS 1.0\"}}a(Rm,\"formatDtlsVersion\");function xm(r){switch(r){case 1:return\"AES_CM_128_HMAC_SHA1_80\";case 7:return\"AEAD_AES_128_GCM\";default:return}}a(xm,\"formatSrtpCipher\");var hi=class r{static{a(this,\"RTCDtlsTransport\")}#e;#t;constructor(e,t,s,i=[]){this.config=e;this.iceTransport=t;this.localCertificate=s;this.srtpProfiles=i;this.id=(0,Zs.randomUUID)().toString();this.state=\"new\";this.role=\"auto\";this.srtpStarted=false;this.transportSequenceNumber=0;this.receiverTWCC=new co(this);this.senderBWE=new uo;this.bytesSent=0;this.bytesReceived=0;this.packetsSent=0;this.packetsReceived=0;this.dataReceiver=()=>{};this.onStateChange=new w;this.onRtcp=new w;this.onRtp=new w;this.events=new he;this.addEventListener=(n,o,c)=>{this.events.addEventListener(n,o,c)};this.removeEventListener=(n,o)=>{this.events.removeEventListener(n,o)};this.dispatchEvent=n=>this.events.dispatchEvent(n);this.sendData=async n=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return}if(!this.dtls){throw new Error(\"dtls not established\")}await this.dtls.send(n)};this.localCertificate??=r.localCertificate;this.#e=Pm(t.connection)}get localParameters(){return new Js(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate){return this.localCertificate}if(this.localCertificatePromise){return this.localCertificatePromise}this.localCertificatePromise=(async()=>{const{certPem:e,keyPem:t,signatureHash:s}=await Xe.createSelfSignedCertificateWithKey({signature:ce.ecdsa_3,hash:cn.sha256_4},Ve.secp256r1_23);this.localCertificate=new ui(t,e,s);return this.localCertificate})();return this.localCertificatePromise}setRemoteParams(e){const t=km([...this.remoteParameters?.fingerprints??[],...e.fingerprints]);const s=e.role===\"auto\"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new Js(t,s)}async start(){if(this.#t){return await this.#t}if(this.state!==\"new\"){throw new Error(\"state must be new\")}this.#t=this.#s();await this.#t}async#s(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}if(this.role===\"auto\"){if(this.iceTransport.role===\"controlling\"){this.role=\"server\"}else{this.role=\"client\"}}this.setState(\"connecting\");await new Promise((e,t)=>{if(this.role===\"server\"){this.dtls=new Qr({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true,certificateRequest:true})}else{this.dtls=new Ms({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true})}this.dtls.onData.subscribe(s=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}this.dataReceiver(s)});this.dtls.onClose.subscribe(()=>{if(this.state!==\"failed\"){this.setState(\"closed\")}});this.dtls.onConnect.once(e);this.dtls.onError.once(s=>{this.setState(\"failed\");Se(\"dtls failed\",s);t(s)});if(this.dtls instanceof Ms){this.dtls.connect().catch(s=>{this.setState(\"failed\");Se(\"dtls connect failed\",s);t(s)})}});try{this.verifyRemoteCertificateFingerprint()}catch(e){this.setState(\"failed\");this.dtls?.close();throw e}if(this.srtpProfiles.length>0){this.startSrtp()}this.setState(\"connected\");Se(\"dtls connected\")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}const e=this.dtls?.remoteCertificate;if(!e){throw new Error(\"remote certificate not available\")}const t=this.remoteParameters.fingerprints.flatMap(({algorithm:c,value:d})=>{const h=Ga(c);if(!h){return[]}const l=no(d);if(!l){throw new Error(\"remote fingerprint value is empty\")}return[{normalizedAlgorithm:h,normalizedValue:l}]});if(t.length===0){throw new Error(\"no supported remote fingerprint algorithms\")}const s=Im(t);const i=t.filter(({normalizedAlgorithm:c})=>c===s);const n=i.reduce((c,{normalizedAlgorithm:d})=>{if(!c.has(d)){c.set(d,no(Ka(e,d)))}return c},new Map);const o=i.some(({normalizedAlgorithm:c,normalizedValue:d})=>n.get(c)===d);if(!o){throw new Error(\"remote certificate fingerprint mismatch\")}}updateSrtpSession(){if(!this.dtls)throw new Error;const e=this.dtls.srtp.srtpProfile;if(!e){throw new Error(\"need srtpProfile\")}Se(\"selected SRTP Profile\",e);const{localKey:t,localSalt:s,remoteKey:i,remoteSalt:n}=this.dtls.extractSessionKeys(qc(e),Fc(e));const o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:i,remoteMasterSalt:n},profile:e};this.srtp=new Yi(o);this.srtcp=new $i(o)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=true;this.updateSrtpSession();this.iceTransport.connection.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}if(!jc(e))return;this.bytesReceived+=e.length;this.packetsReceived++;if($c(e)){let t;try{t=this.srtcp.decrypt(e)}catch(i){if(i instanceof le){Se(\"dropping invalid SRTCP packet\",i);return}throw i}let s;try{s=Oi.deSerialize(t)}catch(i){Se(\"dropping malformed SRTCP packet\",i);return}for(const i of s){try{if(i instanceof Z&&i.feedback instanceof je){this.senderBWE.receiveTWCC(i.feedback);continue}this.onRtcp.execute(i)}catch(n){Se(\"RTCP error\",n)}}}else{let t;try{t=this.srtp.decrypt(e)}catch(i){if(i instanceof le){Se(\"dropping invalid SRTP packet\",i);return}throw i}let s;try{s=W.deSerialize(t)}catch(i){Se(\"dropping malformed SRTP packet\",i);return}try{this.onRtp.execute(s)}catch(i){Se(\"RTP error\",i)}}})}async sendRtp(e,t){try{const s=this.srtp.encrypt(e,t);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(Em);return s.length}catch(s){Se(\"failed to send\",s);return 0}}async sendRtcp(e){if(!this.srtcp){return}const t=Buffer.concat(e.map(i=>i.serialize()));const s=this.srtcp.encrypt(t);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,t=true){if(e!=this.state){this.state=e;if(e===\"closed\"||e===\"failed\")this.receiverTWCC.stop();this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}async stop(){this.setState(\"closed\",false);this.dtls?.close();await this.iceTransport.stop()}async getStats(e=J()){const t=[];const s=D(\"transport\",this.id);const i={type:\"transport\",id:s,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===\"unknown\"?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?D(\"candidate-pair\",this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?D(\"certificate\",this.id,\"local\"):void 0,remoteCertificateId:this.dtls?.remoteCertificate?D(\"certificate\",this.id,\"remote\"):void 0,dtlsRole:this.role===\"auto\"?void 0:this.role,tlsVersion:Rm(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:xm(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};t.push(i);if(this.localCertificate){const o=this.localCertificate.getFingerprints();if(o.length>0){const c={type:\"certificate\",id:D(\"certificate\",this.id,\"local\"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(\"base64\")};t.push(c)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){const o={type:\"certificate\",id:D(\"certificate\",this.id,\"remote\"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(\"base64\")};t.push(o)}const n=await this.iceTransport.getStats(e,s);t.push(...n);return t}};var ui=class{static{a(this,\"RTCCertificate\")}constructor(e,t,s){this.certPem=t;this.signatureHash=s;this.publicKey=new Zs.X509Certificate(t).publicKey.export({type:\"spki\",format:\"pem\"});this.privateKey=(0,Zs.createPrivateKey)(e).export({type:\"pkcs8\",format:\"pem\"})}getFingerprints(){return[new Xs(\"sha-256\",Ka(fn(this.certPem),\"sha256\"))]}};var Xs=class{static{a(this,\"RTCDtlsFingerprint\")}constructor(e,t){this.algorithm=e;this.value=t}};var Js=class{static{a(this,\"RTCDtlsParameters\")}constructor(e=[],t){this.fingerprints=e;this.role=t}};var km=a(r=>{const e=new Set;return r.filter(({algorithm:t,value:s})=>{const i=`${Ga(t)??t.trim().toLowerCase()}:${no(s)}`;if(e.has(i)){return false}e.add(i);return true})},\"deduplicateFingerprints\");var vm=[\"sha512\",\"sha384\",\"sha256\",\"sha224\",\"sha1\"];var Im=a(r=>{return vm.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm},\"selectPreferredFingerprintAlgorithm\");var Va=class{static{a(this,\"IceTransport\")}#e;#t;constructor(e){this.ice=e;this.closed=false;this.#e=[];this.type=\"ice\";this.send=t=>{return this.ice.send(t)};e.onData.subscribe(t=>{if(!Ou(t))return;if(this.#t)this.#t(t);else if(this.#e&&this.#e.length<16)this.#e.push(t)})}get onData(){return this.#t??(()=>void 0)}set onData(e){const t=this.#e;if(!t){this.#t=e;return}queueMicrotask(()=>{this.#e=void 0;this.#t=e;t.forEach(s=>e(s))})}get address(){return{}}async close(){this.closed=true;K(()=>this.ice.close(),e=>Se(\"close failed\",e))}};var Pm=a(r=>new Va(r),\"createIceTransport\");var ju=require(\"node:crypto\");var lo=b(\"webrtc/peer/transport/ice\");function Am(r){switch(r){case 0:return\"frozen\";case 1:return\"waiting\";case 2:return\"in-progress\";case 3:return\"succeeded\";case 4:return\"failed\";default:return\"failed\"}}a(Am,\"mapCandidatePairState\");var fo=class{static{a(this,\"RTCIceTransport\")}constructor(e){this.iceGather=e;this.id=(0,ju.randomUUID)().toString();this.state=\"new\";this.component=\"rtp\";this.iceRestarts=0;this.renominating=false;this.events=new he;this.onStateChange=new w;this.onIceCandidate=new w;this.onNegotiationNeeded=new w;this.addEventListener=(t,s,i)=>{this.events.addEventListener(t,s,i)};this.removeEventListener=(t,s)=>{this.events.removeEventListener(t,s)};this.dispatchEvent=t=>this.events.dispatchEvent(t);this.addRemoteCandidate=async t=>{if(!this.connection.remoteCandidatesEnd){await this.connection.addRemoteCandidate(t?_m(t):void 0)}};this.connection=this.iceGather.connection;this.connection.stateChanged.subscribe(t=>{this.setState(t)});this.iceGather.onIceCandidate=t=>{this.onIceCandidate.execute(t)};this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.();this.events.emit(\"gatheringstatechange\")})}get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return\"unknown\"}if(this.connection.iceControlling)return\"controlling\";else return\"controlled\"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==\"prflx\").map(e=>nt(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>nt(e).toJSON())}getSelectedCandidatePair(){const e=this.connection.candidatePairs.find(t=>t.nominated)??this.connection.candidatePairs.find(t=>t.state===3);if(!e){return null}return{local:nt(e.localCandidate).toJSON(),remote:nt(e.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return null}return new er({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=true){if(e!==this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}gather(){return this.iceGather.gather()}setIceServers(e){this.iceGather.setIceServers(e)}setRemoteParams(e,t=false){if(t){this.renominating=true}if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)){if(this.renominating){lo(\"renomination\",e);this.connection.resetNominatedPair();this.checking=void 0;this.renominating=false}else{lo(\"restart\",e);this.restart()}}this.connection.setRemoteParams(e)}restart(){this.iceRestarts++;this.connection.restart().catch(e=>lo(\"restart failed\",e));this.setState(\"new\");this.iceGather.setGatheringState(\"new\");this.checking=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.checking??=this.check();await this.checking}async check(){this.setState(\"checking\");try{await this.connection.connect()}catch(e){if(this.state!==\"closed\")this.setState(\"failed\");throw e}}async stop(){if(this.state!==\"closed\"){this.setState(\"closed\",false);await this.connection.close()}this.onStateChange.complete();this.onIceCandidate.complete();this.onNegotiationNeeded.complete()}async getStats(e=J(),t=D(\"transport\",this.id)){const s=[];for(const n of this.connection.localCandidates){const o={type:\"local-candidate\",id:D(\"local-candidate\",n.id),timestamp:e,transportId:t,address:n.host,port:n.port,protocol:n.transport,candidateType:n.type,priority:n.priority,foundation:n.foundation,relatedAddress:n.relatedAddress,relatedPort:n.relatedPort,usernameFragment:n.ufrag,tcpType:n.tcptype};s.push(o)}for(const n of this.connection.remoteCandidates){const o={type:\"remote-candidate\",id:D(\"remote-candidate\",n.id),timestamp:e,transportId:t,address:n.host,port:n.port,protocol:n.transport,candidateType:n.type,priority:n.priority,foundation:n.foundation,relatedAddress:n.relatedAddress,relatedPort:n.relatedPort,usernameFragment:n.ufrag,tcpType:n.tcptype};s.push(o)}const i=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(n=>n.nominated),...this.connection.candidatePairs.filter(n=>!n.nominated)]:[];for(const n of i){const o={type:\"candidate-pair\",id:D(\"candidate-pair\",n.id),timestamp:e,transportId:t,localCandidateId:D(\"local-candidate\",n.localCandidate.id),remoteCandidateId:D(\"remote-candidate\",n.remoteCandidate.id),state:Am(n.state),nominated:n.nominated,packetsSent:n.packetsSent,packetsReceived:n.packetsReceived,bytesSent:n.bytesSent,bytesReceived:n.bytesReceived,currentRoundTripTime:n.rtt,totalRoundTripTime:n.totalRoundTripTime,roundTripTimeMeasurements:n.roundTripTimeMeasurements,requestsReceived:n.requestsReceived,requestsSent:n.requestsSent,responsesReceived:n.responsesReceived,responsesSent:n.responsesSent,retransmissionsReceived:n.retransmissionsReceived,retransmissionsSent:n.retransmissionsSent,consentRequestsSent:n.consentRequestsSent};s.push(o)}return s}};var po=class{static{a(this,\"RTCIceGatherer\")}constructor(e={}){this.options=e;this.onIceCandidate=()=>{};this.gatheringState=\"new\";this.onGatheringStateChange=new w;this.connection=new eo(false,this.options);this.connection.onIceCandidate.subscribe(t=>{this.onIceCandidate(nt(t))})}async gather(){if(this.gatheringState===\"new\"){this.setState(\"gathering\");await this.connection.gatherCandidates();this.onIceCandidate(void 0);this.setState(\"complete\")}}setIceServers(e){this.connection.setIceServers(e)}setGatheringState(e){this.setState(e)}get localCandidates(){return this.connection.localCandidates.map(nt)}get localParameters(){const e=new er({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword});return e}setState(e){if(e!==this.gatheringState){this.gatheringState=e;this.onGatheringStateChange.execute(e)}}};function nt(r){const e=new li(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);e.relatedAddress=r.relatedAddress;e.relatedPort=r.relatedPort;e.tcpType=r.tcptype;return e}a(nt,\"candidateFromIce\");function _m(r){return new te(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}a(_m,\"candidateToIce\");var Ya=class{static{a(this,\"RTCIceCandidate\")}constructor(e){Object.assign(this,e)}static fromSdp(e){const t=te.fromSdp(e);const s=nt(t);return s.toJSON()}static isThis(e){if(typeof e?.candidate===\"string\")return true}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};var li=class{static{a(this,\"IceCandidate\")}constructor(e,t,s,i,n,o,c,d,h){this.component=e;this.foundation=t;this.ip=s;this.port=i;this.priority=n;this.protocol=o;this.type=c;this.generation=d;this.ufrag=h}toJSON(){return new Ya({candidate:Qa(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate){throw new Error(\"candidate is required\")}const t=e.candidate.startsWith(\"candidate:\")?e.candidate.slice(\"candidate:\".length):e.candidate;const s=Xa(t);s.sdpMLineIndex=e.sdpMLineIndex??void 0;s.sdpMid=e.sdpMid??void 0;return s}catch(t){lo(\"candidate not parsed\",t)}}};var er=class{static{a(this,\"RTCIceParameters\")}constructor(e={}){this.iceLite=false;Object.assign(this,e)}};var Wu=require(\"node:crypto\");var oe=b(\"webrtc/peer/transport/sctp\");var tr=65536;var mo=class r{static{a(this,\"RTCSctpTransport\")}constructor(e=5e3,t=tr,s={}){this.port=e;this.maxMessageSize=t;this.sctpOptions=s;this.onDataChannel=new w;this.id=(0,Wu.randomUUID)().toString();this.bundled=false;this.dataChannels={};this.remoteMaxMessageSize=tr;this.dataChannelQueue=[];this.eventDisposer=[];this.datachannelReceive=async(i,n,o)=>{if(n===Us&&o.length>0){oe(\"DCEP\",i,n,o);switch(o[0]){case la:{if(o.length<12){oe(\"DATA_CHANNEL_OPEN data.length not enough\");return}if(!Object.keys(this.dataChannels).includes(i.toString())){const h=o.readUInt8(1);const l=o.readUInt32BE(4);const u=o.readUInt16BE(8);const g=o.readUInt16BE(10);let S=12;const p=o.slice(S,S+u).toString(\"utf8\");S+=u;const f=o.slice(S,S+g).toString(\"utf8\");oe(\"DATA_CHANNEL_OPEN\",{channelType:h,reliability:l,streamId:i,label:p,protocol:f});const y=(h&3)===1?l:void 0;const m=(h&3)===2?l:void 0;const T=new Zt({label:p,ordered:(h&128)===0,maxPacketLifeTime:m,maxRetransmits:y,protocol:f,id:i});const C=new Jt(this,T,false);C.isCreatedByRemote=true;this.dataChannels[i]=C;this.onDataChannel.execute(C);C.setReadyState(\"open\")}else{oe(\"datachannel already opened\",\"retransmit ack\")}const c=this.dataChannels[i];const d=Buffer.allocUnsafe(1);d.writeUInt8(ua,0);this.dataChannelQueue.push([c,Us,d]);await this.dataChannelFlush()}break;case ua:{oe(\"DATA_CHANNEL_ACK\",i,n);const c=this.dataChannels[i];if(!c){throw new Error(\"channel not found\")}c.setReadyState(\"open\")}break}}else{const c=this.dataChannels[i];if(c){const d=(()=>{switch(n){case fa:return o.toString(\"utf8\");case On:return\"\";case pa:return o;case Un:return Buffer.from([]);default:throw new Error}})();c.messagesReceived++;c.bytesReceived+=o.length;c.onMessage.execute(d);c.emit(\"message\",{data:d});if(c.onmessage){K(()=>c.onmessage({data:d}),h=>oe(\"onmessage failed\",h))}}}};this.datachannelSend=(i,n)=>{const o=pr(n);this.assertSendableMessageSize(o);i.addBufferedAmount(o);if(o===0){this.dataChannelQueue.push([i,typeof n===\"string\"?On:Un,Buffer.from([0])])}else{const c=Buffer.isBuffer(n)?n:Buffer.from(n);this.dataChannelQueue.push(typeof n===\"string\"?[i,fa,c]:[i,pa,c])}if(this.sctp.associationState!==A.ESTABLISHED){oe(\"sctp not established\",this.sctp.associationState)}this.dataChannelFlush().catch(c=>oe(\"flush failed\",c));return o}}get transport(){return this.dtlsTransport}setDtlsTransport(e){if(this.dtlsTransport&&this.dtlsTransport.id===e.id){return}this.eventDisposer.forEach(t=>t());this.dtlsTransport=e;this.sctp=new Br(new Ja(this.dtlsTransport),this.port,this.sctpOptions);this.eventDisposer=[...[this.sctp.onReceive.subscribe(ye(this.datachannelReceive,t=>oe(\"receive failed\",t))),this.sctp.onReconfigStreams.subscribe(t=>{t.forEach(s=>{const i=this.dataChannels[s];if(!i)return;i.setReadyState(\"closing\");i.setReadyState(\"closed\");delete this.dataChannels[s]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{if(t.negotiated&&t.readyState!==\"open\"){t.setReadyState(\"open\")}});this.dataChannelFlush().catch(t=>oe(\"flush failed\",t))}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState(\"closed\")});this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"closed\"){this.sctp.setState(A.CLOSED)}})].map(t=>t.unSubscribe),()=>this.sctp.onSackReceived=async()=>{},()=>this.sctp.onSent=void 0];this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()};this.sctp.onSent=(t,s,i)=>{if(s===Us||s===On||s===Un){return}this.dataChannels[t]?.addBufferedAmount(-i)}}holdReceived(e){this.sctp.holdReceived(e)}releaseReceived(e){this.sctp.releaseReceived(e)}get isServer(){return this.dtlsTransport.iceTransport.role!==\"controlling\"}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}dataChannelAddNegotiated(e){if(e.id==void 0){throw new Error}if(this.dataChannels[e.id]){throw new Error}this.dataChannels[e.id]=e;if(this.sctp.associationState===A.ESTABLISHED){e.setReadyState(\"open\")}}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=Lh;const s=0;let i=0;if(e.maxRetransmits!==null){t=1;i=e.maxRetransmits}else if(e.maxPacketLifeTime!==null){t=2;i=e.maxPacketLifeTime}if(!e.ordered){t|=128}const n=Buffer.allocUnsafe(12);n.writeUInt8(la,0);n.writeUInt8(t,1);n.writeUInt16BE(s,2);n.writeUInt32BE(i,4);const o=Buffer.from(e.label,\"utf8\");const c=Buffer.from(e.protocol,\"utf8\");n.writeUInt16BE(o.length,8);n.writeUInt16BE(c.length,10);const d=Buffer.concat([n,o,c]);this.dataChannelQueue.push([e,Us,d]);this.dataChannelFlush().catch(h=>oe(\"flush failed\",h))}async dataChannelFlush(){if(this.sctp.associationState!=A.ESTABLISHED)return;while(this.dataChannelQueue.length>0){const[e,t,s]=this.dataChannelQueue.shift();let i=e.id;if(i===void 0){i=this.dataChannelId;while(Object.keys(this.dataChannels).includes(i.toString())){i+=2}this.dataChannels[i]=e;e.setId(i)}if(t===Us){this.sctp.send(i,t,s,{ordered:true}).catch(n=>oe(\"send dcep failed\",n.message))}else{const n=e.maxPacketLifeTime!==null?Date.now()+e.maxPacketLifeTime/1e3:void 0;this.sctp.send(i,t,s,{expiry:n,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}).catch(o=>oe(\"send data failed\",o.message))}}this.dataChannelQueue=[]}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize){throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}}getCapabilities(){return r.getCapabilities(this.maxMessageSize)}static getCapabilities(e=tr){return new fi(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??tr}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=this.dtlsTransport.role===\"server\"?1:0;this.sctp.isServer=this.isServer;await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{};await this.sctp.stop()}dataChannelClose(e){if(![\"closing\",\"closed\"].includes(e.readyState)){e.setReadyState(\"closing\");if(this.sctp.associationState===A.ESTABLISHED){if(!this.sctp.reconfigQueue.includes(e.id)){this.sctp.reconfigQueue.push(e.id)}if(this.sctp.reconfigQueue.length===1){this.sctp.transmitReconfigRequest().catch(t=>oe(\"reconfig failed\",t))}}else{this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id);this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id);if(e.id!==void 0){delete this.dataChannels[e.id]}e.setReadyState(\"closed\")}}}};var fi=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};var Ja=class{static{a(this,\"BridgeDtls\")}constructor(e){this.dtls=e;this.send=t=>{return this.dtls.sendData(t)}}set onData(e){this.dtls.dataReceiver=e}close(){}};var ot=class r{static{a(this,\"SessionDescription\")}constructor(){this.version=0;this.name=\"-\";this.time=\"0 0\";this.group=[];this.extMapAllowMixed=true;this.msidSemantic=[];this.media=[];this.dtlsFingerprints=[]}static parse(e){const[t,s]=Bm(e);const i=new r;t.forEach(c=>{if(c.startsWith(\"v=\")){i.version=Number.parseInt(c.slice(2),10)}else if(c.startsWith(\"o=\")){i.origin=c.slice(2)}else if(c.startsWith(\"s=\")){i.name=c.slice(2)}else if(c.startsWith(\"c=\")){i.host=Za(c.slice(2))}else if(c.startsWith(\"t=\")){i.time=c.slice(2)}else if(c.startsWith(\"a=\")){const[d,h]=ec(c);switch(d){case\"fingerprint\":{const[l,u]=h?.split(\" \")||[];i.dtlsFingerprints.push(new Xs(l,u))}break;case\"ice-lite\":i.iceLite=true;break;case\"ice-options\":i.iceOptions=h;break;case\"ice-pwd\":i.icePassword=h;break;case\"ice-ufrag\":i.iceUsernameFragment=h;break;case\"group\":tc(i.group,h);break;case\"msid-semantic\":tc(i.msidSemantic,h);break;case\"setup\":i.dtlsRole=Sa[h];break;case\"extmap-allow-mixed\":i.extMapAllowMixed=true;break}}});const n=i.group.find(c=>c.semantic===\"BUNDLE\");s.forEach(c=>{const d=c[0];const h=d.match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!h){throw new Error(\"m line not found\")}const l=h[1];const u=h[4].split(\" \");const g=[\"audio\",\"video\"].includes(l)?u.map(f=>Number(f)):void 0;const S=new $t(l,Number.parseInt(h[2]),h[3],g||u);S.dtlsParams=new Js([...i.dtlsFingerprints],i.dtlsRole);S.iceParams=new er({iceLite:i.iceLite,usernameFragment:i.iceUsernameFragment,password:i.icePassword});S.iceOptions=i.iceOptions;i.media.push(S);c.slice(1).forEach(f=>{if(f.startsWith(\"c=\")){S.host=Za(f.slice(2))}else if(f.startsWith(\"a=\")){const[y,m]=ec(f);switch(y){case\"candidate\":if(!m)throw new Error;S.iceCandidates.push(Xa(m));break;case\"end-of-candidates\":S.iceCandidatesComplete=true;break;case\"extmap\":{let[T,C]=m.split(\" \");if(T.includes(\"/\")){[T]=T.split(\"/\")}S.rtp.headerExtensions.push(new Te({id:Number.parseInt(T),uri:C}))}break;case\"fingerprint\":{if(!m)throw new Error;const[T,C]=m.split(\" \");S.dtlsParams?.fingerprints.push(new Xs(T,C))}break;case\"ice-options\":S.iceOptions=m;break;case\"ice-pwd\":S.iceParams.password=m;break;case\"ice-ufrag\":S.iceParams.usernameFragment=m;break;case\"ice-lite\":S.iceParams.iceLite=true;break;case\"max-message-size\":S.sctpCapabilities=new fi(Number.parseInt(m,10));break;case\"mid\":S.rtp.muxId=m;break;case\"msid\":S.msids.push(m);break;case\"rtcp\":{const[T,C]=_e(m,\" \");S.rtcpPort=Number.parseInt(T);S.rtcpHost=Za(C)}break;case\"rtcp-mux\":S.rtcpMux=true;break;case\"bundle-only\":S.bundleOnly=true;break;case\"setup\":S.dtlsParams.role=Sa[m];break;case\"recvonly\":case\"sendonly\":case\"sendrecv\":case\"inactive\":S.direction=y;break;case\"rtpmap\":{const[T,C]=_e(m,\" \");const[E,P,de]=C.split(\"/\");let q;if(S.kind===\"audio\"){q=de?Number.parseInt(de):1}const pt=new re({mimeType:S.kind+\"/\"+E,channels:q,clockRate:Number.parseInt(P),payloadType:Number.parseInt(T)});S.rtp.codecs.push(pt)}break;case\"sctpmap\":{if(!m)throw new Error;const[T,C]=_e(m,\" \");S.sctpMap[Number.parseInt(T)]=C;S.sctpPort=Number.parseInt(T)}break;case\"sctp-port\":if(!m)throw new Error;S.sctpPort=Number.parseInt(m);break;case\"ssrc\":{const[T,C]=_e(m,\" \");const E=Number.parseInt(T);const[P,de]=_e(C,\":\");let q=S.ssrc.find(pt=>pt.ssrc===E);if(!q){q=new sr({ssrc:E});S.ssrc.push(q)}if(ya.includes(P)){q[P]=de}}break;case\"ssrc-group\":tc(S.ssrcGroup,m);break;case\"rid\":{const[T,C]=_e(m,\" \");S.simulcastParameters.push(new es({rid:T,direction:C}))}break}}});if(!S.iceParams.usernameFragment||!S.iceParams.password){if(S.rtp.muxId&&n&&n.items.includes(S.rtp.muxId)){for(let f=0;f<n.items.length;f++){if(!n.items.includes(f.toString()))continue;const y=i.media[f];if(y.iceParams?.usernameFragment&&y.iceParams.password){S.iceParams={...y.iceParams};break}}}}if(!S.dtlsParams.role){S.dtlsParams=void 0}const p=a(f=>S.rtp.codecs.find(y=>y.payloadType===f),\"findCodec\");c.slice(1).forEach(f=>{if(f.startsWith(\"a=\")){const[y,m]=ec(f);if(y===\"fmtp\"){const[T,C]=_e(m,\" \");const E=p(Number(T));E.parameters=C}else if(y===\"rtcp-fb\"){const[T,C,E]=m.split(\" \");S.rtp.codecs.forEach(P=>{if([\"*\",P.payloadType.toString()].includes(T)){P.rtcpFeedback.push(new Li({type:C,parameter:E}))}})}}})});const o=n?i.media.find(c=>c.rtp.muxId===n.items[0]):void 0;if(n&&o?.port){for(const c of i.media){if(c.port===0&&c.bundleOnly&&c.rtp.muxId&&n.items.includes(c.rtp.muxId))c.port=o.port}}return i}webrtcTrackId(e){if(e.msid?.includes(\" \")){const t=e.msid.split(\" \");for(const s of this.msidSemantic){if(s.semantic===\"WMS\"&&(s.items.includes(t[0])||s.items.includes(\"*\"))){return t[1]}}}return}get string(){const e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host){e.push(`c=${sc(this.host)}`)}e.push(`t=${this.time}`);this.group.forEach(i=>e.push(`a=group:${i.str}`));if(this.extMapAllowMixed){e.push(`a=extmap-allow-mixed`)}this.msidSemantic.forEach(i=>e.push(`a=msid-semantic:${i.str}`));const t=this.media.map(i=>i.toString()).join(\"\");const s=e.join(\"\\r\\n\")+\"\\r\\n\"+t;return s}toJSON(){const e=this.string;if(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type){this.cachedJson=new rc(e,this.type)}return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}};var $t=class{static{a(this,\"MediaDescription\")}constructor(e,t,s,i){this.kind=e;this.port=t;this.profile=s;this.fmt=i;this.msids=[];this.rtcpMux=false;this.bundleOnly=false;this.ssrc=[];this.ssrcGroup=[];this.rtp={codecs:[],headerExtensions:[]};this.sctpMap={};this.iceCandidates=[];this.iceCandidatesComplete=false;this.simulcastParameters=[]}get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){const e=[];e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(t=>t.toString()).join(\" \")}`);if(this.host){e.push(`c=${sc(this.host)}`)}this.iceCandidates.forEach(t=>{e.push(`a=candidate:${Qa(t)}`)});if(this.iceCandidatesComplete){e.push(\"a=end-of-candidates\")}if(this.iceParams?.usernameFragment){e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`)}if(this.iceParams?.password){e.push(`a=ice-pwd:${this.iceParams.password}`)}if(this.iceParams?.iceLite){e.push(`a=ice-lite`)}if(this.iceOptions){e.push(`a=ice-options:${this.iceOptions}`)}if(this.dtlsParams){this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)});e.push(`a=setup:${Mn[this.dtlsParams.role]}`)}if(this.direction){e.push(`a=${this.direction}`)}if(this.rtp.muxId){e.push(`a=mid:${this.rtp.muxId}`)}this.msids.forEach(t=>e.push(`a=msid:${t}`));if(this.rtcpPort&&this.rtcpHost){e.push(`a=rtcp:${this.rtcpPort} ${sc(this.rtcpHost)}`);if(this.rtcpMux){e.push(\"a=rtcp-mux\")}}this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)});this.ssrc.forEach(t=>{ya.forEach(s=>{const i=t[s];if(i!==void 0){e.push(`a=ssrc:${t.ssrc} ${s}:${i}`)}})});this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`);t.rtcpFeedback.forEach(s=>{let i=s.type;if(s.parameter)i+=` ${s.parameter}`;e.push(`a=rtcp-fb:${t.payloadType} ${i}`)});if(t.parameters){e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}});Object.keys(this.sctpMap).forEach(t=>{const s=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${s}`)});if(this.sctpPort){e.push(`a=sctp-port:${this.sctpPort}`)}if(this.sctpCapabilities){e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`)}this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`));if(this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{e.push(`a=rid:${n.rid} ${n.direction}`)});let t=`a=simulcast:`;const s=this.simulcastParameters.filter(n=>n.direction===\"recv\");if(s.length){t+=`recv ${s.map(n=>n.rid).join(\";\")} `}const i=this.simulcastParameters.filter(n=>n.direction===\"send\");if(i.length){t+=`send ${i.map(n=>n.rid).join(\";\")}`}e.push(t)}return e.join(\"\\r\\n\")+\"\\r\\n\"}};var ft=class{static{a(this,\"GroupDescription\")}constructor(e,t){this.semantic=e;this.items=t}get str(){return`${this.semantic} ${this.items.join(\" \")}`}};function Za(r){const e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error(\"exception\");return e[2]}a(Za,\"ipAddressFromSdp\");function sc(r){const e=(0,Vu.isIPv4)(r)?4:6;return`IN IP${e} ${r}`}a(sc,\"ipAddressToSdp\");function Qa(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;if(r.relatedAddress!=void 0){e+=` raddr ${r.relatedAddress}`}if(r.relatedPort!=void 0){e+=` rport ${r.relatedPort}`}if(r.tcpType!=void 0){e+=` tcptype ${r.tcpType}`}if(r.generation!=void 0){e+=` generation ${r.generation}`}if(r.ufrag!=void 0){e+=` ufrag ${r.ufrag}`}return e}a(Qa,\"candidateToSdp\");function Bm(r){const e=[];const t=[];let s=r.split(\"\\r\\n\");if(s.length===1){s=r.split(\"\\n\")}s.forEach(i=>{if(i.startsWith(\"m=\")){t.push([i])}else if(t.length>0){t[t.length-1].push(i)}else{e.push(i)}});return[e,t]}a(Bm,\"groupLines\");function ec(r){if(r.includes(\":\")){const e=_e(r.slice(2),\":\");return[e[0],e[1]]}else{return[r.slice(2),void 0]}}a(ec,\"parseAttr\");function tc(r,e,t=s=>s.toString()){const s=e.split(\" \");if(s.length>0){r.push(new ft(s[0],s.slice(1).map(t)))}}a(tc,\"parseGroup\");function Xa(r){const e=te.fromSdp(r);const t=nt(e);return t}a(Xa,\"candidateFromSdp\");var rc=class{static{a(this,\"RTCSessionDescription\")}constructor(e,t){Object.defineProperties(this,{sdp:{configurable:true,enumerable:true,value:e,writable:false},type:{configurable:true,enumerable:true,value:t,writable:false}})}static isThis(e){if(typeof e?.sdp===\"string\")return true}toSdp(){return{sdp:this.sdp,type:this.type}}};function ic(r,e){const t=\"-\";const s=(0,$u.randomBytes)(8).readBigUInt64BE(0).toString().slice(0,8);const i=0;e.origin=`${t} ${s} ${i} IN IP4 0.0.0.0`;e.msidSemantic.push(new ft(\"WMS\",[\"*\"]));e.type=r}a(ic,\"addSDPHeader\");function Ie(r){const e={};r.split(\";\").forEach(t=>{if(t.length===0)return;if(t.includes(\"=\")){const[s,i]=_e(t,\"=\");if(Dh.includes(s)){e[s]=Number(i)}else{e[s]=i}}else if(t.includes(\":\")){const[s,i]=t.split(\":\");e[s]=Number.isNaN(Number(i))?i:Number(i)}else{e[t]=void 0}});return e}a(Ie,\"codecParametersFromString\");var sr=class{static{a(this,\"SsrcDescription\")}constructor(e){Object.assign(this,e)}};function mi(r){return r.name.toLowerCase()}a(mi,\"codecName\");function go(r,e){return r==void 0||e==void 0||r===e}a(go,\"optionalEqual\");function Yu(r){const e=Ie(r.parameters??\"\");return{packetizationMode:e[\"packetization-mode\"],profileLevelId:e[\"profile-level-id\"]?.toString().toLowerCase()}}a(Yu,\"h264Parameters\");function rr(r,e){if(r.mimeType.toLowerCase()!==e.mimeType.toLowerCase()){return false}if(r.clockRate!==e.clockRate)return false;if(!go(r.channels,e.channels))return false;if(mi(r)!==\"h264\")return true;const t=Yu(r);const s=Yu(e);if(!go(t.packetizationMode,s.packetizationMode)){return false}return go(t.profileLevelId,s.profileLevelId)}a(rr,\"isCodecCompatible\");function Vt(r){return[\"rtx\",\"red\"].includes(mi(r))}a(Vt,\"isAuxiliary\");function So(r,e,t){if(r!==\"audio\"||e==void 0||mi(e)!==\"red\"){return e}const[s]=nc(e);return t.find(i=>!Vt(i)&&i.payloadType===s)??t.find(i=>!Vt(i))??e}a(So,\"deliveredTrackCodec\");function Qu(r,e){return r.some(t=>!Vt(t)&&e.some(s=>s.mimeType.toLowerCase()===t.mimeType.toLowerCase()))}a(Qu,\"hasCommonPrimaryMimeType\");function nc(r){const e=r.parameters??\"\";if(mi(r)===\"rtx\"){const t=Number(Ie(e).apt);return Number.isNaN(t)?[]:[t]}if(mi(r)===\"red\"){return e.split(\"/\").map(Number).filter(t=>!Number.isNaN(t))}return[]}a(nc,\"referencedPayloadTypes\");function Xu(r,e){const t=new Set(e.map(i=>i.payloadType));const s=r.filter(i=>{if(!Vt(i))return false;const n=nc(i);return n.length>0&&n.every(o=>t.has(o))});return r.filter(i=>e.includes(i)||s.includes(i))}a(Xu,\"withAuxiliaryCodecs\");function Ju(r,e){const t=r.filter(s=>!Vt(s)&&e.some(i=>rr(i,s)));return Xu(r,t)}a(Ju,\"intersectCodecs\");function Lm(r,e){return r.mimeType.toLowerCase()===e.mimeType.toLowerCase()&&go(r.clockRate,e.clockRate)}a(Lm,\"matchesPreference\");function Zu(r,e){if(e==void 0)return r;const t=e.flatMap(c=>{const d=r.find(h=>Lm(h,c));return d?[d]:[]});const s=[...new Set(t)];const i=new Set(s.filter(Vt).flatMap(nc));const n=r.filter(c=>!Vt(c)&&(s.includes(c)||i.has(c.payloadType)));const o=Xu(r,n);return[...s.filter(c=>o.includes(c)),...o.filter(c=>!s.includes(c))]}a(Zu,\"applyCodecPreferences\");function oc(r,e,t){return Zu(e==void 0?r:Ju(r,e),t)}a(oc,\"resolveCodecs\");function pi(r){return r?.map(e=>e.mimeType).join(\", \")||\"(none)\"}a(pi,\"list\");function Yt(r){const{kind:e,configured:t,source:s,preferences:i}=r;const n=s==void 0?t:Ju(t,s);if(s!=void 0&&n.length===0){throw _(\"NotSupportedError\",`Track codec ${pi(s)} is not supported by this RTCPeerConnection. Configured ${e} codecs: ${pi(t)}`)}const o=Zu(n,i);if(o.length===0){throw _(\"NotSupportedError\",`No codec remains after applying codec preferences. Source codecs: ${pi(s)} Configured codecs: ${pi(t)} Preferred codecs: ${pi(i)}`)}return o}a(Yt,\"assertCodecsSupported\");function ac(){return new Te({uri:M.sdesMid})}a(ac,\"useSdesMid\");function cc(){return new Te({uri:M.transportWideCC})}a(cc,\"useTransportWideCC\");function dc(){return new Te({uri:M.absSendTime})}a(dc,\"useAbsSendTime\");function el(){return new Te({uri:M.audioLevelIndication})}a(el,\"useAudioLevelIndication\");var sl=require(\"node:crypto\");var wo=require(\"node:timers/promises\");var Dm=b(\"webrtc/peer/media/receiver/nack\");var tl=30*5;var yo=class{static{a(this,\"NackHandler\")}constructor(e){this.receiver=e;this.newEstSeqNum=0;this._lost={};this.onPacketLost=new w;this.retryCount=10;this.closed=false;this.sendNack=()=>new Promise((t,s)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){const i=new Ge({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers});const n=new Z({feedback:i});this.receiver.dtlsTransport.sendRtcp([n]).then(t).catch(s);this.updateRetryCount();this.onPacketLost.execute(i)}})}get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t;if(this.nackLoop||this.closed){return}this.nackLoop=setInterval(ye(async()=>{await this.sendNack();if(!Object.keys(this._lost).length){clearInterval(this.nackLoop);this.nackLoop=void 0}},s=>Dm(\"failed to send nack\",s)),5)}removeLost(e){delete this._lost[e]}addPacket(e){const{sequenceNumber:t,ssrc:s}=e.header;this.mediaSourceSsrc=s;if(this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===j(this.newEstSeqNum,1)){this.newEstSeqNum=t}else if(t>j(this.newEstSeqNum,1)){for(let i=j(this.newEstSeqNum,1);i<t;i=j(i,1)){this.setLost(i,1)}this.newEstSeqNum=t;this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>tl){this._lost=Object.entries(this._lost).slice(-tl).reduce((e,[t,s])=>{e[t]=s;return e},{})}}close(){this.closed=true;clearInterval(this.nackLoop);this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{const t=this._lost[e]++;if(t>this.retryCount){this.removeLost(e);return e}})}};var To=class{static{a(this,\"StreamStatistics\")}constructor(e){this.cycles=0;this.packets_received=0;this.bytesReceived=0;this.headerBytesReceived=0;this.jitter_q4=0;this.expected_prior=0;this.received_prior=0;this.clockRate=e}add(e,t=Date.now()/1e3){const s=this.max_seq==void 0||Ei(e.header.sequenceNumber,this.max_seq);this.packets_received++;this.bytesReceived+=e.payload.length;this.headerBytesReceived+=e.header.serializeSize;this.lastPacketReceivedTimestamp=J();if(this.base_seq==void 0){this.base_seq=e.header.sequenceNumber}if(s){const i=at(t*this.clockRate);if(this.max_seq!=void 0&&e.header.sequenceNumber<this.max_seq){this.cycles+=1<<16}this.max_seq=e.header.sequenceNumber;if(e.header.timestamp!==this.last_timestamp&&this.packets_received>1){const n=Math.abs(i-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=i;this.last_timestamp=e.header.timestamp}}get fraction_lost(){const e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;const t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;const s=e-t;if(e==0||s<=0){return 0}else{return Math.floor((s<<8)/e)}}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){const e=this.packets_expected-this.packets_received;return e<0?0:e}};var ir=b(\"webrtc/peer/media/rtpReceiver\");var nr=class{static{a(this,\"RTCRtpReceiver\")}get codecArray(){this.sortedCodecs??=Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType);return this.sortedCodecs}constructor(e,t,s){this.config=e;this.kind=t;this.rtcpSsrc=s;this.codecs={};this.ssrcByRtx={};this.nack=new yo(this);this.audioRedHandler=new zi;this.type=\"receiver\";this.uuid=(0,sl.randomUUID)().toString();this.tracks=[];this.trackBySSRC={};this.trackByRID={};this.lastSRtimestamp={};this.receiveLastSRTimestamp={};this.onPacketLost=this.nack.onPacketLost;this.onRtcp=new w;this.stopped=false;this.remoteStreamIds=[];this.rtcpRunning=false;this.rtcpCancel=new AbortController;this.remoteStreams={};this.senderReportsReceivedBySsrc={};this.remoteTimestampsBySsrc={};this.remotePacketCountBySsrc={};this.remoteOctetCountBySsrc={};this.nackCountBySsrc={};this.pliCountBySsrc={};this.handleRtpBySsrc=(i,n)=>{const o=this.trackBySSRC[i.header.ssrc];this.handleRTP(i,n,o)};this.handleRtpByRid=(i,n,o)=>{const c=this.trackByRID[n];if(!this.trackBySSRC[i.header.ssrc]){this.trackBySSRC[i.header.ssrc]=c}this.handleRTP(i,o,c)};this.defaultTrack=new Be({kind:t,remote:true});this.onPacketLost.subscribe(i=>{this.nackCountBySsrc[i.mediaSourceSsrc]=(this.nackCountBySsrc[i.mediaSourceSsrc]??0)+1})}get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===\"nack\")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===rn().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===Bt().type)}prepareReceive(e){e.codecs.forEach(t=>{this.codecs[t.payloadType]=t});this.sortedCodecs=void 0;e.encodings.forEach(t=>{if(t.rtx){this.ssrcByRtx[t.rtx.ssrc]=t.ssrc}})}resyncCodecs(e){for(const s of Object.keys(this.codecs)){delete this.codecs[Number(s)]}this.sortedCodecs=void 0;for(const s of Object.keys(this.ssrcByRtx)){delete this.ssrcByRtx[Number(s)]}this.prepareReceive(e);const t=So(this.kind,e.codecs[0],e.codecs);if(t){for(const s of this.tracks){s.codec=t}}}addTrack(e){const t=this.tracks.find(s=>{if(s.rid){return s.rid===e.rid}if(s.ssrc){return s.ssrc===e.ssrc}});if(t){return false}this.tracks.push(e);if(e.ssrc){this.trackBySSRC[e.ssrc]=e}if(e.rid){this.trackByRID[e.rid]=e}return true}stop(){this.stopped=true;this.rtcpRunning=false;this.rtcpCancel.abort();this.nack.close()}endTracks(){for(const e of[...this.tracks,this.defaultTrack]){e.stop()}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,wo.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=Object.entries(this.remoteStreams).map(([s,i])=>{let n=0,o=0;if(this.lastSRtimestamp[s]){n=this.lastSRtimestamp[s];const c=Ys()-this.receiveLastSRTimestamp[s];if(c>0&&c<65536){o=at(c*65536)}}return new wt({ssrc:Number(s),fractionLost:i.fraction_lost,packetsLost:i.packets_lost,highestSequence:i.max_seq,jitter:i.jitter,lsr:n,dlsr:o})});const t=new be({ssrc:this.rtcpSsrc,reports:e});try{if(this.config.debug.receiverReportDelay){await(0,wo.setTimeout)(this.config.debug.receiverReportDelay)}await this.dtlsTransport.sendRtcp([t])}catch(s){ir(\"sendRtcp failed\",s);await(0,wo.setTimeout)(500+Math.random()*1e3)}}}catch(e){ir(\"rtcp loop ended\",e)}}getInboundRtpStatsId(e){return D(\"inbound-rtp\",e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return D(\"remote-outbound-rtp\",e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e?true:t===e).filter(t=>t.ssrc).map(t=>this.getInboundRtpStatsId(t))}collectStats(e){const t=[];const s=this.dtlsTransport?D(\"transport\",this.dtlsTransport.id):void 0;const i=this.codecArray[0];const n=new Set;for(const o of this.tracks){if(!o.ssrc)continue;const c=this.remoteStreams[o.ssrc];const d=this.remoteTimestampsBySsrc[o.ssrc]!==void 0;const h=this.lastSRtimestamp[o.ssrc]!==void 0||d?this.getRemoteOutboundRtpStatsId(o):void 0;const l=i&&s?$s(s,i.payloadType,o.id??o.uuid):void 0;if(i&&s&&l&&!n.has(l)){n.add(l);const g={type:\"codec\",id:l,timestamp:e,payloadType:i.payloadType,transportId:s,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,sdpFmtpLine:i.parameters};t.push(g)}const u={type:\"inbound-rtp\",id:this.getInboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:l,mid:this.sdesMid,trackIdentifier:o.id??o.uuid,packetsReceived:c?.packets_received??0,bytesReceived:c?.bytesReceived??0,headerBytesReceived:c?.headerBytesReceived??0,packetsLost:c?.packets_lost??0,jitter:c?.clockRate?c.jitter/c.clockRate:void 0,lastPacketReceivedTimestamp:c?.lastPacketReceivedTimestamp,remoteId:h,nackCount:this.nackCountBySsrc[o.ssrc]||void 0,pliCount:this.pliCountBySsrc[o.ssrc]||void 0};t.push(u);if(h){const g={type:\"remote-outbound-rtp\",id:this.getRemoteOutboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:u.codecId,localId:u.id,remoteTimestamp:this.remoteTimestampsBySsrc[o.ssrc],reportsSent:this.senderReportsReceivedBySsrc[o.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[o.ssrc],bytesSent:this.remoteOctetCountBySsrc[o.ssrc]};t.push(g)}}return t}async getStats(){const e=J();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return Wt(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){ir(\"pli not supported\",{mediaSsrc:e});return}if(this.stopped){return}ir(\"sendRtcpPLI\",{mediaSsrc:e});const t=new we({feedback:new Fe({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1;await this.dtlsTransport.sendRtcp([t])}catch(s){ir(s)}}handleRtcpPacket(e){switch(e.type){case ue.type:{const t=e;this.lastSRtimestamp[t.ssrc]=ao(t.senderInfo.ntpTimestamp);this.receiveLastSRTimestamp[t.ssrc]=Ys();this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1;this.remoteTimestampsBySsrc[t.ssrc]=qu(t.senderInfo.ntpTimestamp);this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount;this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;const s=this.trackBySSRC[e.ssrc];if(s){s.onReceiveRtcp.execute(e)}}break}this.onRtcp.execute(e)}handleRTP(e,t,s){if(this.stopped){return}const i=this.codecs[e.header.payloadType];if(!i){return}this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new To(i.clockRate);this.remoteStreams[e.header.ssrc].add(e);if(this.twccEnabled){const o=t[M.transportWideCC];if(o!==void 0){this.dtlsTransport.receiverTWCC.handleTWCC(o,e.header.ssrc)}}if(i.name.toLowerCase()===\"rtx\"){const o=this.ssrcByRtx[e.header.ssrc];const c=Ie(i.parameters??\"\");const d=this.codecs[c[\"apt\"]];if(e.payload.length<2)return;e=rd(e,d.payloadType,o);s=this.trackBySSRC[o]}let n;if(i.name.toLowerCase()===\"red\"){n=is.deSerialize(e.payload);if(!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())){return}}if(s?.kind===\"video\"&&this.nackEnabled){this.nack.addPacket(e)}if(s){if(n){if(s.kind===\"audio\"){const o=this.audioRedHandler.push(n,e);for(const c of o){s.onReceiveRtp.execute(c.clone(),t)}}}else{s.onReceiveRtp.execute(e.clone(),t)}}this.runRtcp().catch(o=>ir(\"rtcp failed\",o))}};var gi=b(\"webrtc/peer/media/router\");var bo=class{static{a(this,\"RtpRouter\")}constructor(){this.ssrcTable={};this.ridTable={};this.extIdUriMap={};this.routeRtp=e=>{const t=Vc(e.header.extensions,this.extIdUriMap);let s=this.ssrcTable[e.header.ssrc];const i=t[M.sdesRTPStreamID];if(typeof i===\"string\"){s=this.ridTable[i];if(s){s.latestRid=i;s.handleRtpByRid(e,i,t)}}else if(s){s.handleRtpBySsrc(e,t)}else{s=Object.values(this.ridTable).filter(c=>c instanceof nr).find(c=>c.trackBySSRC[e.header.ssrc]);if(s){gi(\"simulcast register receiver by ssrc\",e.header.ssrc);this.registerRtpReceiver(s,e.header.ssrc);s.handleRtpBySsrc(e,t)}else{}}if(!s){gi(\"ssrcReceiver not found\");return}const n=t[M.sdesMid];if(typeof n===\"string\"){s.sdesMid=n}const o=t[M.repairedRtpStreamId];if(typeof o===\"string\"){s.latestRepairedRid=o}};this.routeRtcp=e=>{const t=[];switch(e.type){case ue.type:{e=e;t.push(this.ssrcTable[e.ssrc])}break;case be.type:{e=e;e.reports.forEach(s=>{t.push(this.ssrcTable[s.ssrc])})}break;case We.type:break;case Z.type:{const s=e;if(s.feedback){t.push(this.ssrcTable[s.feedback.mediaSourceSsrc])}}break;case we.type:{const s=e;switch(s.feedback.count){case Ke.count:{const i=s.feedback;t.push(this.ssrcTable[i.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[s.feedback.mediaSsrc]||this.ssrcTable[s.feedback.senderSsrc])}}break}t.filter(s=>s).forEach(s=>s.handleRtcpPacket(e))}}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){gi(\"registerRtpReceiver\",t);this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){gi(\"registerRtpReceiverBySsrc\",t);t.encodings.filter(s=>s.ssrc!=void 0).forEach((s,i)=>{this.registerRtpReceiver(e.receiver,s.ssrc);e.addTrack(new Be({ssrc:s.ssrc,kind:e.kind,id:e.sender.trackId,remote:true,codec:So(e.kind,t.codecs[i],t.codecs)}));if(s.rtx){this.registerRtpReceiver(e.receiver,s.rtx.ssrc)}});t.headerExtensions.forEach(s=>{this.extIdUriMap[s.id]=s.uri})}registerRtpReceiverByRid(e,t,s){const[i]=s.codecs;gi(\"registerRtpReceiverByRid\",t);e.addTrack(new Be({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:true,codec:i}));this.ridTable[t.rid]=e.receiver}unregisterTransceiver(e){const t=[e.sender,e.receiver];for(const[s,i]of Object.entries(this.ssrcTable)){if(t.includes(i)){delete this.ssrcTable[Number(s)]}}for(const[s,i]of Object.entries(this.ridTable)){if(t.includes(i)){delete this.ridTable[s]}}}};var Si=require(\"node:crypto\");var uc=require(\"node:timers/promises\");var Co=class{static{a(this,\"SDPManager\")}constructor({cname:e,midSuffix:t,bundlePolicy:s,mLineReuse:i}){this.seenMid=new Set;this.cname=e;this.midSuffix=t??false;this.bundlePolicy=s;this.mLineReuse=i??\"compatible\"}get localDescription(){if(!this._localDescription){return void 0}return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription){return void 0}return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(e=>e.direction===\"inactive\")}createMediaDescriptionForTransceiver(e,t){const s=new $t(e.kind,9,\"UDP/TLS/RTP/SAVPF\",e.codecs.map(i=>i.payloadType));s.direction=t;s.msids=e.msids;s.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0};s.rtcpHost=\"0.0.0.0\";s.rtcpPort=9;s.rtcpMux=true;s.ssrc=[new sr({ssrc:e.sender.ssrc,cname:this.cname})];if(e.options.simulcast){s.simulcastParameters=e.options.simulcast.map(i=>new es(i))}if(s.rtp.codecs.find(i=>i.name.toLowerCase()===\"rtx\")){s.ssrc.push(new sr({ssrc:e.sender.rtxSsrc,cname:this.cname}));s.ssrcGroup=[new ft(\"FID\",[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]}this.addTransportDescription(s,e.dtlsTransport);return s}createRejectedMediaDescription(e,t){const s=e.fmt[0]??e.codecs[0]?.payloadType??0;const i=new $t(e.kind,0,e.profile,[s]);i.host=ma;i.direction=\"inactive\";i.rtp={codecs:e.codecs.filter(n=>n.payloadType?.toString()===s.toString()),headerExtensions:[],muxId:e.mid};i.rtcpMux=true;if(t){i.iceParams=t.iceTransport.localParameters;i.dtlsParams=t.localParameters}return i}createMediaDescriptionForSctp(e){const t=new $t(\"application\",ga,\"UDP/DTLS/SCTP\",[\"webrtc-datachannel\"]);t.sctpPort=e.port;t.rtp.muxId=e.mid;t.sctpCapabilities=e.getCapabilities();this.addTransportDescription(t,e.dtlsTransport);return t}addTransportDescription(e,t){const s=t.iceTransport;e.iceCandidates=s.localCandidates;e.iceCandidatesComplete=s.gatheringState===\"complete\";e.iceParams=s.localParameters;e.iceOptions=\"trickle\";e.host=ma;e.port=ga;if(e.direction===\"inactive\"){if(this.mLineReuse===\"aggressive\"){e.port=0}e.msids=[]}if(!e.dtlsParams){e.dtlsParams=t.localParameters;if(!e.dtlsParams.fingerprints){e.dtlsParams.fingerprints=t.localParameters.fingerprints}}}allocateMid(e=\"\"){let t;for(let s=0;;){t=(s++).toString()+e;if(!this.seenMid.has(t))break}this.seenMid.add(t);return t}parseSdp({sdp:e,isLocal:t,signalingState:s,type:i}){const n=ot.parse(e);this.validateDescription({description:n,isLocal:t,signalingState:s,type:i});n.type=i;return n}validateDescription({isLocal:e,signalingState:t,type:s}){if(e){if(s===\"offer\"){if(![\"stable\",\"have-local-offer\"].includes(t))throw _(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}else{if(s===\"offer\"){if(![\"stable\",\"have-remote-offer\",\"have-local-offer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-local-offer\",\"have-remote-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}}buildOfferSdp(e,t){const s=new ot;ic(\"offer\",s);const i=this.findLiveDtlsTransport(e,t);const n=this.currentLocalDescription?.media??[];const o=new Set;n.forEach((c,d)=>{const h=c.rtp.muxId;if(!h){return}if(c.kind===\"application\"){if(!t){throw new Error(\"sctpTransport not found\")}t.mLineIndex=d;s.media.push(this.createMediaDescriptionForSctp(t))}else{const l=e.find(u=>u.mid===h);if(!l){o.add(d);s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:h},i));return}l.mLineIndex=d;if(l.stopping||l.stopped){s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:h},this.liveTransportOr(l.dtlsTransport,i)));return}s.media.push(this.createMediaDescriptionForTransceiver(l,l.direction))}});for(const c of e.filter(d=>!d.stopping&&!d.stopped&&!s.media.find(h=>h.rtp.muxId===d.mid))){if(c.mid==void 0){c.mid=this.allocateMid(this.midSuffix?\"av\":\"\")}const d=this.createMediaDescriptionForTransceiver(c,c.direction);const h=c.mLineIndex;if(h!=void 0&&o.has(h)&&s.media[h]?.kind===c.kind){o.delete(h);s.media[h]=d}else{c.mLineIndex=s.media.length;s.media.push(d)}}if(t&&!s.media.find(c=>c.kind===\"application\")){t.mLineIndex=s.media.length;if(t.mid==void 0){t.mid=this.allocateMid(this.midSuffix?\"dc\":\"\")}s.media.push(this.createMediaDescriptionForSctp(t))}if(this.bundlePolicy!==\"disable\"){const c=s.media.filter(d=>d.port!==0).map(d=>d.rtp.muxId).filter(d=>d);if(c.length){const d=new ft(\"BUNDLE\",rl(c,this.negotiatedBundleTag));s.group.push(d)}}return s}liveTransportOr(e,t){return e&&e.state!==\"closed\"?e:t}findLiveDtlsTransport(e,t){return[...e.filter(s=>!s.stopped&&!s.pendingRejection).map(s=>s.dtlsTransport),t?.dtlsTransport,...e.map(s=>s.dtlsTransport)].find(s=>!!s&&s.state!==\"closed\")}get negotiatedBundleTag(){const e=[this.currentLocalDescription,this.currentRemoteDescription].find(t=>t?.type===\"answer\");return e?.group.find(t=>t.semantic===\"BUNDLE\")?.items[0]}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:s}){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(s)){throw new Error(\"createAnswer failed\")}if(!this._remoteDescription){throw new Error(\"wrong state\")}const i=new ot;ic(\"answer\",i);const n=this._remoteDescription;const o=this.findLiveDtlsTransport(e,t);for(const c of n.media){let d;let h;let l=true;if([\"audio\",\"video\"].includes(c.kind)){const u=e.find(g=>g.mid!=void 0&&g.mid===c.rtp.muxId);if(!u&&c.port!==0){throw new Error(`Transceiver with mid=${c.rtp.muxId} not found`)}if(!u||c.port===0||u.stopped||u.pendingRejection){l=false;d=this.liveTransportOr(u?.dtlsTransport,o);h=this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:c.rtp.muxId},d)}else{h=this.createMediaDescriptionForTransceiver(u,u.stopping?\"inactive\":oo(u.direction,u.offerDirection));d=u.dtlsTransport}}else if(c.kind===\"application\"){if(!t||!t.mid){throw new Error(\"sctpTransport not found\")}h=this.createMediaDescriptionForSctp(t);d=t.dtlsTransport}else{throw new Error(\"invalid kind\")}if(h.dtlsParams&&d){if(d.role===\"auto\"){h.dtlsParams.role=\"client\"}else{h.dtlsParams.role=d.role}}if(l&&c.simulcastParameters&&c.simulcastParameters.length>0){h.simulcastParameters=c.simulcastParameters.map(u=>({...u,direction:u.direction===\"send\"?\"recv\":\"send\"}))}i.media.push(h)}if(this.bundlePolicy!==\"disable\"){i.group.push(...this.buildAnswerBundleGroups(n,i))}return i}buildAnswerBundleGroups(e,t){const s=new Set(t.media.filter(n=>n.port!==0&&n.rtp.muxId).map(n=>n.rtp.muxId));const i=this.negotiatedBundleTag;return e.group.filter(n=>n.semantic===\"BUNDLE\").map(n=>n.items.filter((o,c,d)=>{return s.has(o)&&d.indexOf(o)===c})).filter(n=>n.length>0).map(n=>new ft(\"BUNDLE\",rl(n,i)))}assertRemoteAnswerCodecs(e){if(![\"answer\",\"pranswer\"].includes(e.type)){return}const t=this.pendingLocalDescription;if(!t){return}e.media.forEach((s,i)=>{if(![\"audio\",\"video\"].includes(s.kind)||s.port===0){return}const n=t.media[i];if(!n||n.port===0||n.kind!==s.kind){return}const o=s.rtp.codecs.some(c=>c.name.toLowerCase()!==\"rtx\"&&n.rtp.codecs.some(d=>d.mimeType.toLowerCase()===c.mimeType.toLowerCase()));if(!o){throw _(\"InvalidAccessError\",`No common codec for m-line ${i} (mid=${s.rtp.muxId}) in remote ${e.type}`)}})}assertBundlePreserved(e){if(e.type!==\"offer\"||this.bundlePolicy===\"disable\"){return}const t=[this.currentLocalDescription,this.currentRemoteDescription].find(i=>i?.type===\"answer\")?.group.filter(i=>i.semantic===\"BUNDLE\")??[];const s=e.group.filter(i=>i.semantic===\"BUNDLE\");for(const i of t){let n;for(const o of i.items){const c=e.media.find(h=>h.rtp.muxId===o);if(!c||c.port===0){continue}const d=s.find(h=>h.items.includes(o));if(!d){throw _(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be preserved by the remote offer`)}n??=d;if(d!==n){throw _(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be split into another BUNDLE group by the remote offer`)}}}}setLocalDescription(e){if(e.type===\"offer\"||e.type===\"pranswer\"){this.pendingLocalDescription=e;return}this.currentLocalDescription=e;if(this.pendingRemoteDescription){this.currentRemoteDescription=this.pendingRemoteDescription}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type){throw new Error(\"invalid sessionDescription\")}if(e.type===\"rollback\"){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot rollback remote description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0;return}if(!e.sdp){throw new Error(\"invalid sessionDescription\")}const s=this.parseSdp({sdp:e.sdp,isLocal:false,signalingState:t,type:e.type});this.assertRemoteAnswerCodecs(s);this.assertBundlePreserved(s);if(s.type===\"offer\"||s.type===\"pranswer\"){this.pendingRemoteDescription=s}else{if(this.pendingLocalDescription){this.currentLocalDescription=this.pendingLocalDescription}this.currentRemoteDescription=s;this.pendingRemoteDescription=void 0;this.pendingLocalDescription=void 0}return s}rollbackLocalDescription(e){if(![\"have-local-offer\",\"have-local-pranswer\"].includes(e)){throw _(\"InvalidStateError\",\"Cannot rollback local description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){const e=this._remoteDescription;if(!e){return void 0}const t=e.group.find(s=>s.semantic===\"BUNDLE\"&&this.bundlePolicy!==\"disable\");return t}setLocal(e,t,s){const i=new Map(t.map(c=>[c?.mLineIndex,c]));const n=t.find(c=>c?.dtlsTransport)?.dtlsTransport??s?.dtlsTransport;e.media.forEach((c,d)=>{if(![\"audio\",\"video\"].includes(c.kind)){return}const h=t.find(g=>g?.mid!=void 0&&g.mid===c.rtp.muxId)??i.get(d);if(c.port===0){const g=h&&!h.stopping&&!h.stopped&&!h.pendingRejection;if(!g){return}}const l=h?.dtlsTransport??n;if(!l){throw new Error(`dtls transport not found for media index ${d}`)}const u=c.port;this.addTransportDescription(c,l);if(u===0){c.port=0}});const o=e.media.find(c=>c.kind===\"application\");if(s&&o){this.addTransportDescription(o,s.dtlsTransport)}this.setLocalDescription(e)}};function rl(r,e){if(!e||!r.includes(e)){return r}return[e,...r.filter(t=>t!==e)]}a(rl,\"orderBundleMids\");var Qt=b(\"webrtc/peer/media/rtpSender\");var il=128;var hc=256;var nl=.85;function Nm(r){if(r===true){return{enabled:true,maxLength:hc}}if(r==void 0||r===false){return{enabled:false,maxLength:hc}}const e=typeof r.maxLength===\"number\"&&Number.isFinite(r.maxLength)&&r.maxLength>=1?Math.floor(r.maxLength):hc;return{enabled:r.enabled??true,maxLength:e}}a(Nm,\"resolvePendingRtpOptions\");function Mm(r,e,t,s,i){return{seqOffset:j(j(r,1),-t),timestampOffset:Ae(Ae(e,i),-s)}}a(Mm,\"freezeRtpContinuityOffsets\");var Eo=class{static{a(this,\"RTCRtpSender\")}constructor(e,t={}){this.trackOrKind=e;this.type=\"sender\";this.ssrc=(0,Si.randomBytes)(4).readUInt32BE(0);this.rtxSsrc=(0,Si.randomBytes)(4).readUInt32BE(0);this.trackId=(0,Si.randomUUID)().toString();this.onReady=new w;this.onRtcp=new w;this.onPictureLossIndication=new w;this.onGenericNack=new w;this.onStreamsChanged=new w;this.rtxSequenceNumber=_o();this._redDistance=2;this.redEncoder=new Hi(this._redDistance);this.headerExtensions=[];this.sendEncodings=[{}];this.rtpTimestamp=0;this.octetCount=0;this.packetCount=0;this.headerBytesSent=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.retransmittedPacketsSent=0;this.retransmittedBytesSent=0;this.nackCount=0;this.pliCount=0;this.firCount=0;this.receiverEstimatedMaxBitrate=0n;this.timestampOffset=0;this.seqOffset=0;this.rtpContinuityPending=false;this.pendingTimestampStep=1;this.rtpCache=[];this.pendingRtp=[];this.drainingPendingRtp=false;this.negotiatedCodecs=[];this.dtlsDisposer=[];this.track=null;this.streamIds=[];this.stopped=false;this.rtcpRunning=false;this.rtcpCancel=new AbortController;const s=Nm(t.pendingRtp);this.pendingRtpEnabled=s.enabled;this.pendingRtpMaxLength=s.maxLength;this.kind=typeof this.trackOrKind===\"string\"?this.trackOrKind:this.trackOrKind.kind;if(typeof e!==\"string\"){this.registerTrack(e)}}get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){if(this.dtlsTransport){this.dtlsDisposer.forEach(t=>t())}this.dtlsTransport=e;this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"connected\"){this.onReady.execute();void this.drainPendingRtp()}}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e;this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname;this.mid=e.muxId;this.headerExtensions=e.headerExtensions;this.rtpStreamId=e.rtpStreamId??this.rtpStreamId;this.repairedRtpStreamId=e.repairedRtpStreamId;this.negotiatedCodecs=[...e.codecs];this.selectCodec(this.track?Le(this.track):void 0);if(this.track){this.track.codec=this.codec}void this.drainPendingRtp()}selectCodec(e){const t=this.negotiatedCodecs;const s=a(o=>{if(o?.name.toLowerCase()!==\"red\")return o;const c=Number((o.parameters??\"\").split(\"/\")[0]);return t.find(d=>![\"red\",\"rtx\"].includes(d.name.toLowerCase())&&d.payloadType===c)},\"primaryOf\");const i=a(o=>{const c=s(o);return!!c&&(!e||e.some(d=>rr(d,c)))},\"compatible\");const n=t.find(o=>o.name.toLowerCase()!==\"rtx\")??t[0];this.codec=t.find(o=>o.name.toLowerCase()!==\"rtx\"&&i(o))??n;this.sendPrimaryCodec=s(this.codec);this.rtxPayloadType=void 0;this.redRedundantPayloadType=void 0;t.forEach(o=>{const c=Ie(o.parameters??\"\");if(o.name.toLowerCase()===\"rtx\"&&this.sendPrimaryCodec?.payloadType===c[\"apt\"]){this.rtxPayloadType=o.payloadType}});if(this.codec?.name.toLowerCase()===\"red\"&&this.sendPrimaryCodec!=void 0){this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType}}canSendRtp(){return!this.stopped&&this.dtlsTransport?.state===\"connected\"&&!!this.codec}settlePendingRtp(e,t){if(t==void 0){e.resolve();return}e.reject(t)}discardPendingRtp(){const e=this.pendingRtp.splice(0);for(const t of e){this.settlePendingRtp(t)}}enqueuePendingRtp(e,t,s){const i=Buffer.isBuffer(e)?W.deSerialize(e):e.clone();this.pendingRtp.push({packet:i,resolve:t,reject:s});while(this.pendingRtp.length>this.pendingRtpMaxLength){const n=this.pendingRtp.shift();if(n){this.settlePendingRtp(n)}}}async drainPendingRtp(){if(this.drainingPendingRtp){return}this.drainingPendingRtp=true;try{while(this.pendingRtp.length>0&&this.canSendRtp()){const e=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(e);continue}try{await this.dispatchRtp(e.packet);this.settlePendingRtp(e)}catch(t){this.settlePendingRtp(e,t)}}}finally{this.drainingPendingRtp=false}if(this.pendingRtp.length>0&&this.canSendRtp()){await this.drainPendingRtp()}}registerTrack(e){if(e.stopped)throw new Error(\"track is ended\");Et(e);if(this.disposeTrack){this.disposeTrack()}e.id=this.trackId;const{unSubscribe:t}=e.onReceiveRtp.subscribe(ye((i,n)=>e.remote?this.sendRtp(this.relayedRtp(i,n),true):this.sendRtp(i),i=>Qt(\"send rtp failed\",i)));const{unSubscribe:s}=e.onSourceChanged.subscribe(i=>{this.replaceRTP(i)});this.track=e;this.disposeTrack=()=>{t();s()};if(this.codec){e.codec=this.codec}}relayedRtp(e,t={}){const s=e.clone();s.header.extensions=this.headerExtensions.flatMap(i=>{switch(i.uri){case M.audioLevelIndication:{const n=t[i.uri];return n?[{id:i.id,payload:Buffer.from([(n.v?128:0)|n.level&127])}]:[]}case M.videoOrientation:{const n=t[i.uri];return n?[{id:i.id,payload:Buffer.from([n.c<<3|n.f<<2|n.r1<<1|n.r0])}]:[]}default:return[]}});return s}setStreams(e=[]){const t=[...new Set(e.map(i=>i.id))];const s=t.join(\"\\n\")!==(this.streamIds??[]).join(\"\\n\");this.streamIds=t;if(s)this.onStreamsChanged.execute()}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(s=>({...s})):[{}];const t=this.sendEncodings.find(s=>typeof s.rid===\"string\")?.rid;if(typeof t===\"string\"){this.rtpStreamId=t}}async replaceTrack(e){if(e===null){this.detachTrack();return}if(e.stopped)throw new Error(\"track is ended\");Et(e);const t=Le(e);if(this.sendPrimaryCodec!=void 0&&t!=void 0&&!this.negotiatedCodecs.some(s=>![\"red\",\"rtx\"].includes(s.name.toLowerCase())&&t.some(i=>rr(i,s)))){throw _(\"InvalidModificationError\",`Track codec ${t.map(s=>s.mimeType).join(\", \")} is incompatible with negotiated codecs ${this.negotiatedCodecs.map(s=>s.mimeType).join(\", \")}`)}if(this.negotiatedCodecs.length)this.selectCodec(t);if(this.sequenceNumber!=void 0){this.scheduleRtpContinuity()}this.registerTrack(e);Qt(\"replaceTrack\",\"ssrc\",e.ssrc,\"rid\",e.rid)}detachTrack(){this.rtpContinuityPending=false;this.discardPendingRtp();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}this.track=null}stop({keepTrack:e=false}={}){this.stopped=true;this.rtpContinuityPending=false;this.discardPendingRtp();this.rtcpRunning=false;this.rtcpCancel.abort();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}if(!e){this.track=null}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,uc.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=this.sentAtEpochMs===void 0?0n:zu(this.sentAtEpochMs);const t=[new ue({ssrc:this.ssrc,senderInfo:new wr({ntpTimestamp:e,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=ao(e);this.lastSentSRTimestamp=Ys();if(this.cname){t.push(new We({chunks:[new yr({source:this.ssrc,items:[new Tr({type:1,text:this.cname})]})]}))}try{await this.dtlsTransport.sendRtcp(t)}catch(s){Qt(\"sendRtcp failed\",s);await(0,uc.setTimeout)(500+Math.random()*1e3)}}}catch(e){Qt(\"rtcp loop ended\",e)}}async sendRtp(e,t=false){if(this.stopped){return}if(!this.pendingRtpEnabled){if(!this.canSendRtp()){return}await this.dispatchRtp(e,t);return}await new Promise((s,i)=>{this.enqueuePendingRtp(e,s,i);void this.drainPendingRtp()})}replaceRTP(e,t=false,s=1){this.scheduleRtpContinuity(s);Qt(\"replaceRTP\",this.sequenceNumber,e.sequenceNumber,t,s)}scheduleRtpContinuity(e=1){this.rtpContinuityPending=true;this.pendingTimestampStep=e;this.rtpCache=[]}async dispatchRtp(e,t=false){if(!this.canSendRtp()){return}const s=this.codec;if(!s){return}e=Buffer.isBuffer(e)?W.deSerialize(e):t?e:e.clone();const{header:i,payload:n}=e;const o=i.sequenceNumber;const c=i.timestamp;if(this.rtpContinuityPending){if(this.sequenceNumber!=void 0&&this.timestamp!=void 0){const p=Mm(this.sequenceNumber,this.timestamp,o,c,this.pendingTimestampStep);this.seqOffset=p.seqOffset;this.timestampOffset=p.timestampOffset}this.rtpContinuityPending=false;this.pendingTimestampStep=1}i.ssrc=this.ssrc;i.payloadType=s.payloadType;i.timestamp=Ae(i.timestamp,this.timestampOffset);i.sequenceNumber=j(i.sequenceNumber,this.seqOffset);this.timestamp=i.timestamp;this.sequenceNumber=i.sequenceNumber;const d=performance.timeOrigin+performance.now();let h;const l=[];for(const p of this.headerExtensions){let f;switch(p.uri){case M.sdesMid:if(this.mid)f=Yc(this.mid);break;case M.sdesRTPStreamID:if(this.rtpStreamId)f=Qc(this.rtpStreamId);break;case M.repairedRtpStreamId:if(this.repairedRtpStreamId)f=Xc(this.repairedRtpStreamId);break;case M.transportWideCC:h=this.nextTransportSequenceNumber();f=Ko(h);break;case M.absSendTime:f=Wa(d);break}if(f)l.push({id:p.id,payload:f})}for(const p of i.extensions){let f;for(const y of l){if(y.id===p.id){f=y;break}}if(f){f.payload=p.payload}else{l.push(p)}}for(let p=1;p<l.length;p++){if(l[p-1].id>l[p].id){l.sort((f,y)=>f.id-y.id);break}}i.extensions=l;this.sentAtEpochMs=d;this.rtpTimestamp=i.timestamp;this.octetCount+=n.length;this.headerBytesSent+=i.serializeSize;this.packetCount=Ae(this.packetCount,1);this.rtpCache[i.sequenceNumber%il]=e;let u=n;if(this.redRedundantPayloadType){this.redEncoder.push({block:u,timestamp:i.timestamp,blockPT:this.redRedundantPayloadType});const p=this.redEncoder.build();u=p.serialize()}const g=Vs();const S=await this.dtlsTransport.sendRtp(u,i);if(!this.rtcpRunning&&!this.stopped)this.runRtcp().catch(p=>Qt(\"rtcp failed\",p));if(h!==void 0){this.packetSent(h,S,g)}}nextTransportSequenceNumber(){this.dtlsTransport.transportSequenceNumber=j(this.dtlsTransport.transportSequenceNumber,1);return this.dtlsTransport.transportSequenceNumber}packetSent(e,t,s){const i={wideSeq:e,size:t,sendingAtMs:s,sentAtMs:Vs()};this.dtlsTransport.senderBWE.rtpPacketSent(i)}async resendRtp(e){let t;const s=e.header.extensions.map(c=>{const d=this.headerExtensions.find(h=>h.id===c.id)?.uri;switch(d){case M.transportWideCC:t=this.nextTransportSequenceNumber();return{id:c.id,payload:Ko(t)};case M.absSendTime:return{id:c.id,payload:Wa(performance.timeOrigin+performance.now())};default:return c}});let i=new W(new ee({...e.header,extensions:s}),e.payload);if(this.rtxPayloadType!=void 0){i=id(i,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc);this.rtxSequenceNumber=j(this.rtxSequenceNumber,1)}this.retransmittedPacketsSent++;this.retransmittedBytesSent+=i.payload.length;this.headerBytesSent+=i.header.serializeSize;const n=Vs();const o=await this.dtlsTransport.sendRtp(i.payload,i.header);if(t!==void 0){this.packetSent(t,o,n)}}handleRtcpPacket(e){switch(e.type){case ue.type:case be.type:{const t=e;t.reports.filter(s=>s.ssrc===this.ssrc).forEach(s=>{this.remotePacketsLost=s.packetsLost;this.remoteFractionLost=s.fractionLost/256;if(this.lastSRtimestamp===s.lsr&&s.dlsr){if(this.lastSentSRTimestamp){const i=Ys()-this.lastSentSRTimestamp-s.dlsr/65536;this.totalRoundTripTime+=i;this.roundTripTimeMeasurements++;if(this.rtt===void 0){this.rtt=i}else{this.rtt=nl*this.rtt+(1-nl)*i}}}})}break;case Z.type:{const t=e;switch(t.feedback.count){case Ge.count:{const s=t.feedback;this.nackCount++;s.lost.forEach(ye(async i=>{const n=this.rtpCache[i%il];if(n&&n.header.sequenceNumber===i){await this.resendRtp(n)}},i=>Qt(\"retransmission failed\",i)));this.onGenericNack.execute(s)}break}}break;case we.type:{const t=e;switch(t.feedback.count){case Ke.count:{const s=t.feedback;this.receiverEstimatedMaxBitrate=s.bitrate}break;case Fe.count:{this.pliCount++;this.onPictureLossIndication.execute()}break}}break}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){if(e.encodings){this.setSendEncodings(e.encodings)}}get outboundRtpStatsId(){return D(\"outbound-rtp\",this.trackId)}get mediaSourceStatsId(){return D(\"media-source\",this.trackId)}get remoteInboundRtpStatsId(){return D(\"remote-inbound-rtp\",this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){const t=[];const s=this.dtlsTransport?D(\"transport\",this.dtlsTransport.id):void 0;const i=this.codec&&s?$s(s,this.codec.payloadType,this.trackId):void 0;const n={type:\"outbound-rtp\",id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:i,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};t.push(n);if(this.track){const o={type:\"media-source\",id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(o)}if(this.codec&&s){const o={type:\"codec\",id:i,timestamp:e,payloadType:this.codec.payloadType,transportId:s,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(o)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){const o={type:\"remote-inbound-rtp\",id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:n.codecId,localId:n.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(o)}return t}async getStats(){const e=J();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return Wt(t,this.getStatsRootIds())}};var ol=b(\"webrtc/peer/transceiverManager\");function Om(r){if(!r||r.length<2){return void 0}const e=r.map(t=>t.rid).filter(t=>typeof t===\"string\"&&t.length>0);if(e.length<2){return void 0}return e.map(t=>({rid:t,direction:\"send\"}))}a(Om,\"simulcastFromSendEncodings\");var Ro=class{static{a(this,\"TransceiverManager\")}constructor(e,t,s){this.cname=e;this.config=t;this.router=s;this.transceivers=[];this.watched=new WeakSet;this.stableState=new Map;this.onTransceiverAdded=new w;this.onRemoteTransceiverAdded=new w;this.onTrack=new w;this.onNegotiationNeeded=new w}getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.watchTransceiver(e);this.transceivers.push(e)}replaceTransceiver(e,t){this.watchTransceiver(e);this.transceivers[t]=e}unwatchTransceiver(e){this.watched.delete(e);e.onRelease.allUnsubscribe();e.onStopRequested.allUnsubscribe();e.onDirectionChanged.allUnsubscribe();e.sender.onStreamsChanged.allUnsubscribe()}watchTransceiver(e){if(this.watched.has(e)){return}this.watched.add(e);e.onRelease.subscribe(()=>{this.router.unregisterTransceiver(e)});e.onStopRequested.subscribe(()=>{if(!e.stopped){this.onNegotiationNeeded.execute()}});e.onDirectionChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()});e.sender.onStreamsChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(e){return this.transceivers.find(t=>t.stopped&&t.kind===e&&t.mLineIndex!=void 0&&!this.transceivers.some(s=>s!==t&&s.mLineIndex===t.mLineIndex))}takeOverMLine(e,t){const s=this.transceivers.indexOf(e);t.mLineIndex=e.mLineIndex;e.mid=null;e.mLineIndex=void 0;this.unwatchTransceiver(e);this.replaceTransceiver(t,s)}associateMLine(e,t){const s=this.transceivers.find(i=>i!==e&&i.stopped&&i.mLineIndex===t);if(!s){return}this.transceivers.splice(this.transceivers.indexOf(e),1);this.takeOverMLine(s,e)}releaseUnassociatedReservations(e,t){for(const s of this.transceivers){if(!e.has(s)&&s.mid==null&&s.mLineIndex!=void 0&&s.mLineIndex<t){s.mLineIndex=void 0}}}addTransceiver(e,t,s={},{remoteMLineIndex:i}={}){const n=typeof e===\"string\"?e:e.kind;const o=s.direction||\"sendrecv\";if(typeof e!==\"string\"){Et(e);Yt({kind:n,configured:this.filterCodecsByDirection(n,o),source:Le(e),preferences:void 0})}const c=new Eo(e,{pendingRtp:this.config.pendingRtp});const d=new nr(this.config,n,c.ssrc);const h=new so(n,t,d,c,o);h.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()});h.options={...s,simulcast:s.simulcast??Om(s.sendEncodings)};h.sender.setStreams(s.streams??[]);h.sender.setSendEncodings((s.sendEncodings??[]).map(u=>({...u})));this.router.registerRtpSender(h.sender);const l=i==void 0?this.findReusableTransceiver(n):this.transceivers.find(u=>u.stopped&&u.mLineIndex===i);if(l){this.takeOverMLine(l,h)}else{this.pushTransceiver(h)}if(i!=void 0){this.remoteOfferSnapshot?.remoteCreated.add(h)}this.onTransceiverAdded.execute(h);return h}reusableForTrack(e,t){return e.sender.track==void 0&&e.kind===t&&!e.usedForSender&&!e.stopping&&!e.stopped&&!e.rejected&&!e.pendingRejection}addTrack(e,t=[],s){if(this.getSenders().find(c=>c.track?.uuid===e.uuid)){throw _(\"InvalidAccessError\",\"Track already added\")}const i=a(c=>this.reusableForTrack(c,e.kind)&&(s===void 0||c===s),\"reusableForTrack\");const n=s===null?void 0:this.transceivers.find(c=>i(c)&&zt.includes(c.direction));if(n){this.validateTrackForTransceiver(e,n);const c=n.sender;c.setStreams(t);c.registerTrack(e);n.options={...n.options,streams:t};n.codecs=[];return n}const o=s===null?void 0:this.transceivers.find(c=>i(c)&&!zt.includes(c.direction));if(o){const c=o.direction===\"recvonly\"?\"sendrecv\":o.direction===\"inactive\"?\"sendonly\":o.direction;this.validateTrackForTransceiver(e,o,c);const d=o.sender;d.setStreams(t);d.registerTrack(e);o.options={...o.options,streams:t};switch(o.direction){case\"recvonly\":o.setDirection(\"sendrecv\");break;case\"inactive\":o.setDirection(\"sendonly\");break}o.codecs=[];return o}else{const c=this.addTransceiver(e,void 0,{direction:\"sendrecv\",streams:t});c.addedByAddTrack=true;return c}}removeTrack(e){if(!this.getSenders().find(({ssrc:s})=>e.ssrc===s)){throw _(\"InvalidAccessError\",\"Sender does not exist\")}const t=this.transceivers.find(({sender:{ssrc:s}})=>e.ssrc===s);if(!t)throw new Error(\"No matching transceiver found\");if(t.stopping||t.stopped){return false}if(e.track==void 0){return false}e.detachTrack();if(t.direction===\"sendrecv\"){t.setDirection(\"recvonly\")}else if(t.direction===\"sendonly\"){t.setDirection(\"inactive\")}return true}assignTransceiverCodecs(e){const t=this.filterCodecsByDirection(e.kind,e.direction);e.codecs=Yt({kind:e.kind,configured:t,source:Le(e.sender.track),preferences:e.codecPreferences});e.codecPreferencesNeedResolution=false}filterCodecsByDirection(e,t){return this.config.codecs[e].filter(s=>{switch(s.direction){case\"recvonly\":{if(Nh.includes(t))return true;return false}case\"sendonly\":{if(zt.includes(t))return true;return false}case\"sendrecv\":{if([qa,za,Ha].includes(t))return true;return false}case\"all\":{return true}default:return false}})}validateTrackForTransceiver(e,t,s=t.direction){Et(e);Yt({kind:e.kind,configured:this.filterCodecsByDirection(e.kind,s),source:Le(e),preferences:t.codecPreferences})}getLocalRtpParams(e){if(e.mid==void 0)throw new Error(\"mid not assigned\");const t={codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:true}};return t}getRemoteRtpParams(e,t){const s={muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((i,n)=>{if(n.name.toLowerCase()===\"rtx\"){const o=Ie(n.parameters??\"\");const c=i[o[\"apt\"]];if(c&&e.ssrc.length===2){c.rtx=new Di({ssrc:e.ssrc[1].ssrc})}return i}i[n.payloadType]=new Ni({ssrc:e.ssrc[0]?.ssrc,payloadType:n.payloadType});return i},{}))};return s}resyncAnswerCodecs(e,t){this.refreshAnswerCodecs(e,t);const s=this.getLocalRtpParams(e);e.sender.prepareSend(s);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const i=this.getRemoteRtpParams(t,e);for(const n of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,n,i)}e.receiver.resyncCodecs(i);this.router.registerRtpReceiverBySsrc(e,i)}}resolveRemoteCodecSet(e,t,s,i){const n=a(l=>l.name.toLowerCase(),\"codecName\");const o=a(l=>(l.parameters??\"\").split(\"/\").map(Number).filter(u=>!Number.isNaN(u)),\"redPayloadTypes\");const c=new Map;const d=new Set;for(const l of e){if([\"red\",\"rtx\"].includes(n(l)))continue;const u=t.rtp.codecs.find(g=>!d.has(g)&&g.mimeType.toLowerCase()===l.mimeType.toLowerCase()&&(i==void 0||i.some(S=>rr(S,g))));if(u){c.set(l,u);d.add(u)}}const h=e.flatMap(l=>{if(n(l)===\"red\"){const f=o(l).flatMap(m=>{const T=e.find(E=>E.payloadType===m);const C=T?c.get(T):void 0;return C?[C.payloadType]:[]});const y=t.rtp.codecs.find(m=>{if(n(m)!==\"red\"||d.has(m))return false;const T=o(m);return T.length===f.length&&T.every((C,E)=>C===f[E])});if(!y)return[];d.add(y);return[y]}if(n(l)!==\"rtx\"){const f=c.get(l);return f?[f]:[]}const u=Ie(l.parameters??\"\").apt;const g=e.find(f=>f.payloadType===u);if(!g)return[];const S=c.get(g);if(!S)return[];const p=t.rtp.codecs.find(f=>{if(n(f)!==\"rtx\"||d.has(f)){return false}return Ie(f.parameters??\"\").apt===S.payloadType});if(!p)return[];d.add(p);return[p]});if(s===\"remote\"){const l=new Map(t.rtp.codecs.map((u,g)=>[u,g]));h.sort((u,g)=>l.get(u)-l.get(g))}if(h.length===0){throw _(\"NotSupportedError\",\"No compatible codec remains after remote negotiation.\")}return h}refreshAnswerCodecs(e,t){const s=this.config.codecs[t.kind]||[];const i=Le(e.sender.track);Yt({kind:t.kind,configured:s,source:i,preferences:e.codecPreferences});const n=oc(s,i,e.codecPreferences);e.codecs=this.resolveRemoteCodecSet(n,t,\"local\",i);e.codecPreferencesNeedResolution=false;ol(\"negotiated codecs\",e.codecs)}planRemoteRtpCodecs(e,t){const s=new Map;const i=e.type===\"offer\";for(const[n,o]of e.media.entries()){if(![\"audio\",\"video\"].includes(o.kind))continue;const c=t(o,n);if(o.port===0||c?.stopped||c?.stopping){s.set(n,[]);continue}const d=Le(c?.sender.track);const h=this.config.codecs[o.kind]||[];const l=i?h:c?.pendingLocalOfferCodecs||[];if(!Qu(l,o.rtp.codecs)){s.set(n,[]);continue}if(i){Yt({kind:o.kind,configured:h,source:d,preferences:c?.codecPreferences})}const u=this.resolveRemoteCodecSet(i?oc(h,d,c?.codecPreferences):l,o,i?\"local\":\"remote\",d);if(d!=void 0){Yt({kind:o.kind,configured:u,source:d,preferences:void 0})}s.set(n,u)}return s}setRemoteRTP(e,t,s,i,n){if(!e.mid){e.mid=t.rtp.muxId??null}e.mLineIndex=i;if(s===\"answer\")e.pendingLocalOfferCodecs=void 0;if(e.stopped){return false}if(e.stopping){if(s===\"answer\"&&t.port===0){e.commitStopped({rejected:false})}return false}ol(\"negotiated codecs\",n);if(t.port===0||n.length===0){if(s===\"answer\"){e.commitStopped({rejected:true})}else{e.pendingRejection=true}return false}e.pendingRejection=false;e.codecs=n;e.headerExtensions=t.rtp.headerExtensions.filter(h=>(this.config.headerExtensions[t.kind]||[]).find(l=>l.uri===h.uri));const o=t.direction??\"inactive\";const c=Uu(o);if([\"answer\",\"pranswer\"].includes(s)){e.setCurrentDirection(c)}else{e.offerDirection=c}const d=this.getLocalRtpParams(e);e.sender.prepareSend(d);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const h=this.getRemoteRtpParams(t,e);for(const l of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,l,h)}e.receiver.resyncCodecs(h);this.router.registerRtpReceiverBySsrc(e,h)}if([\"sendonly\",\"sendrecv\"].includes(o)){const h=[...new Set(t.msids.map(u=>u.split(\" \")[0]))];const l=t.msids[0]?.split(\" \")[1];e.receiver.remoteStreamId=h[0];e.receiver.remoteStreamIds=h;e.receiver.remoteTrackId=l;if(!e.firedReceiving){e.firedReceiving=true;this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:h.map(u=>new us({id:u,tracks:[e.receiver.track]}))})}}else{e.firedReceiving=false}return true}markStable(){this.stableState=new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex}]))}rollbackLocalOffer(){for(const e of this.transceivers){const t=this.stableState.get(e);e.mid=t?.mid??null;e.mLineIndex=t?.mLineIndex}}beginRemoteOffer(){if(this.remoteOfferSnapshot){return}this.remoteOfferSnapshot={transceivers:[...this.transceivers],remoteCreated:new Set,states:new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex,pendingRejection:e.pendingRejection,firedReceiving:e.firedReceiving}]))}}commitRemoteOffer(){this.remoteOfferSnapshot=void 0;for(const e of this.transceivers){if(e.pendingRejection){e.commitStopped({rejected:true})}}}rollbackRemoteOffer(){const e=this.remoteOfferSnapshot;this.remoteOfferSnapshot=void 0;if(!e){return}for(const t of this.transceivers){if(e.states.has(t)){continue}if(!e.remoteCreated.has(t)||t.sender.track){t.mid=null;t.mLineIndex=void 0;e.transceivers.push(t);continue}t.forceStop();this.unwatchTransceiver(t)}this.transceivers.splice(0,this.transceivers.length,...e.transceivers);e.transceivers.forEach(t=>this.watchTransceiver(t));for(const[t,s]of e.states){t.mid=s.mid;t.mLineIndex=s.mLineIndex;t.pendingRejection=s.pendingRejection;t.firedReceiving=s.firedReceiving}}settleStoppingTransceivers(e){for(const t of this.transceivers){if(!t.stopping||t.stopped){continue}if(t.mid==void 0||!e.has(t.mid)){t.commitStopped({rejected:false})}}return this.transceivers.some(t=>t.stopping&&!t.stopped)}collectStats(e){const t=[];for(const s of this.transceivers){if(s.sender){t.push(...s.sender.collectStats(e))}if(s.receiver){t.push(...s.receiver.collectStats(e))}const i=s.collectCodecStats(e);if(i){t.push(...i)}}return t}getStatsRootIds(e){if(!e){return[]}const t=[];for(const s of this.transceivers){if(s.sender.track===e){t.push(...s.sender.getStatsRootIds())}if(s.receiver.tracks.includes(e)){t.push(...s.receiver.getStatsRootIds(e))}}return t}close(){for(const e of this.transceivers){e.forceStop();this.unwatchTransceiver(e)}this.onTransceiverAdded.allUnsubscribe();this.onRemoteTransceiverAdded.allUnsubscribe();this.onTrack.allUnsubscribe();this.onNegotiationNeeded.allUnsubscribe()}};var Um=b(\"webrtc/peer/sctpManager\");var xo=class{static{a(this,\"SctpTransportManager\")}constructor(){this.dataChannelsOpened=0;this.dataChannelsClosed=0;this.dataChannels=[];this.onDataChannel=new w}createSctpTransport(e,t){const s=new mo(5e3,e,t);s.mid=void 0;s.onDataChannel.subscribe(i=>{this.dataChannelsOpened++;this.dataChannels.push(i);this.onDataChannel.execute(i)});this.sctpTransport=s;return s}createDataChannel(e,t={}){const s=al(t.maxPacketLifeTime,\"maxPacketLifeTime\");const i=al(t.maxRetransmits,\"maxRetransmits\");const n={protocol:\"\",ordered:true,negotiated:false};const o={...n,...t,maxPacketLifeTime:s,maxRetransmits:i};if(o.maxPacketLifeTime!=null&&o.maxRetransmits!=null){throw Re(\"maxPacketLifeTime and maxRetransmits cannot both be set\")}if(!this.sctpTransport){this.sctpTransport=this.createSctpTransport()}const c=new Zt({id:o.id,label:e,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits,negotiated:o.negotiated,ordered:o.ordered,protocol:o.protocol});const d=new Jt(this.sctpTransport,c);this.dataChannelsOpened++;this.dataChannels.push(d);d.stateChange.subscribe(h=>{if(h===\"closed\"){this.dataChannelsClosed++;const l=this.dataChannels.indexOf(d);if(l!==-1){this.dataChannels.splice(l,1)}}});return d}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort){return}await this.sctpTransport.start(this.sctpRemotePort);await this.sctpTransport.sctp.stateChanged.connected.asPromise();Um(\"sctp connected\")}setRemoteSCTP(e,t){if(!this.sctpTransport){return}this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize);this.sctpRemotePort=e.sctpPort;if(!this.sctpRemotePort){throw new Error(\"sctpRemotePort not exist\")}this.sctpTransport.setRemotePort(this.sctpRemotePort);this.sctpTransport.mLineIndex=t;if(!this.sctpTransport.mid){this.sctpTransport.mid=e.rtp.muxId}}async close(){if(this.sctpTransport){await this.sctpTransport.stop();await new Promise(e=>setImmediate(e))}this.onDataChannel.allUnsubscribe()}async getStats(e=J()){const t=[];for(const s of this.dataChannels){const i={type:\"data-channel\",id:D(\"data-channel\",s.id??s.statsId),timestamp:e,label:s.label,protocol:s.protocol,dataChannelIdentifier:s.id??void 0,state:s.readyState,messagesSent:s.messagesSent||0,bytesSent:s.bytesSent||0,messagesReceived:s.messagesReceived||0,bytesReceived:s.bytesReceived||0};t.push(i)}return t}};function al(r,e){if(r===void 0){return void 0}const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw Re(`${e} must be an unsigned short`)}return t}a(al,\"coerceUnsignedShortOption\");var lc=b(\"webrtc/peer/secureTransportManager\");var ko=class{static{a(this,\"SecureTransportManager\")}constructor({config:e,transceiverManager:t,sctpManager:s}){this.connectionState=\"new\";this.iceConnectionState=\"new\";this.iceGatheringState=\"new\";this.iceGatheringStateChange=new w;this.iceConnectionStateChange=new w;this.onIceCandidate=new w;this.connectionStateChange=new w;this.createdTransports=new Set;this.config=e;this.transceiverManager=t;this.sctpManager=s;if(this.config.dtls){const{keys:i}=this.config.dtls;if(this.config.certificates[0]){this.certificate=this.config.certificates[0]}else if(i){this.setupCertificate(i)}}}get dtlsTransports(){return fc([...this.transceiverManager.getTransceivers().filter(e=>!e.stopped).map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return fc([...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new ui(e.keyPem,e.certPem,e.signatureHash)}resolveIceServerOptions(){const e=Fu(this.config.iceServers);const t=$a({parsedTurnTransport:e.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:t,stunServers:e.stunServers,turnServers:e.turnServers.map(s=>({...s,transport:$a({parsedTurnTransport:s.transport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP})}))}}updateIceServers(){const e={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy===\"relay\",useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(const t of this.iceTransports){if(t.gatheringState===\"new\"){t.setIceServers(e)}}}createTransport({inheritCredentials:e=true}={}){const t=e?this.iceTransports.find(o=>o.state!==\"closed\"):void 0;const s=new po({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy===\"relay\",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});if(t){s.connection.localUsername=t.connection.localUsername;s.connection.localPassword=t.connection.localPassword}s.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()});this.updateIceGatheringState();const i=new fo(s);i.onStateChange.subscribe(()=>{this.updateIceConnectionState()});const n=new hi(this.config,i,this.certificate,Hm);this.createdTransports.add(n);return n}handleNewIceCandidate({candidate:e,sdpMid:t,sdpMLineIndex:s}){e.sdpMid=t;e.sdpMLineIndex=s;if(e.foundation&&!e.foundation.startsWith(\"candidate:\")){e.foundation=\"candidate:\"+e.foundation}this.onIceCandidate.execute(e);return e}async addIceCandidate(e,t){const s=t?.candidate;const i=t?.sdpMid;const n=t?.sdpMLineIndex;const o=t?.usernameFragment;const c=t==null||s==null||s===\"\";const d=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:c,sdpMid:i,sdpMLineIndex:n,usernameFragment:o});if(c){const S=d.map(p=>this.getTransportByMLineIndex(e,p)).filter(p=>!!p).reduce((p,f)=>{if(!p.find(({id:y})=>y===f.id)){p.push(f)}return p},[]);await Promise.all(S.map(p=>p.addRemoteCandidate(void 0)));return{kind:\"end-of-candidates\",mediaIndices:d}}const h=li.fromJSON(t);if(!h){throw _(\"OperationError\",\"Failed to parse ICE candidate\")}const l=d[0];const u=e.media[l];if(!u){throw _(\"OperationError\",\"ICE media section not found\")}h.sdpMid=u.rtp.muxId??void 0;h.sdpMLineIndex=l;const g=this.getTransportByMLineIndex(e,l);if(!g){if(this.isRejectedMedia(u)){return{kind:\"candidate\",candidate:h,mediaIndices:[l]}}throw _(\"OperationError\",\"ICE transport not found for candidate\")}await g.addRemoteCandidate(h);return{kind:\"candidate\",candidate:h,mediaIndices:[l]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:s,sdpMLineIndex:i,usernameFragment:n}){let o;if(typeof s===\"string\"){const c=e.media.findIndex(d=>d.rtp.muxId===s);if(c<0){throw _(\"OperationError\",\"Media section for sdpMid was not found\")}o=[c]}else if(typeof i===\"number\"){if(i<0||i>=e.media.length){throw _(\"OperationError\",\"Media section for sdpMLineIndex was not found\")}o=[i]}else if(t){o=e.media.map((c,d)=>d)}else{throw Re(\"sdpMid or sdpMLineIndex must be provided with a candidate\")}if(typeof n===\"string\"){const c=o.filter(d=>e.media[d]?.iceParams?.usernameFragment===n);if(c.length===0){throw _(\"OperationError\",\"No media section matched the ICE usernameFragment\")}o=c}return o}isRejectedMedia(e){if(e.port===0){return true}if(![\"audio\",\"video\"].includes(e.kind)){return false}const t=this.transceiverManager.getTransceivers().find(s=>s.mid!=void 0&&s.mid===e.rtp.muxId);return!t||t.stopped||t.stopping||t.pendingRejection}getTransportByMid(e){if(!e){return}let t;const s=this.transceiverManager.getTransceivers().find(i=>i.mid===e);if(s){t=s.dtlsTransport?.iceTransport}else if(!t&&this.sctpManager.sctpTransport?.mid===e){t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport}if(t?.state===\"closed\"){return}return t}getTransportByMLineIndex(e,t){const s=e.media[t];if(!s){return}const i=this.getTransportByMid(s.rtp.muxId);return i}restartIce(){for(const e of this.iceTransports){e.restart()}this.updateIceGatheringState()}setLocalRole({type:e,role:t,roleOfTransport:s}){for(const i of this.dtlsTransports){const n=i.iceTransport;if(n.state===\"new\"){if(n.connection.iceLite){n.connection.iceControlling=false}else if(n.connection.remoteIsLite){n.connection.iceControlling=true}else{n.connection.iceControlling=e===\"offer\"}}if(e===\"answer\"){const o=s?.get(i)??t;if(o){i.role=o}}}}updateIceGatheringState(){const e=this.iceTransports;function t(...i){return e.filter(n=>i.includes(n.gatheringState)).length===e.length}a(t,\"allMatch\");let s;if(e.length&&t(\"complete\")){s=\"complete\"}else if(!e.length||t(\"new\",\"complete\")){s=\"new\"}else if(e.map(i=>i.gatheringState).includes(\"gathering\")){s=\"gathering\"}else{s=\"new\"}if(this.iceGatheringState===s){return}this.iceGatheringState=s;this.iceGatheringStateChange.execute(s)}updateIceConnectionState(){const e=this.iceTransports;let t;function s(...n){return e.filter(o=>n.includes(o.state)).length===e.length}a(s,\"allMatch\");function i(...n){return e.some(o=>n.includes(o.state))}a(i,\"anyMatch\");if(this.connectionState===\"closed\"){t=\"closed\"}else if(i(\"failed\")){t=\"failed\"}else if(i(\"disconnected\")){t=\"disconnected\"}else if(s(\"new\",\"closed\")){t=\"new\"}else if(i(\"new\",\"checking\")){t=\"checking\"}else if(s(\"completed\",\"closed\")){t=\"completed\"}else if(s(\"connected\",\"completed\",\"closed\")){t=\"connected\"}else{t=\"new\"}if(this.iceConnectionState===t){return}lc(\"iceConnectionStateChange\",t);this.iceConnectionState=t;this.iceConnectionStateChange.execute(t);if(t===\"failed\"&&this.connectionState!==\"closed\"){this.setConnectionState(\"failed\")}else if(t===\"disconnected\"&&this.connectionState===\"connected\"){this.setConnectionState(\"disconnected\")}}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter(e=>e.state!==\"closed\").map(e=>e.gather())).catch(e=>{lc(\"gatherCandidates failed\",e)})}setConnectionState(e){if(this.connectionState===e||this.connectionState===\"closed\"){return}lc(\"connectionStateChange\",e);this.connectionState=e;this.connectionStateChange.execute(e)}async getStats(e){const t=[];for(const s of this.dtlsTransports){const i=await s.getStats(e);if(i){t.push(...i)}}return t}async ensureCerts(){if(!this.certificate){this.certificate=await hi.SetupCertificate()}for(const e of this.dtlsTransports){e.localCertificate=this.certificate}}async close(){this.setConnectionState(\"closed\");await Promise.allSettled(fc([...this.allDtlsTransports,...this.createdTransports]).map(e=>e.stop()));this.createdTransports.clear();this.iceGatheringStateChange.allUnsubscribe();this.iceConnectionStateChange.allUnsubscribe();this.onIceCandidate.allUnsubscribe();this.connectionStateChange.allUnsubscribe()}};function fc(r){return r.reduce((e,t)=>{if(t&&!e.map(s=>s.id).includes(t.id)){e.push(t)}return e},[])}a(fc,\"uniqueTransports\");var Hm=[Ta.SRTP_AEAD_AES_128_GCM,Ta.SRTP_AES128_CM_HMAC_SHA1_80];var U=b(\"webrtc/peer/peerConnection\");var vo=class extends he{static{a(this,\"RTCPeerConnection\")}get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super();this.id=(0,pc.randomUUID)().toString();this.cname=(0,pc.randomUUID)().toString();this.config=dl();this.signalingState=\"stable\";this.negotiationneeded=false;this.negotiationneededScheduled=false;this.negotiationChangeSeq=0;this.negotiatedChangeSeq=0;this.lastCreatedOfferChangeSeq=0;this.needRestart=false;this.router=new bo;this.isClosed=false;this.shouldNegotiationneeded=false;this.pendingRemoteCandidates=[];this.iceGatheringStateChange=new w;this.iceConnectionStateChange=new w;this.signalingStateChange=new w;this.connectionStateChange=new w;this.onDataChannel=new w;this.onRemoteTransceiverAdded=new w;this.onTransceiverAdded=new w;this.onIceCandidate=new w;this.onNegotiationneeded=new w;this.onTrack=new w;this.eventHandlers={};this.needNegotiation=()=>{this.negotiationChangeSeq++;this.scheduleNegotiationneeded()};this.setConfiguration(e);this.sdpManager=new Co({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse});this.transceiverManager=new Ro(this.cname,this.config,this.router);this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);this.transceiverManager.onTrack.subscribe(({track:t,streams:s,transceiver:i})=>{const n=new mc({track:t,streams:s,transceiver:i,receiver:i.receiver});this.onTrack.execute(t);this.emit(\"track\",n);if(this.ontrack){K(()=>this.ontrack(n),o=>U(\"event handler failed\",o))}});this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation());this.sctpManager=new xo;this.sctpManager.onDataChannel.subscribe(t=>{this.onDataChannel.execute(t);const s={type:\"datachannel\",channel:t};if(this.ondatachannel)K(()=>this.ondatachannel(s),i=>U(\"event handler failed\",i));this.emit(\"datachannel\",s)});this.secureManager=new ko({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager});this.secureManager.iceGatheringStateChange.subscribe(t=>{this.iceGatheringStateChange.execute(t);if(this.onicegatheringstatechange){K(()=>this.onicegatheringstatechange(new globalThis.Event(\"icegatheringstatechange\")),s=>U(\"event handler failed\",s))}this.emit(\"icegatheringstatechange\")});this.secureManager.iceConnectionStateChange.subscribe(t=>{if(t===\"closed\"){this.close().catch(s=>U(\"close failed\",s))}this.iceConnectionStateChange.execute(t);if(this.oniceconnectionstatechange)K(()=>this.oniceconnectionstatechange(),s=>U(\"event handler failed\",s));this.emit(\"iceconnectionstatechange\")});this.secureManager.connectionStateChange.subscribe(t=>{this.connectionStateChange.execute(t);if(this.onconnectionstatechange)K(()=>this.onconnectionstatechange(),s=>U(\"event handler failed\",s));this.emit(\"connectionstatechange\")});this.secureManager.onIceCandidate.subscribe(t=>{const s=t?t.toJSON():void 0;this.onIceCandidate.execute(s);const i={type:\"icecandidate\",candidate:s};if(this.onicecandidate)K(()=>this.onicecandidate(i),n=>U(\"event handler failed\",n));this.emit(\"icecandidate\",i)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){const e=this.sdpManager._remoteDescription;if(!e){return null}const t=[e.iceOptions,...e.media.map(s=>s.iceOptions)].filter(s=>!!s).join(\" \");return t.split(/\\s+/).includes(\"trickle\")}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(e){const t=qm(e);const s=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==\"require\"){throw new Error(\"rtcpMuxPolicy must be require\")}if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0)){throw new Error(\"iceCandidatePoolSize must be a non-negative integer\")}if(s&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy){throw new Error(\"bundlePolicy cannot be changed\")}if(t.mLineReuse!==void 0&&!cl.includes(t.mLineReuse)){throw Re(`mLineReuse must be one of ${cl.join(\", \")}`)}if(s&&t.mLineReuse!==void 0&&t.mLineReuse!==this.config.mLineReuse){throw _(\"InvalidModificationError\",\"mLineReuse cannot be changed\")}if(s&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy){throw new Error(\"rtcpMuxPolicy cannot be changed\")}if(s&&t.certificates!==void 0&&!Km(t.certificates,this.config.certificates)){throw new Error(\"certificates cannot be changed\")}if(s&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize){throw new Error(\"iceCandidatePoolSize cannot be changed after setLocalDescription\")}if((t.iceCandidatePoolSize??0)>0){throw new Error(\"iceCandidatePoolSize > 0 is not supported\")}if(t.sctp!==void 0){const o=t.sctp.mtu??bs;sn(o);if(this.sctpManager?.sctpTransport&&o!==this.config.sctp.mtu){throw new Error(\"sctp.mtu cannot be changed after SCTP transport creation\")}}Ku(this.config,t);this.config.sctp={mtu:this.config.sctp?.mtu??bs};if(this.config.icePortRange){const[o,c]=this.config.icePortRange;if(o===c)throw new Error(\"should not be same value\");if(o>=c)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\")}if(this.sctpManager?.sctpTransport){this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize}zm(this.config);const i=new Map;const n=[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]];n.forEach(o=>{if(!i.has(o.uri))i.set(o.uri,i.size+1);o.id=i.get(o.uri)});if(s&&this.secureManager&&(t.iceServers!==void 0||t.turnUdpFamily!==void 0)){this.secureManager.updateIceServers()}}getConfiguration(){return Gm(this.config)}headerExtensionsFor(e){const t=new Map;for(const i of this.transceiverManager.getTransceivers()){for(const n of i.headerExtensions)t.set(n.uri,n.id)}const s=new Set(t.values());return(this.config.headerExtensions[e]??[]).flatMap(i=>{let n=t.get(i.uri);if(n===void 0){n=s.has(i.id)?Array.from({length:14},(o,c)=>c+1).find(o=>!s.has(o)):i.id;if(n===void 0)return[];s.add(n);t.set(i.uri,n)}return[new Te({uri:i.uri,id:n})]})}async createOffer({iceRestart:e}={}){if(e||this.needRestart){this.needRestart=false;this.secureManager.restartIce()}await this.secureManager.ensureCerts();for(const i of this.transceiverManager.getTransceivers()){if(i.codecs.length===0||i.codecPreferencesNeedResolution){this.transceiverManager.assignTransceiverCodecs(i)}if(i.headerExtensions.length===0){i.headerExtensions=this.headerExtensionsFor(i.kind)}}const t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);const s=t.toJSON();this.lastCreatedOffer=s;this.lastCreatedOfferChangeSeq=this.negotiationChangeSeq;return s}createSctpTransport(){const e=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp);const t=this.findOrCreateTransport();e.setDtlsTransport(t);return e}createDataChannel(e,t={}){if(!this.sctpTransport){this.createSctpTransport();this.needNegotiation()}const s=this.sctpManager.createDataChannel(e,t);if(!s.sctp.dtlsTransport){const i=this.findOrCreateTransport();s.sctp.setDtlsTransport(i)}return s}removeTrack(e){if(this.isClosed){throw _(\"InvalidStateError\",\"peer closed\")}if(this.transceiverManager.removeTrack(e)){this.needNegotiation()}}scheduleNegotiationneeded(){this.invalidateLastCreatedDescriptions();this.shouldNegotiationneeded=true;if(this.negotiationneeded||this.negotiationneededScheduled||this.signalingState!==\"stable\"){return}this.shouldNegotiationneeded=false;this.negotiationneededScheduled=true;setImmediate(()=>{this.negotiationneededScheduled=false;if(this.negotiatedChangeSeq>=this.negotiationChangeSeq){return}if(this.signalingState!==\"stable\"){this.shouldNegotiationneeded=true;return}this.negotiationneeded=true;this.onNegotiationneeded.execute();if(this.onnegotiationneeded){K(()=>this.onnegotiationneeded(new globalThis.Event(\"negotiationneeded\")),e=>U(\"event handler failed\",e))}this.emit(\"negotiationneeded\")})}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0;this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed();await Promise.resolve();if(this.isClosed){await new Promise(()=>void 0)}}findOrCreateTransport(){const e=this.dtlsTransports.find(t=>t.state!==\"closed\");if(this.sdpManager.bundlePolicy===\"max-bundle\"||this.sdpManager.bundlePolicy!==\"disable\"&&this.remoteIsBundled){if(e){return e}}return this.createDtlsTransport()}createDtlsTransport({inheritCredentials:e=true}={}){const t=this.secureManager.createTransport({inheritCredentials:e});t.onRtp.subscribe(i=>{this.router.routeRtp(i)});t.onRtcp.subscribe(i=>{this.router.routeRtcp(i)});const s=t.iceTransport;s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()});s.onIceCandidate.subscribe(i=>{if(!this.localDescription){U(\"localDescription not found when ice candidate was gathered\");return}if(!i){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport);this.onIceCandidate.execute(void 0);if(this.onicecandidate){K(()=>this.onicecandidate({candidate:void 0}),o=>U(\"event handler failed\",o))}this.emit(\"icecandidate\",{candidate:void 0});return}if(!this._localDescription){U(\"localDescription not found when ice candidate was gathered\");return}const n=this.resolveLocalCandidateOwner(s);if(!n){U(\"no accepted m-line owns the ice transport\",s.id);return}this.secureManager.handleNewIceCandidate({candidate:i,sdpMid:n.mid,sdpMLineIndex:n.index})});return t}resolveLocalCandidateOwner(e){const t=this._localDescription;if(!t){return}const s=t.media.map((o,c)=>({media:o,index:c})).filter(({media:o})=>{if(o.port===0){return false}const c=o.rtp.muxId;if(o.kind===\"application\"){return!!this.sctpTransport&&this.sctpTransport.mid===c&&this.sctpTransport.dtlsTransport?.iceTransport.id===e.id}const d=this.transceiverManager.getTransceivers().find(h=>h.mid!=void 0&&h.mid===c);return!!d&&!d.stopped&&d.dtlsTransport?.iceTransport.id===e.id});const i=t.group.filter(o=>o.semantic===\"BUNDLE\").map(o=>o.items[0]);const n=s.find(({media:o})=>i.includes(o.rtp.muxId))??s[0];if(!n){return}return{mid:n.media.rtp.muxId,index:n.index}}settleStoppingTransceivers(){const e=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter(s=>s.port!==0&&s.rtp.muxId).map(s=>s.rtp.muxId));const t=this.transceiverManager.settleStoppingTransceivers(e);this.closeIdleTransports();return t}closeIdleTransports(e=this.transceiverManager.getTransceivers().filter(t=>t.stopped).map(t=>t.dtlsTransport)){const t=new Set(this.dtlsTransports.map(s=>s.id));for(const s of new Set(e)){if(!s||s.state===\"closed\"||t.has(s.id)){continue}s.stop().catch(i=>{U(\"failed to close idle transport\",i)})}}async setLocalDescription(e){const t=[\"stable\",\"have-local-offer\",\"have-remote-pranswer\"];await this.waitForPendingDescriptionTask();if(e?.type===\"rollback\"){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const u of this.transceiverManager.getTransceivers()){u.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}const s=!e?.type||!e.sdp||e.sdp.length===0;const i=s?e?.type===\"offer\"?this.lastCreatedOffer??await this.createOffer():e?.type===\"answer\"||e?.type===\"pranswer\"?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;e={type:e?.type??i.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:i.sdp};if(e.type===\"offer\"&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp){throw _(\"InvalidModificationError\",\"setLocalDescription must use the latest created offer\")}const n=e.type;const o=e.sdp;const c=this.sdpManager.parseSdp({sdp:o,isLocal:true,signalingState:this.signalingState,type:n});if(c.type===\"offer\"){this.pendingOfferChangeSeq=this.lastCreatedOffer?.sdp===e.sdp?this.lastCreatedOfferChangeSeq:void 0;this.setSignalingState(\"have-local-offer\")}else if(c.type===\"answer\"){this.setSignalingState(\"stable\")}else if(c.type===\"pranswer\"){this.setSignalingState(\"have-local-pranswer\")}if(c.type===\"answer\"){this.transceiverManager.commitRemoteOffer();for(const u of c.media){if(![\"audio\",\"video\"].includes(u.kind)||u.port!==0){continue}const g=this.transceiverManager.getTransceivers().find(S=>S.mid===u.rtp.muxId&&!S.stopped);g?.commitStopped({rejected:true})}this.closeIdleTransports()}for(const[u,g]of Uo(c.media)){const S=g.rtp.muxId;this.sdpManager.registerMid(S);if([\"audio\",\"video\"].includes(g.kind)&&g.port!==0){const p=this.transceiverManager.getTransceivers().find(f=>f.mLineIndex===u&&!f.stopped&&f.kind===g.kind&&(f.mid==null||f.mid===S));if(p){p.mid=S;if(c.type===\"offer\"){p.pendingLocalOfferCodecs=[...g.rtp.codecs]}}}if(g.kind===\"application\"&&this.sctpTransport){this.sctpTransport.mid=S}}const d=c.media.find(u=>u.dtlsParams)?.dtlsParams?.role;const h=new Map;for(const u of c.media){const g=u.rtp.muxId;const S=u.dtlsParams?.role;if(u.port===0||g==void 0||!S){continue}const p=u.kind===\"application\"?this.sctpTransport?.mid===g?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(f=>f.mid===g&&!f.stopped);if(p?.dtlsTransport&&!h.has(p.dtlsTransport)){h.set(p.dtlsTransport,S)}}this.secureManager.setLocalRole({type:c.type===\"offer\"?\"offer\":\"answer\",role:d,roleOfTransport:h});if([\"answer\",\"pranswer\"].includes(c.type)){for(const u of c.media){const g=this.transceiverManager.getTransceivers().find(p=>p.mid!=void 0&&p.mid===u.rtp.muxId);if(!g||g.stopped||g.pendingRejection){continue}const S=g.stopping?\"inactive\":oo(g.direction,g.offerDirection);g.setCurrentDirection(S)}}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);await this.gatherCandidates().catch(u=>{U(\"gatherCandidates failed\",u)});if(c.type===\"answer\"){this.connect().catch(u=>{U(\"connect failed\",u);this.secureManager.setConnectionState(\"failed\")})}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);const l=c.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||l){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return c}async gatherCandidates(){await this.secureManager.gatherCandidates()}async addIceCandidate(e={}){if(this.isClosed){throw _(\"InvalidStateError\",\"is closed\")}if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){const t=this.sdpManager._remoteDescription;if(!t){return}const s=await this.secureManager.addIceCandidate(t,e);const i=this.sdpManager._remoteDescription;if(!i||!s){return}if(s.kind===\"end-of-candidates\"){for(const n of s.mediaIndices){const o=i.media[n];if(o){o.iceCandidatesComplete=true}}return}for(const n of s.mediaIndices){const o=i.media[n];if(!o){continue}o.iceCandidates.push(s.candidate)}}async flushPendingRemoteCandidates(){while(this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription){const e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){U(\"start connect\");const e=await Promise.allSettled(this.dtlsTransports.map(async t=>{const{iceTransport:s}=t;if(s.state===\"connected\"){return}if(!s.connection.remoteUsername||!s.connection.remotePassword){return}const i=a(()=>t.state===\"connected\",\"checkDtlsConnected\");if(i()){if(!s.connection.nominated){await s.start().catch(n=>{U(\"iceTransport.start failed\",n);throw n})}return}this.secureManager.setConnectionState(\"connecting\");await s.start().catch(n=>{U(\"iceTransport.start failed\",n);throw n});if(i()){return}await t.start().catch(n=>{U(\"dtlsTransport.start failed\",n);throw n});if(this.sctpTransport&&this.sctpTransport.dtlsTransport.id===t.id){await this.sctpManager.connectSctp()}}));if(e.find(t=>t.status===\"rejected\")){this.secureManager.setConnectionState(\"failed\")}else{this.secureManager.setConnectionState(\"connected\")}}restartIce(){this.needRestart=true;this.needNegotiation()}async setRemoteDescription(e){if(e instanceof ot){e=e.toSdp()}await this.waitForPendingDescriptionTask();const t=e.type===\"offer\"&&[\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState);if(t){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const m of this.transceiverManager.getTransceivers()){m.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.shouldNegotiationneeded=true;this.setSignalingState(\"stable\");await Promise.resolve()}let s=new Map;if(e.type&&e.type!==\"rollback\"&&e.sdp){const m=this.sdpManager.parseSdp({sdp:e.sdp,isLocal:false,signalingState:this.signalingState,type:e.type});const T=new Set;s=this.transceiverManager.planRemoteRtpCodecs(m,(C,E)=>{const P=this.findTransceiverForRemoteMedia(C,E,T,e.type===\"offer\");if(P)T.add(P);return P})}this.assertAnswerKeepsSharedTransports(e);const i=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!i){const m=this.transceiverManager.getTransceivers().map(T=>T.dtlsTransport);this.transceiverManager.rollbackRemoteOffer();this.closeIdleTransports(m);this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}if(i.type===\"offer\"){this.transceiverManager.beginRemoteOffer()}const n=this.config.bundlePolicy===\"disable\"?[]:i.group.filter(m=>m.semantic===\"BUNDLE\");const o=a(m=>m==void 0?void 0:n.find(T=>T.items.includes(m)),\"groupOfMid\");const c=new Set;const d=i.media.map((m,T)=>{if([\"audio\",\"video\"].includes(m.kind)){let C=this.findTransceiverForRemoteMedia(m,T,c,i.type===\"offer\");if(!C){if(m.port===0){return{remoteMedia:m,index:T}}C=this.addRemoteTransceiver(m,T)}else if(C.mid==null){this.transceiverManager.associateMLine(C,T)}c.add(C);return{remoteMedia:m,index:T,transceiver:C}}else if(m.kind===\"application\"){let C=this.sctpTransport;if(!C){C=this.createSctpTransport();C.mid=m.rtp.muxId}return{remoteMedia:m,index:T,sctpTransport:C}}else{throw new Error(\"invalid media kind\")}});if(i.type===\"offer\"){this.transceiverManager.releaseUnassociatedReservations(c,i.media.length)}const h=a(m=>m.transceiver??m.sctpTransport,\"ownerOf\");const l=i.type===\"offer\";const u=a(m=>!!m&&m.state!==\"closed\",\"liveTransport\");const g=new Map;const S=new Set;for(const m of n){const T=d.filter(E=>!!h(E)&&m.items.includes(E.remoteMedia.rtp.muxId));if(T.length===0){continue}let C=T.map(E=>h(E).dtlsTransport).find(E=>u(E)&&(!l||!S.has(E)));if(!C){C=this.createDtlsTransport({inheritCredentials:false})}g.set(m,C);S.add(C);for(const E of T){const P=h(E);if(P.dtlsTransport!==C){P.setDtlsTransport(C)}}}if(l){for(const m of d){const T=h(m);if(!T||m.remoteMedia.port===0||o(m.remoteMedia.rtp.muxId)){continue}if(!u(T.dtlsTransport)||S.has(T.dtlsTransport)){T.setDtlsTransport(this.createDtlsTransport({inheritCredentials:false}))}S.add(T.dtlsTransport)}}const p=new Set;for(const m of d){const{remoteMedia:T,index:C}=m;if(m.transceiver){if(this.transceiverManager.setRemoteRTP(m.transceiver,T,i.type,C,s.get(C)??[])){p.add(m)}}else if(m.sctpTransport){this.sctpManager.setRemoteSCTP(T,C);p.add(m)}}const f=new Map;for(const m of n){for(const T of m.items){const C=d.find(E=>E.remoteMedia.rtp.muxId===T&&E.remoteMedia.port!==0&&p.has(E));if(C){f.set(m,C);break}}}for(const m of d){const{remoteMedia:T}=m;const C=h(m);if(!C){continue}const E=p.has(m);const P=C.dtlsTransport;const de=o(T.rtp.muxId);if(T.port===0||!P||P.state===\"closed\"||!E&&!de){continue}const q=P.iceTransport;const pt=!de||f.get(de)===m;if(pt){if(T.iceParams){const mt=!!this.sdpManager.inactiveRemoteMedia;q.setRemoteParams(T.iceParams,mt);if(T.iceParams.iceLite&&!q.connection.iceLite){q.connection.iceControlling=true}}if(T.dtlsParams){P.setRemoteParams(T.dtlsParams)}}for(const mt of T.iceCandidates){q.addRemoteCandidate(mt).catch(He=>U(\"add candidate failed\",He))}if(T.iceCandidatesComplete){q.addRemoteCandidate(void 0).catch(mt=>U(\"end of candidates failed\",mt))}if(i.type===\"answer\"&&T.dtlsParams?.role){P.role=T.dtlsParams.role===\"client\"?\"server\":\"client\"}}if(i.type===\"answer\"){for(const m of this.transceiverManager.getTransceivers()){if(!c.has(m)&&m.mid!=void 0&&!m.stopped){m.commitStopped({rejected:true})}}this.closeIdleTransports()}if(i.type===\"offer\"){this.setSignalingState(\"have-remote-offer\")}else if(i.type===\"answer\"){this.setSignalingState(\"stable\")}else if(i.type===\"pranswer\"){this.setSignalingState(\"have-remote-pranswer\")}await this.flushPendingRemoteCandidates();if(i.type===\"answer\"){U(\"caller start connect\");this.connect().catch(m=>{U(\"connect failed\",m);this.secureManager.setConnectionState(\"failed\")})}this.negotiationneeded=false;if(i.type===\"answer\"&&this.pendingOfferChangeSeq!=void 0){this.negotiatedChangeSeq=Math.max(this.negotiatedChangeSeq,this.pendingOfferChangeSeq);this.pendingOfferChangeSeq=void 0}const y=i.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||y){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions()}assertAnswerKeepsSharedTransports(e){if(![\"answer\",\"pranswer\"].includes(e.type??\"\")||![\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState)||!e.sdp||this.config.bundlePolicy===\"disable\"){return}const t=ot.parse(e.sdp);const s=t.group.filter(n=>n.semantic===\"BUNDLE\");const i=new Map;for(const n of t.media){const o=n.rtp.muxId;if(n.port===0||o==void 0){continue}const c=n.kind===\"application\"?this.sctpTransport?.mid===o?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(g=>g.mid===o&&!g.stopped);const d=c?.dtlsTransport;if(!d){continue}const h={group:s.find(g=>g.items.includes(o)),credentials:`${n.iceParams?.usernameFragment}:${n.iceParams?.password}`};const l=i.get(d);if(!l){i.set(d,h);continue}const u=!!h.group&&h.group===l.group;if(!u&&h.credentials!==l.credentials){throw _(\"InvalidAccessError\",`mid=${o} shares a transport in the local offer but the remote ${e.type} moves it out of that BUNDLE group`)}}}findTransceiverForRemoteMedia(e,t,s,i){const n=this.transceiverManager.getTransceivers().filter(h=>!s.has(h)&&h.kind===e.kind);const o=e.rtp.muxId;const c=o!=void 0?n.find(h=>h.mid===o):void 0;if(c){return c}if(e.port===0){return}const d=n.filter(h=>h.mid==null&&!h.stopping&&!h.stopped&&(!i||h.addedByAddTrack&&[\"sendrecv\",\"recvonly\"].includes(e.direction??\"sendrecv\")));return d.find(h=>h.mLineIndex===t)??d[0]}addRemoteTransceiver(e,t){const s=this.findOrCreateTransport();const i=this.transceiverManager.addTransceiver(e.kind,s,{direction:\"recvonly\"},{remoteMLineIndex:t});i.mid=e.rtp.muxId??null;this.secureManager.updateIceConnectionState();this.onRemoteTransceiverAdded.execute(i);return i}addTransceiver(e,t={}){const s=this.findOrCreateTransport();const i=this.transceiverManager.addTransceiver(e,s,t);this.secureManager.updateIceConnectionState();this.needNegotiation();return i}addTrack(e,...t){return this.addTrackOn(void 0,e,...t)}reusableForTrack(e){return this.transceiverManager.reusableForTrack(e,e.kind)}addTrackOn(e,t,...s){if(this.isClosed){throw _(\"InvalidStateError\",\"is closed\")}const i=this.transceiverManager.addTrack(t,s,e);if(!i.dtlsTransport){const n=this.findOrCreateTransport();i.setDtlsTransport(n)}this.needNegotiation();return i.sender}async createAnswer(){this.assertNotClosed();await this.secureManager.ensureCerts();for(const s of this.transceiverManager.getTransceivers()){if(s.codecs.length!==0&&!s.codecPreferencesNeedResolution){continue}if(s.pendingRejection||s.stopping||s.stopped){continue}const i=this.sdpManager._remoteDescription;const n=i?.media.find(o=>o.rtp.muxId!=void 0&&o.rtp.muxId===s.mid&&o.kind===s.kind)??(s.mLineIndex!=void 0?i?.media[s.mLineIndex]:void 0);if(n&&[\"audio\",\"video\"].includes(n.kind)){this.transceiverManager.resyncAnswerCodecs(s,n)}else{this.transceiverManager.assignTransceiverCodecs(s)}if(s.headerExtensions.length===0){s.headerExtensions=this.headerExtensionsFor(s.kind)}}const e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState});const t=e.toJSON();this.lastCreatedAnswer=t;return t}assertNotClosed(){if(this.isClosed){throw _(\"InvalidStateError\",\"RTCPeerConnection is closed\")}}markStable(){this.transceiverManager.markStable();const e=this.sctpTransport;this.stableSctp=e?{mid:e.mid,mLineIndex:e.mLineIndex}:void 0}rollbackLocalOffer(){this.transceiverManager.rollbackLocalOffer();const e=this.sctpTransport;if(e){e.mid=this.stableSctp?.mid;e.mLineIndex=this.stableSctp?.mLineIndex}}setSignalingState(e){if(this.signalingState===e){return}U(\"signalingStateChange\",e);this.signalingState=e;if(e===\"stable\")this.markStable();this.signalingStateChange.execute(e);if(this.onsignalingstatechange){K(()=>this.onsignalingstatechange(new globalThis.Event(\"signalingstatechange\")),t=>U(\"event handler failed\",t))}this.emit(\"signalingstatechange\")}createPeerConnectionStats(e){return{type:\"peer-connection\",id:D(\"peer-connection\",this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){const t=J();const s=[];if(!e){s.push(this.createPeerConnectionStats(t))}s.push(...this.transceiverManager.collectStats(t));const i=await this.secureManager.getStats(t);s.push(...i);if(!e&&this.sctpTransport){const n=await this.sctpManager.getStats(t);if(n){s.push(...n)}}if(!e){return Wt(s)}return Wt(s,this.transceiverManager.getStatsRootIds(e))}async close(){if(this.isClosed)return;this.isClosed=true;this.pendingRemoteCandidates.length=0;this.setSignalingState(\"closed\");this.transceiverManager.close();await this.sctpManager.close();await this.secureManager.close();this.completePeerEvents();U(\"peerConnection closed\")}completePeerEvents(){const e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(const t of e){if(!t.ended){t.complete()}}}};var cl=[\"compatible\",\"aggressive\"];function zm(r){for(const[e,t]of Uo([...r.codecs.audio||[],...r.codecs.video||[]])){if(t.payloadType!=void 0){continue}t.payloadType=96+e;switch(t.name.toLowerCase()){case\"rtx\":{t.parameters=`apt=${t.payloadType-1}`}break;case\"red\":{if(t.contentType===\"audio\"){const s=t.payloadType+1;t.parameters=`${s}/${s}`;t.payloadType=63}}break}}}a(zm,\"assignDynamicPayloadTypes\");function dl(){return{codecs:Ad(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:\"all\",iceLite:false,iceServers:[],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:true,iceUseIpv6:true,iceUseTcp:false,iceTcpPassive:true,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:\"max-compat\",rtcpMuxPolicy:\"require\",iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:false,forceTurnTCP:false,maxMessageSize:tr,sctp:{mtu:bs},pendingRtp:false,mLineReuse:\"compatible\"}}a(dl,\"generateDefaultPeerConfig\");var t1=dl();function qm(r){const e=Object(r??{});const t={...e};if(e.sctp!==void 0){t.sctp={...e.sctp}}if(e.bundlePolicy===\"balanced\"){t.bundlePolicy=\"max-compat\"}if(\"certificates\"in e){if(e.certificates===void 0){t.certificates=void 0}else if(!Array.isArray(e.certificates)||e.certificates.some(s=>s==null)){throw Re(\"certificates must be an array of RTCCertificate\")}else{t.certificates=[...e.certificates]}}if(\"iceCandidatePoolSize\"in e){t.iceCandidatePoolSize=Fm(e.iceCandidatePoolSize,\"iceCandidatePoolSize\")}return t}a(qm,\"normalizePeerConfiguration\");function Fm(r,e){const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw Re(`${e} must be an unsigned short`)}return t}a(Fm,\"coerceUnsignedShort\");function Km(r,e){return r.length===e.length&&r.every((t,s)=>t===e[s])}a(Km,\"hasSameCertificates\");function Gm(r){return{...r,codecs:{audio:r.codecs.audio?[...r.codecs.audio]:void 0,video:r.codecs.video?[...r.codecs.video]:void 0},headerExtensions:{audio:r.headerExtensions.audio?[...r.headerExtensions.audio]:void 0,video:r.headerExtensions.video?[...r.headerExtensions.video]:void 0},iceServers:r.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:r.icePortRange?[...r.icePortRange]:void 0,iceAdditionalHostAddresses:r.iceAdditionalHostAddresses?[...r.iceAdditionalHostAddresses]:void 0,dtls:{...r.dtls},certificates:[...r.certificates],debug:{...r.debug},sctp:{...r.sctp},pendingRtp:typeof r.pendingRtp===\"object\"&&r.pendingRtp!=void 0?{...r.pendingRtp}:r.pendingRtp}}a(Gm,\"clonePeerConfiguration\");var mc=class{static{a(this,\"RTCTrackEvent\")}constructor(e){this.type=\"track\";this.track=e.track;this.streams=[...e.streams];this.transceiver=e.transceiver;this.receiver=e.receiver}};var jm={\"audio/opus\":a(()=>on(),\"audio/opus\"),\"audio/pcmu\":a(()=>an(),\"audio/pcmu\"),\"video/vp8\":a(()=>nn(),\"video/vp8\"),\"video/vp9\":a(()=>ea(),\"video/vp9\"),\"video/h264\":a(()=>Zo(),\"video/h264\")};var Wm=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/VP9\",\"video/H264\"];function $m(r){const e=jm[r.toLowerCase()];if(!e)throw new TypeError(`The codec ${r} is not supported: ${Wm.join(\", \")}`);return e()}a($m,\"engineCodecOf\");function hl(r){const e=r.map($m);return{audio:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"audio/\")),video:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"video/\"))}}a(hl,\"engineCodecsOf\");function ul(r){const e={iceServers:r.iceServers,iceTransportPolicy:r.iceTransportPolicy,iceUseIpv4:r.iceUseIpv4,iceUseIpv6:r.iceUseIpv6,codecs:hl(r.codecs),maxMessageSize:262144};if(r.icePortRange)e.icePortRange=r.icePortRange;if(r.iceAdditionalHostAddresses)e.iceAdditionalHostAddresses=r.iceAdditionalHostAddresses;if(r.headerExtensions){e.headerExtensions={audio:[el(),dc(),cc(),ac()],video:[dc(),cc(),ac()]};for(const t of[...e.codecs.audio,...e.codecs.video])t.rtcpFeedback.push(rn())}return e}a(ul,\"engineConfigOf\");var gc=b(\"webrtc/peer/threads\");var Vm=4096;var ll=65536;var fl=2*1024*1024;function Ym(r){const e=new Uint8Array(r);return{bytes:e,transfer:[e.buffer]}}a(Ym,\"ownCopy\");function Qm(r){return Object.assign(new Error(r.message),{name:r.name})}a(Qm,\"threadErrorOf\");function yi(r){return r instanceof Error?{name:r.name,message:r.message}:{name:\"Error\",message:String(r)}}a(yi,\"sentError\");var Io=class{static{a(this,\"PeerThreadChannel\")}#e;#t;#s=new Map;#n=new Set;#i=[];#o=[];#u=false;#l=1;#r;#a;#c=0;constructor(e,t){this.#e=e;this.#t=t;e.on(\"message\",s=>{if(!Array.isArray(s))return;for(const i of s)this.#f(i)})}get closed(){return!!this.#r}post(e,t){if(this.#r)return;this.#i.push(e);if(t)this.#o.push(...t);this.#h()}pack(e){if(e.byteLength>=Vm)return Ym(e);let t;if(!this.#a||this.#c+e.byteLength>ll){this.#a=new Uint8Array(ll);this.#c=0;t=[this.#a.buffer]}const s=this.#a.subarray(this.#c,this.#c+e.byteLength);s.set(e);this.#c+=e.byteLength;return{bytes:s,transfer:t}}postOrExtend(e,t,s){if(this.#r)return;const i=this.#i.at(-1);if(!i||!e(i))this.#i.push(t());if(s)this.#o.push(...s);this.#h()}request(e,t){if(this.#r)return Promise.reject(this.#r);const s=this.#l++;return new Promise((i,n)=>{this.#s.set(s,{resolve:i,reject:n});this.post({...e,request:s},t)})}beforeSending(e){this.#n.add(e)}schedule(){if(!this.#r)this.#h()}flush(){this.#u=false;if(this.#r)return;for(const s of this.#n)s();this.#a=void 0;if(!this.#i.length)return;const e=this.#i;const t=this.#o;this.#i=[];this.#o=[];try{this.#e.postMessage(e,t)}catch(s){gc(\"a batch could not be sent: %O\",s);for(const i of e)if(i.request!==void 0)this.#d(i.request,void 0,s)}}close(e){this.#r??=e;this.#i=[];this.#o=[];for(const{reject:t}of this.#s.values())t(e);this.#s.clear()}#h(){if(this.#u)return;this.#u=true;setImmediate(()=>this.flush())}#f(e){if(e.type===\"reply\"){const i=this.#s.get(e.reply);this.#s.delete(e.reply);if(e.error===void 0)i?.resolve(e.result);else i?.reject(Qm(e.error));return}const t=e.request;let s;try{s=this.#t(e)}catch(i){if(t===void 0)gc(\"a message failed: %O\",i);else this.#d(t,void 0,i);return}if(t===void 0){if(s instanceof Promise)s.catch(i=>gc(\"a message failed: %O\",i));return}if(s instanceof Promise)s.then(i=>this.#d(t,i),i=>this.#d(t,void 0,i));else this.#d(t,s)}#d(e,t,s){if(this.#r)return;this.#i.push(s===void 0?{type:\"reply\",reply:e,result:t}:{type:\"reply\",reply:e,error:yi(s)});this.#h()}};function Po(r){return r?{type:r.type,sdp:r.sdp}:null}a(Po,\"plainDescription\");function pl(r){return{payloadType:r.payloadType,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,parameters:r.parameters,rtcpFeedback:r.rtcpFeedback.map(e=>({type:e.type,parameter:e.parameter}))}}a(pl,\"plainCodec\");function Xm(r){return{label:r.label,protocol:r.protocol,ordered:r.ordered,maxRetransmits:r.maxRetransmits,maxPacketLifeTime:r.maxPacketLifeTime,negotiated:r.negotiated,id:r.id??null,readyState:r.readyState}}a(Xm,\"infoOf\");var Jm=b(\"webrtc/peer/threads\");function gl(){if(!Ti.parentPort)throw new Error(\"The connections of a thread are served in a worker thread only\");const r=Ti.workerData;const e=new Map;const t=new Io(Ti.parentPort,p=>S(p));t.beforeSending(()=>{for(const p of e.values()){for(const f of p.changed)t.post({type:\"buffered\",conn:p.conn,ch:f.ref,amount:f.engine.bufferedAmount,applied:f.applied});p.changed.clear()}});const s=a(p=>{const f=e.get(p);if(!f)throw Object.assign(new Error(\"The connection is closed\"),{name:\"InvalidStateError\"});return f},\"servedOf\");const i=a((p,f,y)=>{let m=p.receivedRefs.get(f);if(m)return m;m=`r${p.next++}`;p.receivedRefs.set(f,m);p.received.set(m,{track:f,receiver:y});const T=m;f.once(\"ended\",()=>{p.received.get(T)?.unsubscribe?.();p.received.delete(T);t.post({type:\"trackEnded\",conn:p.conn,track:T})});return m},\"receivedRef\");const n=a((p,f,y)=>{let m=p.transceiverRefs.get(f);if(m)return m;m=y??`w${p.next++}`;p.transceiverRefs.set(f,m);p.transceivers.set(m,f);const T=m;f.sender.onPictureLossIndication.subscribe(()=>t.post({type:\"pli\",conn:p.conn,transceiver:T}));return m},\"transceiverRef\");const o=a((p,f)=>{const y=f.receiver.track;const m={ref:i(p,y,f.receiver),kind:y.kind,id:y.id??y.uuid,...y.codec?{codec:pl(y.codec)}:{}};const T=f.sender.track;return{ref:n(p,f),kind:f.kind,mid:f.mid,direction:f.direction,currentDirection:f.currentDirection,reusable:p.engine.reusableForTrack(f),sending:T?p.mirrorRefs.get(T)??null:null,...T?.codec?{sendingCodec:pl(T.codec)}:{},receiving:m}},\"transceiverInfo\");const c=a(p=>{const f=p.engine;const y=f.sctpTransport;const m=f.getConfiguration();return{connectionState:f.connectionState,iceConnectionState:f.iceConnectionState,iceGatheringState:f.iceGatheringState,signalingState:f.signalingState,localDescription:Po(f.localDescription),remoteDescription:Po(f.remoteDescription),maxMessageSize:y?y.remoteMaxMessageSize:null,configuration:{iceServers:m.iceServers,iceTransportPolicy:m.iceTransportPolicy},transceivers:f.getTransceivers().map(T=>o(p,T)),ops:p.ops,seq:++p.seq}},\"stateOf\");const d=a((p,f,y)=>{const m={ref:y,engine:f,applied:0};p.channels.set(y,m);f.stateChanged.subscribe(T=>{t.post({type:\"channelState\",conn:p.conn,ch:y,readyState:T,id:f.id??null});if(T===\"closed\")p.channels.delete(y)});f.onMessage.subscribe(T=>{p.engine.sctpTransport?.holdReceived(pr(T));const{bytes:C,transfer:E}=typeof T===\"string\"?{bytes:T,transfer:void 0}:t.pack(T);t.postOrExtend(P=>P.type===\"message\"&&P.conn===p.conn&&P.ch===y&&P.data.push(C)>0,()=>({type:\"message\",conn:p.conn,ch:y,data:[C]}),E)});f.bufferedAmountChanged.subscribe(()=>{p.changed.add(m);t.schedule()});f.error.subscribe(T=>t.post({type:\"channelError\",conn:p.conn,ch:y,error:yi(T)}));return m},\"adopt\");const h=a((p,f)=>{const y={conn:p,engine:f,channels:new Map,changed:new Set,transceivers:new Map,transceiverRefs:new WeakMap,mirrors:new Map,mirrorRefs:new WeakMap,received:new Map,receivedRefs:new WeakMap,next:1,ops:0,seq:0,rtpOut:0,rtpRead:0};e.set(p,y);f.onIceCandidate.subscribe(m=>{const T=m?{candidate:m.candidate,sdpMid:m.sdpMid??null,sdpMLineIndex:m.sdpMLineIndex??null,usernameFragment:m.usernameFragment??null}:null;t.post({type:\"event\",conn:p,name:\"icecandidate\",candidate:T,state:c(y)})});f.onDataChannel.subscribe(m=>{const T=`w${y.next++}`;d(y,m,T);t.post({type:\"datachannel\",conn:p,ch:T,info:Xm(m)})});f.on(\"track\",m=>{t.post({type:\"track\",conn:p,transceiver:o(y,m.transceiver),streams:m.streams.map(T=>T.id),state:c(y)})});f.onNegotiationneeded.subscribe(()=>t.post({type:\"event\",conn:p,name:\"negotiationneeded\",state:c(y)}));f.connectionStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"connectionstatechange\",value:m,state:c(y)}));f.iceConnectionStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"iceconnectionstatechange\",value:m,state:c(y)}));f.iceGatheringStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"icegatheringstatechange\",value:m,state:c(y)}));f.signalingStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"signalingstatechange\",value:m,state:c(y)}));return y},\"open\");const l=a((p,f)=>{const y=p.mirrors.get(f);if(!y)throw new Error(`The track ${f} is not known`);return y},\"mirrorOf\");const u=a((p,f)=>{const y=p.transceivers.get(f);if(!y)throw new Error(`The transceiver ${f} is not known`);return y},\"transceiverOf\");const g=a(async(p,f)=>{const y=a(m=>m.map(T=>new us({id:T})),\"streams\");try{switch(f.type){case\"addTrack\":{const m=f.transceiver===null?null:p.transceivers.get(f.transceiver)??null;const T=p.engine.addTrackOn(m,l(p,f.track),...y(f.streams));const C=p.engine.getTransceivers().find(E=>E.sender===T);if(C)n(p,C,f.created);break}case\"addTransceiver\":{const m=p.engine.addTransceiver(f.track===void 0?f.kind:l(p,f.track),{direction:f.direction,streams:y(f.streams)});n(p,m,f.created);break}case\"removeTrack\":p.engine.removeTrack(u(p,f.transceiver).sender);break;case\"direction\":u(p,f.transceiver).direction=f.direction;break;case\"stopTransceiver\":u(p,f.transceiver).stop();break;case\"replaceTrack\":await u(p,f.transceiver).sender.replaceTrack(f.track===null?null:l(p,f.track));break;case\"setStreams\":u(p,f.transceiver).sender.setStreams(y(f.streams));break}}finally{p.ops=Math.max(p.ops,f.op);t.post({type:\"state\",conn:p.conn,state:c(p)})}},\"change\");const S=a(async p=>{switch(p.type){case\"open\":{const f=h(p.conn,new vo(ul(p.options)));return c(f)}case\"call\":{const f=s(p.conn);const y=f.engine;let m;switch(p.method){case\"createOffer\":m=Po(await y.createOffer(p.args[0]));break;case\"createAnswer\":m=Po(await y.createAnswer());break;case\"setLocalDescription\":await y.setLocalDescription(p.args[0]);break;case\"setRemoteDescription\":await y.setRemoteDescription(p.args[0]);break;case\"addIceCandidate\":{const T=p.args[0];await y.addIceCandidate({candidate:T.candidate,sdpMid:T.sdpMid??void 0,sdpMLineIndex:T.sdpMLineIndex??void 0,usernameFragment:T.usernameFragment??void 0});break}}return{result:m,state:c(f)}}case\"close\":{const f=e.get(p.conn);if(!f)return void 0;await f.engine.close();for(const y of f.mirrors.values())y.stop();e.delete(p.conn);return c(f)}case\"restartIce\":return s(p.conn).engine.restartIce();case\"setConfiguration\":return s(p.conn).engine.setConfiguration(p.configuration);case\"channel\":{const f=s(p.conn);let y;try{y=f.engine.createDataChannel(p.label,p.options)}catch(m){t.post({type:\"channelError\",conn:p.conn,ch:p.ch,error:yi(m)});t.post({type:\"channelState\",conn:p.conn,ch:p.ch,readyState:\"closed\",id:null});return void 0}d(f,y,p.ch);t.post({type:\"channelState\",conn:p.conn,ch:p.ch,readyState:y.readyState,id:y.id??null});return void 0}case\"send\":{const f=e.get(p.conn);const y=f?.channels.get(p.ch);if(!f||!y)return void 0;f.changed.add(y);for(const m of p.data){const T=typeof m===\"string\"?m:Buffer.from(m.buffer,m.byteOffset,m.byteLength);y.applied+=pr(T);try{y.engine.send(T)}catch(C){t.post({type:\"channelError\",conn:p.conn,ch:p.ch,error:yi(C)})}}return void 0}case\"closeChannel\":return e.get(p.conn)?.channels.get(p.ch)?.engine.close();case\"mirror\":{const f=s(p.conn);const y=new Be({kind:p.kind,id:p.id,remote:p.remote,...p.codec?{codec:new re(p.codec)}:{}});f.mirrors.set(p.track,y);f.mirrorRefs.set(y,p.track);return void 0}case\"rtp\":{const f=e.get(p.conn);if(!f)return void 0;const y=f.mirrors.get(p.track);if(!f.rtpRead){setImmediate(()=>{t.post({type:\"consumed\",conn:f.conn,rtp:f.rtpRead});f.rtpRead=0})}for(const m of p.packets)f.rtpRead+=m.byteLength;p.packets.forEach((m,T)=>{y?.applyIncomingRtp(W.deSerialize(Buffer.from(m.buffer,m.byteOffset,m.byteLength)),p.extensions[T]??void 0)});return void 0}case\"consumed\":{const f=e.get(p.conn);if(!f)return void 0;f.rtpOut-=p.rtp;if(p.bytes)f.engine.sctpTransport?.releaseReceived(p.bytes);return void 0}case\"source\":return e.get(p.conn)?.mirrors.get(p.track)?.onSourceChanged.execute(p.header);case\"mirrorEnded\":return e.get(p.conn)?.mirrors.get(p.track)?.stop();case\"dropTrack\":{const f=e.get(p.conn);f?.mirrors.get(p.track)?.stop();f?.mirrors.delete(p.track);return void 0}case\"addTrack\":case\"addTransceiver\":case\"removeTrack\":case\"direction\":case\"stopTransceiver\":case\"replaceTrack\":case\"setStreams\":return await g(s(p.conn),p);case\"keyframe\":{const f=e.get(p.conn)?.received.get(p.track);const y=f?.track.ssrc;if(f&&y!==void 0)void f.receiver.sendRtcpPLI(y);return void 0}case\"want\":{const f=e.get(p.conn);const y=f?.received.get(p.track);if(!f||!y)return void 0;y.unsubscribe?.();y.unsubscribe=void 0;if(p.wanted){const m=p.track;y.unsubscribe=y.track.onReceiveRtp.subscribe((T,C)=>{const E=T.serialize();if(f.rtpOut+E.length>fl)return Jm(\"a packet of the track %s dropped: the main thread reads too slowly\",m);f.rtpOut+=E.length;const{bytes:P,transfer:de}=t.pack(E);t.postOrExtend(q=>q.type===\"rtp\"&&q.conn===f.conn&&q.track===m&&q.packets.push(P)>0&&q.extensions.push(C??null)>0,()=>({type:\"rtp\",conn:f.conn,track:m,packets:[P],extensions:[C??null]}),de)}).unSubscribe}return void 0}case\"debug\":return kc(p.enabled?(f,y)=>t.post({type:\"log\",namespace:f,message:`[thread ${r.thread}] ${(0,ml.format)(...y)}`}):void 0);case\"stop\":{const f=[...e.values()];e.clear();await Promise.all(f.map(y=>y.engine.close()));return void 0}}},\"handle\");t.post({type:\"ready\"})}a(gl,\"runPeerWorker\");gl();\n";
1
+ export const peerWorkerCode = "var Sl=Object.create;var wi=Object.defineProperty;var yl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var wl=Object.getPrototypeOf;var bl=Object.prototype.hasOwnProperty;var a=(r,e)=>wi(r,\"name\",{value:e,configurable:true});var Cl=(r,e)=>{for(var t in e)wi(r,t,{get:e[t],enumerable:true})};var El=(r,e,t,s)=>{if(e&&typeof e===\"object\"||typeof e===\"function\"){for(let i of Tl(e))if(!bl.call(r,i)&&i!==t)wi(r,i,{get:()=>e[i],enumerable:!(s=yl(e,i))||s.enumerable})}return r};var bi=(r,e,t)=>(t=r!=null?Sl(wl(r)):{},El(e||!r||!r.__esModule?wi(t,\"default\",{value:r,enumerable:true}):t,r));var ml=require(\"node:util\");var Ti=require(\"node:worker_threads\");var zc=require(\"node:crypto\");var Ao=require(\"node:crypto\");function _o(){return(0,Ao.randomBytes)(2).readUInt16BE(0)}a(_o,\"random16\");function Ci(){return(0,Ao.randomBytes)(4).readUInt32BE(0)}a(Ci,\"random32\");var ze=class{static{a(this,\"BitWriter\")}constructor(e){this.bitLength=e;this.value=0}set(e,t,s){s&=(1<<e)-1;this.value|=s<<this.bitLength-e-t;return this}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};var gt=class{static{a(this,\"BitWriter2\")}constructor(e){this.bitLength=e;this._value=0n;this.offset=0n;if(e>32){throw new Error}}set(e,t=1){let s=BigInt(e);const i=BigInt(t);s&=(1n<<i)-1n;this._value|=s<<BigInt(this.bitLength)-i-this.offset;this.offset+=i;return this}get value(){return Number(this._value)}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};function k(r,e,t=1){const s=Math.min(e+t,8);return r>>8-s&(1<<s-e)-1}a(k,\"getBit\");function N(r,e){return or(r)(e)}a(N,\"bufferWriter\");function or(r,e){const t=r.reduce((i,n)=>i+n,0);const s=e?Buffer.alloc(t):void 0;return i=>{const n=s||Buffer.alloc(t);let o=0;i.forEach((c,d)=>{const h=r[d];if(h===8)n.writeBigUInt64BE(c,o);else n.writeUIntBE(c,o,h);o+=h});return n}}a(or,\"createBufferWriter\");function F(r,e){let t=0;return e.map(s=>{let i;if(s===8){i=r.readBigUInt64BE(t)}else{i=r.readUIntBE(t,s)}t+=s;return i})}a(F,\"bufferReader\");var Pe=class{static{a(this,\"BitStream\")}constructor(e){this.uint8Array=e;this.position=0;this.bitsPending=0}writeBits(e,t){if(e==0){return this}t&=4294967295>>>32-e;let s;if(this.bitsPending>0){if(this.bitsPending>e){this.uint8Array[this.position-1]|=t<<this.bitsPending-e;s=e;this.bitsPending-=e}else if(this.bitsPending==e){this.uint8Array[this.position-1]|=t;s=e;this.bitsPending=0}else{this.uint8Array[this.position-1]|=t>>e-this.bitsPending;s=this.bitsPending;this.bitsPending=0}}else{s=Math.min(8,e);this.bitsPending=8-s;this.uint8Array[this.position++]=t>>e-s<<this.bitsPending}e-=s;if(e>0){this.writeBits(e,t)}return this}readBits(e){return this._readBits(e)}_readBits(e,t){if(typeof t==\"undefined\"){t=0}if(e==0){return t}let s;let i;if(this.bitsPending>0){const n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;i=Math.min(this.bitsPending,e);this.bitsPending-=i;s=n>>this.bitsPending}else{i=Math.min(8,e);this.bitsPending=8-i;s=this.uint8Array[this.position++]>>this.bitsPending}e-=i;t=t<<i|s;return e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0;this.bitsPending=e%8;if(this.bitsPending>0){this.bitsPending=8-this.bitsPending;this.position++}}};var Rl=3988292384;var xl=2197175160;function yc(r){return typeof r!==\"string\"}a(yc,\"isBufferLike\");function Tc(r){const e=new Array(256);for(let t=0;t<256;++t){let s=t;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;s=s&1?r^s>>>1:s>>>1;e[t]=s}return new Int32Array(e)}a(Tc,\"generateCRCTable\");function wc(r){const e=new Int32Array(4096);let t;let s;let i;for(i=0;i<256;++i)e[i]=r[i];for(i=0;i<256;++i){s=r[i];for(t=256+i;t<4096;t+=256){s=e[t]=s>>>8^r[s&255]}}const n=[];for(i=1;i<16;++i){n[i-1]=e.subarray(i*256,i*256+256)}return n}a(wc,\"generateSliceBy16Tables\");function bc(r,e,t){let s=e^-1;let i=0;const n=r.length;let o;let c;while(i<n){o=r.charCodeAt(i++);if(o<128){s=s>>>8^t[(s^o)&255]}else if(o<2048){s=s>>>8^t[(s^(192|o>>6&31))&255];s=s>>>8^t[(s^(128|o&63))&255]}else if(o>=55296&&o<57344){o=(o&1023)+64;c=r.charCodeAt(i++)&1023;s=s>>>8^t[(s^(240|o>>8&7))&255];s=s>>>8^t[(s^(128|o>>2&63))&255];s=s>>>8^t[(s^(128|c>>6&15|(o&3)<<4))&255];s=s>>>8^t[(s^(128|c&63))&255]}else{s=s>>>8^t[(s^(224|o>>12&15))&255];s=s>>>8^t[(s^(128|o>>6&63))&255];s=s>>>8^t[(s^(128|o&63))&255]}}return~s>>>0}a(bc,\"crcGenericString\");function Cc(r,e,t,s){const[i,n,o,c,d,h,l,u,g,S,p,f,y,m,T]=s;let C=e^-1;let E=0;let P=r.length-15;while(E<P){C=T[r[E++]^C&255]^m[r[E++]^C>>>8&255]^y[r[E++]^C>>>16&255]^f[r[E++]^C>>>24]^p[r[E++]]^S[r[E++]]^g[r[E++]]^u[r[E++]]^l[r[E++]]^h[r[E++]]^d[r[E++]]^c[r[E++]]^o[r[E++]]^n[r[E++]]^i[r[E++]]^t[r[E++]]}for(P+=15;E<P;){C=C>>>8^t[(C^r[E++])&255]}return~C>>>0}a(Cc,\"crcBuffer\");var Bo=Tc(Rl);var kl=wc(Bo);var Lo=Tc(xl);var vl=wc(Lo);function Ec(r,e=0){if(yc(r)){return Cc(r,e,Bo,kl)}return bc(r,e,Bo)}a(Ec,\"crc32\");function ar(r,e=0){if(yc(r)){return Cc(r,e,Lo,vl)}return bc(r,e,Lo)}a(ar,\"crc32c\");function Rc(r,e){return r+e&255}a(Rc,\"uint8Add\");function j(r,e){return r+e&65535}a(j,\"uint16Add\");function Ae(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}a(Ae,\"uint32Add\");function Ei(r,e){const t=32768;return r<e&&e-r>t||r>e&&r-e<t}a(Ei,\"uint16Gt\");function ae(r,e){const t=2147483648;return r<e&&e-r>t||r>e&&r-e<t}a(ae,\"uint32Gt\");function Xt(r,e){return r===e||ae(r,e)}a(Xt,\"uint32Gte\");var at=a(r=>Number.parseInt(r,10),\"int\");function K(r,e){try{const t=r();if(t instanceof Promise)t.catch(e)}catch(t){e(t)}}a(K,\"runDetached\");function ye(r,e){return(...t)=>{try{const s=r(...t);if(s instanceof Promise)s.catch(e)}catch(s){e(s)}}}a(ye,\"detached\");var Do=require(\"node:dgram\");var Ri=a((r,e)=>e?e[r]:void 0,\"interfaceAddress\");async function xi(r=\"udp4\",e){const t=(0,Do.createSocket)(r);setImmediate(()=>t.bind({port:0,address:Ri(r,e)}));await new Promise(i=>{t.once(\"error\",i);t.once(\"listening\",i)});const s=t.address()?.port;await new Promise(i=>t.close(()=>i()));return s}a(xi,\"randomPort\");async function xc(r,e,t=\"udp4\",s){let i;for(let n=r;n<=e;n++){const o=(0,Do.createSocket)(t);setImmediate(()=>o.bind({port:n,address:Ri(t,s)}));const c=await new Promise(d=>{o.once(\"error\",h=>d(h));o.once(\"listening\",()=>d())});if(c){await new Promise(d=>o.close(()=>d()));continue}i=o.address()?.port;await new Promise(d=>o.close(()=>d()));if(r<=i&&i<=e){break}}if(!i)throw new Error(\"port not found\");return i}a(xc,\"findPort\");function St(r){if(r===\"IPv4\")return 4;if(r===\"IPv6\")return 6;return r}a(St,\"normalizeFamilyNodeV18\");var ki;var Il=new Set;function kc(r){const e=!!ki!==!!r;ki=r;if(e)for(const t of Il)t(!!r)}a(kc,\"setDebugHandler\");function b(r){return(...e)=>{if(ki)ki(r,e)}}a(b,\"debug\");var vi=class{static{a(this,\"Subscribers\")}constructor(){this.list=[];this.size=0;this.#e=0}#e;add(e){this.list.push(e);this.size++}remove(e){if(e.removed)return false;e.removed=true;this.size--;if(++this.#e>16&&this.#e>this.size){this.list=this.list.filter(t=>!t.removed);this.#e=0}return true}clear(){for(const e of this.list)e.removed=true;this.list=[];this.size=0;this.#e=0}};var w=class{static{a(this,\"Event\")}constructor(){this.subscribers=new vi;this.queued=new vi;this.ended=false;this.onerror=e=>{};this.execute=(...e)=>{if(this.ended){return}for(const t of this.subscribers.list){if(!t.removed)t.execute(...e)}if(this.queued.size===0)return;(async()=>{for(const t of this.queued.list){if(!t.removed)await t.execute(...e)}})().catch(t=>{this.onerror(t)})};this.complete=()=>{if(this.ended){return}for(const e of this.subscribers.list){if(e.complete&&!e.removed){e.complete()}}this.allUnsubscribe();this.ended=true;if(this.onended){this.onended();this.onended=void 0}};this.error=e=>{if(this.ended){return}for(const t of this.subscribers.list){if(t.error&&!t.removed){t.error(e)}}this.allUnsubscribe()};this.allUnsubscribe=()=>{if(this.ended){return}this.subscribers.clear();this.queued.clear();this.onsubscriberschange?.()};this.subscribe=(e,t,s)=>{const i={execute:e,complete:t,error:s};const n=this.subscribers;n.add(i);this.onsubscriberschange?.();const o=a(()=>{if(n.remove(i))this.onsubscriberschange?.()},\"unSubscribe\");const c=a(d=>{d.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.queuingSubscribe=(e,t,s)=>{if(this.ended)throw new Error(\"event completed\");const i={execute:e,complete:t,error:s};const n=this.queued;n.add(i);const o=a(()=>{n.remove(i)},\"unSubscribe\");const c=a(d=>{d.push(o)},\"disposer\");return{unSubscribe:o,disposer:c}};this.once=(e,t,s)=>{const i=this.subscribe((...n)=>{i.unSubscribe();e(...n)},t,s)};this.watch=(e,t)=>new Promise((s,i)=>{const n=t&&setTimeout(()=>{i(\"Event watch timeout\")},t);const{unSubscribe:o}=this.subscribe((...c)=>{const d=e(...c);if(d){if(n)clearTimeout(n);o();s(c)}})});this.asPromise=e=>new Promise((t,s)=>{const i=e&&setTimeout(()=>{s(\"Event asPromise timeout\")},e);this.once((...n)=>{if(i)clearTimeout(i);t(n)},()=>{if(i)clearTimeout(i);t([])},n=>{if(i)clearTimeout(i);s(n)})})}pipe(e){this.subscribe((...t)=>{e.execute(...t)})}get returnTrigger(){const{execute:e,error:t,complete:s}=this;return{execute:e,error:t,complete:s}}get returnListener(){const{subscribe:e,once:t,asPromise:s}=this;return{subscribe:e,once:t,asPromise:s}}get length(){return this.subscribers.size}};var Ii=class{static{a(this,\"EventDisposer\")}constructor(){this._disposer=[]}push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e());this._disposer=[]}};var Ic=require(\"node:dgram\");var No=bi(require(\"node:net\"),1);var Pc=bi(require(\"node:tls\"),1);var Ac=require(\"node:net\");var qe=b(\"webrtc/common/transport\");var Pl=8e3;var vc=4*1024*1024;function Al(r){try{if(r.getRecvBufferSize()<vc)r.setRecvBufferSize(vc)}catch(e){qe(\"the receive buffer cannot grow\",e)}}a(Al,\"growReceiveBuffer\");function _l(r,e){return r===e||r[1]===e[1]&&r[0]===e[0]}a(_l,\"sameAddress\");var yt=class r{static{a(this,\"UdpTransport\")}constructor(e,t={}){this.socketType=e;this.options=t;this.type=\"udp\";this.onData=()=>{};this.closed=false;this.send=async(s,i)=>{const n=this.connected;if(n){if(!i||_l(i,n)){this.socket.send(s)}else{qe(\"not sent to an address other than the connected one\",i)}return}if(this.waiting){this.waiting.push([s,i]);return}if(i&&!No.isIP(i[0])){return new Promise((o,c)=>{this.socket.send(s,i[1],i[0],d=>{if(d){qe(\"send error\",i,s);c(d)}else{o()}})})}else{i=i??[this.rinfo.address,this.rinfo.port];this.socket.send(s,i[1],i[0])}};this.close=()=>new Promise(s=>{this.closed=true;this.connectOnReceive=void 0;this.connecting=void 0;this.connected=void 0;this.waiting=void 0;this.socket.once(\"close\",s);try{this.socket.close()}catch(i){s()}});this.socket=(0,Ic.createSocket)(e);this.socket.on(\"message\",(s,i)=>{if(St(i.family)===6){[i.address]=i.address.split(\"%\")}this.rinfo=i;if(this.connectOnReceive&&s[0]>3&&i.port===this.connectOnReceive[1]&&i.address===this.connectOnReceive[0])this.connectNow(this.connectOnReceive);try{this.onData(s,[i.address,i.port])}catch(n){qe(\"onData error\",n)}})}static async init(e,t={}){const s=new r(e,t);await s.init();return s}async init(){const e=Ri(this.socketType,this.options.interfaceAddresses);if(this.options.port){this.socket.bind({port:this.options.port,address:e})}else if(this.options.portRange){const t=await xc(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else{this.socket.bind({port:await xi(this.socketType,this.options.interfaceAddresses),address:e})}await new Promise((t,s)=>{const i=a(n=>s(n),\"failed\");this.socket.once(\"error\",i);this.socket.once(\"listening\",()=>{this.socket.off(\"error\",i);t()})});this.socket.on(\"error\",t=>qe(\"socket error\",t));Al(this.socket)}connectTo(e){if(this.closed||this.connected||this.waiting||!No.isIP(e[0]))return;this.connectOnReceive=e}disconnect(){this.connectOnReceive=void 0;this.connecting=void 0;if(!this.connected)return;this.connected=void 0;try{this.socket.disconnect()}catch(e){qe(\"disconnect\",e)}}connectNow(e){this.connectOnReceive=void 0;this.connecting=e;const t=[];this.waiting=t;const s=a(i=>{if(this.waiting===t)this.waiting=void 0;const n=this.connecting===e;if(n)this.connecting=void 0;if(this.closed)return;if(i){qe(\"connect\",e,i)}else if(n){this.connected=e}else{this.socket.disconnect()}for(const[o,c]of t)this.send(o,c).catch(d=>qe(\"send\",d))},\"done\");try{this.socket.connect(e[1],e[0],s)}catch(i){s(i)}}get address(){return this.socket.address()}get addressFamily(){return this.socketType===\"udp6\"?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}};var cr=class r{static{a(this,\"TcpTransport\")}constructor(e,t={}){this.type=\"tcp\";this.send=async(s,i)=>{await this.stream.send(s,i)};this.close=async()=>{await this.stream.close()};this.stream=new Pi(\"tcp\",()=>(0,Ac.connect)({port:e[1],host:e[0]}),void 0,t.connectTimeoutMs)}static async init(e,t={}){const s=new r(e,t);try{await s.init();return s}catch(i){await s.close();throw i}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var dr=class r{static{a(this,\"TlsTransport\")}constructor(e,t={},s={}){this.type=\"tls\";this.send=async(i,n)=>{await this.stream.send(i,n)};this.close=async()=>{await this.stream.close()};this.stream=new Pi(\"tls\",()=>Pc.connect({...t,host:e[0],port:e[1]}),void 0,s.connectTimeoutMs)}static async init(e,t={},s={}){const i=new r(e,t,s);try{await i.init();return i}catch(n){await i.close();throw n}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}};var Pi=class{static{a(this,\"StreamTransport\")}constructor(e,t,s=e===\"tls\"?\"secureConnect\":\"connect\",i=Pl){this.createClient=t;this.connectEvent=s;this.connectTimeoutMs=i;this.onData=()=>{};this.closed=false;this.send=async(n,o)=>{void o;await this.connecting;await new Promise((c,d)=>{this.client.write(n,h=>{if(h){d(h);return}c()})})};this.close=async()=>{this.closed=true;this.rejectConnecting?.(new Error(`${this.type} transport closed`));this.client?.destroy()};this.type=e;this.connect()}connect(){if(this.closed){return}if(this.client){this.client.destroy()}const e=this.createClient();this.client=e;this.connecting=new Promise((t,s)=>{let i=false;const n=a(h=>{if(i)return;i=true;clearTimeout(d);e.off(this.connectEvent,o);e.off(\"error\",c);this.rejectConnecting=void 0;h?s(h):t()},\"settle\");const o=a(()=>{n()},\"onConnect\");const c=a(h=>{this.closed=true;n(h);e.destroy()},\"onConnectError\");const d=setTimeout(()=>{this.closed=true;n(new Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`));e.destroy()},this.connectTimeoutMs);this.rejectConnecting=h=>n(h);e.once(this.connectEvent,o);e.once(\"error\",c)});e.on(\"data\",t=>{this.onData(t,this.remoteAddress)});e.on(\"error\",t=>{qe(`${this.type} transport error`,t)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){const{remoteAddress:e,remotePort:t}=this.client;if(!e||!t){return void 0}return[Bl(e),t]}};function Bl(r){return r.split(\"%\")[0]}a(Bl,\"stripZoneId\");var x={};Cl(x,{BinaryReader:()=>_i,BinaryWriter:()=>ur,NotEnoughDataError:()=>Ai,decode:()=>Dl,encode:()=>Ll,types:()=>Ul});var Ai=class extends Error{static{a(this,\"NotEnoughDataError\")}constructor(e,t){super(`requested ${e} bytes but only ${t} available`);this.name=\"NotEnoughDataError\"}};var _i=class{static{a(this,\"BinaryReader\")}constructor(e){this.buf=e;this.offset=0}get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(e){this.assertSize(e);const t=this.buf.subarray(this.offset,this.offset+e);this.offset+=e;return t}readUIntBE(e){this.assertSize(e);const t=this.buf.readUIntBE(this.offset,e);this.offset+=e;return t}assertSize(e){if(e>this.length){throw new Ai(e,this.length)}}};var ur=class{static{a(this,\"BinaryWriter\")}constructor(){this.chunks=[];this.written=0}get bytes(){return this.written}writeBuffer(e){this.chunks.push(e);this.written+=e.length}writeUIntBE(e,t){const s=Buffer.allocUnsafe(t);switch(t){case 1:s.writeUInt8(e,0);break;case 2:s.writeUInt16BE(e,0);break;case 4:s.writeUInt32BE(e,0);break;default:s.writeUIntBE(e,0,t)}this.writeBuffer(s)}toBuffer(){return Buffer.concat(this.chunks,this.written)}};var Bc=a(r=>typeof r===\"object\"&&r!==null,\"isObject\");var se=a(r=>Bc(r)&&typeof r.encode===\"function\"&&typeof r.decode===\"function\",\"isType\");var Lc=a(r=>{if(!Bc(r))return false;const e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},\"isPlainObject\");var Dc=a(()=>({node:void 0,current:void 0}),\"createContext\");var _c=a(r=>({node:r.node,current:r.current}),\"cloneContext\");var Nc=a((r,e)=>{if(!Lc(r)){throw new TypeError(e)}},\"assertSchema\");var Mc=a((r,e,t,s)=>{if(se(e)){e.encode(r,t,s)}else{Oc(r,e,t,s)}},\"encodeCommon\");var Oc=a((r,e,t,s)=>{Nc(e,\"Argument `schema` should be a plain object.\");if(s.node===void 0){s.node=r}s.current=r;for(const i of Object.keys(e)){const n=e[i];const o=r[i];if(se(n)){n.encode(o,t,s)}else{Oc(o,n,t,s);s.current=r}}},\"encodeSchema\");var Mo=a((r,e,t)=>{if(se(e)){return e.decode(r,t)}return Uc(r,e,t)},\"decodeCommon\");var Uc=a((r,e,t)=>{Nc(e,\"Argument #2 should be a plain object.\");const s=Object.create(null);if(t.node===void 0){t.node=s}t.current=s;for(const i of Object.keys(e)){const n=e[i];if(se(n)){s[i]=n.decode(r,t)}else{s[i]=Uc(r,n,t);t.current=s}}return s},\"decodeSchema\");function Ll(r,e){const t=new ur;Mc(r,e,t,Dc());return t.toBuffer()}a(Ll,\"encode\");function Dl(r,e){return Mo(new _i(r),e,Dc())}a(Dl,\"decode\");var hr=a(r=>({encode:a((e,t)=>t.writeUIntBE(e,r),\"encode\"),decode:a(e=>e.readUIntBE(r),\"decode\")}),\"createUIntBE\");var Oo=a(r=>{if(typeof r!==\"number\"&&!se(r)&&typeof r!==\"function\"){throw new TypeError(\"Unknown type of argument #1.\")}},\"assertLengthSpec\");var lr=a((r,e,t)=>{if(r!==e){throw new Error(`${t} required length ${r} instead of ${e}`)}},\"checkLength\");var Tt=a((r,e)=>{if(typeof r!==\"number\"){throw new TypeError(e)}},\"checkLengthType\");function Nl(r){Oo(r);const e=\"Length of a buffer should be a number.\";return{encode(t,s,i){if(!Buffer.isBuffer(t)){throw new TypeError(\"Argument 1 should be a Buffer or a BinaryStream.\")}if(typeof r===\"number\"){lr(r,t.length,\"Buffer\")}else if(se(r)){r.encode(t.length,s,i)}else{const n=r(i);Tt(n,e);lr(n,t.length,\"Buffer\")}s.writeBuffer(t)},decode(t,s){let i;if(typeof r===\"number\"){i=r}else if(se(r)){i=r.decode(t,s)}else{i=r(s)}Tt(i,e);return t.readBuffer(i)}}}a(Nl,\"buffer\");function Ml(r,e,t=\"count\"){if(!se(r)&&!Lc(r)){throw new TypeError(\"Argument #1 should be a valid type.\")}Oo(e);const s=t===\"bytes\";const i=\"Length of an array should be a number.\";return{encode(n,o,c){if(!Array.isArray(n)){throw new TypeError(\"Argument #1 should be an Array.\")}const d=_c(c);let h;if(typeof e===\"number\"){h=e}else if(se(e)){h=n.length}else{h=e(d);Tt(h,i)}const l=new ur;for(const u of n){Mc(u,r,l,d)}if(s){if(se(e)){h=l.bytes}lr(l.bytes,h,\"Argument #1\")}else{lr(h,n.length,\"Argument #1\")}if(se(e)){e.encode(h,o,d)}o.writeBuffer(l.toBuffer())},decode(n,o){const c=_c(o);let d;if(typeof e===\"number\"){d=e}else if(se(e)){d=e.decode(n,c)}else{d=e(c)}Tt(d,i);const h=[];if(s){const l=n.bytes;let u=0;while(u<d){h.push(Mo(n,r,c));u=n.bytes-l}if(u>d){throw new Error(\"Incorrect length of an array.\")}}else{for(let l=0;l<d;l++){h.push(Mo(n,r,c))}}return h}}}a(Ml,\"array\");function Ol(r,e=\"ascii\"){if(!Buffer.isEncoding(e)){throw new Error(\"Argument #2 should be an encoding name.\")}Oo(r);const t=\"Length of a buffer should be a number.\";return{encode(s,i,n){const o=Buffer.from(s.toString(),e);if(typeof r===\"number\"){if(o.length!==r){throw new Error(`Size of string should be ${r} in bytes.`)}}else if(se(r)){r.encode(o.length,i,n)}else{const c=r(n);Tt(c,t);lr(c,o.length,\"Buffer\")}i.writeBuffer(o)},decode(s,i){let n;if(typeof r===\"number\"){n=r}else if(se(r)){n=r.decode(s,i);Tt(n,\"Size of a string should be a number.\")}else{n=r(i);Tt(n,t)}return s.readBuffer(n).toString(e)}}}a(Ol,\"string\");var Ul={uint8:hr(1),uint16be:hr(2),uint24be:hr(3),uint32be:hr(4),uint48be:hr(6),buffer:Nl,array:Ml,string:Ol};var fr=class{static{a(this,\"Deque\")}#e=new Array(16);#t=0;#s=0;get length(){return this.#s}push(e){if(this.#s===this.#e.length)this.#n();this.#e[this.#t+this.#s&this.#e.length-1]=e;this.#s++}unshift(e){if(this.#s===this.#e.length)this.#n();this.#t=this.#t-1&this.#e.length-1;this.#e[this.#t]=e;this.#s++}shift(){if(!this.#s)return void 0;const e=this.#e[this.#t];this.#e[this.#t]=void 0;this.#t=this.#t+1&this.#e.length-1;this.#s--;return e}at(e){const t=e<0?this.#s+e:e;if(t<0||t>=this.#s)return void 0;return this.#e[this.#t+t&this.#e.length-1]}findIndex(e){for(let t=0;t<this.#s;t++){if(e(this.#e[this.#t+t&this.#e.length-1]))return t}return-1}clear(){this.#e=new Array(16);this.#t=0;this.#s=0}*[Symbol.iterator](){for(let e=0;e<this.#s;e++)yield this.#e[this.#t+e&this.#e.length-1]}#n(){const e=new Array(this.#e.length*2);for(let t=0;t<this.#s;t++)e[t]=this.#e[this.#t+t&this.#e.length-1];this.#e=e;this.#t=0}};var Hc=require(\"node:events\");var Ng=b(\"webrtc/peer/helper\");function Uo(r){return r.map((e,t)=>[t,e])}a(Uo,\"enumerate\");function _e(r,e){const t=r.split(e);return[t[0],t.slice(1).join(e)]}a(_e,\"divide\");var he=class extends Hc.EventEmitter{static{a(this,\"EventTarget\")}constructor(){super(...arguments);this.addEventListener=(e,t,s)=>{if(typeof s===\"object\"&&s?.once){this.once(e,t);return}this.addListener(e,t)};this.removeEventListener=(e,t)=>{this.removeListener(e,t)};this.dispatchEvent=e=>this.emit(e.type,e)}emit(e,...t){if(typeof e!==\"string\"){return super.emit(e,...t)}if(t.length===0){return super.emit(e,new Event(e))}const[s,...i]=t;if(s&&typeof s===\"object\"&&!(\"type\"in s)){try{Object.defineProperty(s,\"type\",{configurable:true,enumerable:true,value:e})}catch{return super.emit(e,{type:e,...s},...i)}}return super.emit(e,s,...i)}};var Bi=b(\"webrtc/peer/dataChannel\");function pr(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}a(pr,\"getDataChannelMessageSize\");var Jt=class extends he{static{a(this,\"RTCDataChannel\")}constructor(e,t,s=true){super();this.sctp=e;this.parameters=t;this.sendOpen=s;this.statsId=(0,zc.randomUUID)().toString();this.stateChange=new w;this.stateChanged=new w;this.onMessage=new w;this.error=new w;this.bufferedAmountLow=new w;this.bufferedAmountChanged=new w;this.isCreatedByRemote=false;this.readyState=\"connecting\";this.bufferedAmount=0;this._bufferedAmountLowThreshold=0;this.messagesSent=0;this.bytesSent=0;this.messagesReceived=0;this.bytesReceived=0;this.id=this.parameters.id;if(t.negotiated){if(this.id==void 0||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{if(s){this.sendOpen=false;this.sctp.dataChannelOpen(this)}}}get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){if(e<0||e>4294967295){throw new Error(\"bufferedAmountLowThreshold must be in range 0 - 4294967295\")}this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){this.readyState=e;this.stateChange.execute(e);this.stateChanged.execute(e);switch(e){case\"open\":if(this.onopen)K(()=>this.onopen(),t=>Bi(\"onopen failed\",t));this.emit(\"open\");break;case\"closed\":if(this.onclose)K(()=>this.onclose(),t=>Bi(\"onclose failed\",t));this.emit(\"close\");break;case\"closing\":if(this.onclosing)K(()=>this.onclosing(),t=>Bi(\"onclosing failed\",t));break}Bi(\"change state\",e)}}addBufferedAmount(e){const t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e;this.bufferedAmountChanged.execute();if(t){this.bufferedAmountLow.execute();this.emit(\"bufferedamountlow\")}}send(e){const t=this.sctp.datachannelSend(this,e);this.messagesSent++;this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}};var Zt=class{static{a(this,\"RTCDataChannelParameters\")}constructor(e={}){this.label=\"\";this.ordered=true;this.protocol=\"\";this.negotiated=false;Object.assign(this,e)}};var re=class{static{a(this,\"RTCRtpCodecParameters\")}constructor(e){this.rtcpFeedback=[];this.direction=\"all\";Object.assign(this,e)}get name(){return this.mimeType.split(\"/\")[1]}get contentType(){return this.mimeType.split(\"/\")[0]}get str(){let e=`${this.name}/${this.clockRate}`;if(this.channels===2)e+=\"/2\";return e}};var Te=class{static{a(this,\"RTCRtpHeaderExtensionParameters\")}constructor(e){Object.assign(this,e)}};var Li=class{static{a(this,\"RTCRtcpFeedback\")}constructor(e={}){Object.assign(this,e)}};var Di=class{static{a(this,\"RTCRtpRtxParameters\")}constructor(e={}){Object.assign(this,e)}};var Ni=class{static{a(this,\"RTCRtpCodingParameters\")}constructor(e){Object.assign(this,e)}};var es=class{static{a(this,\"RTCRtpSimulcastParameters\")}constructor(e){Object.assign(this,e)}};var Wo=require(\"node:crypto\");var ts=1;var ct=7;var qc=a(r=>{switch(r){case ts:case ct:return 16}},\"keyLength\");var Fc=a(r=>{switch(r){case ts:return 14;case ct:return 12}},\"saltLength\");function Kc(r){if(!Number.isInteger(r)||r<0||!Number.isSafeInteger(r)){throw new Error(\"LEB128 encode requires a non-negative safe integer\")}const e=[];let t=r;do{let s=t&127;t=Math.floor(t/128);if(t!==0){s|=128}e.push(s)}while(t!==0);return Buffer.from(e)}a(Kc,\"leb128encode\");var Hl=b(\"webrtc/rtp/codec/av1\");var Ho=class r{static{a(this,\"AV1RtpPayload\")}constructor(){this.obu_or_fragment=[]}static{this.deSerialize=e=>{const t=new r;let s=0;t.zBit_RtpStartsWithFragment=k(e[s],0);t.yBit_RtpEndsWithFragment=k(e[s],1);t.w_RtpNumObus=k(e[s],2,2);t.nBit_RtpStartsNewCodedVideoSequence=k(e[s],4);s++;if(t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment){throw new Error}[...Array(t.w_RtpNumObus-1).keys()].forEach(n=>{const[o,c]=zl(e.subarray(s));const d=s+c;const h=d+o;let l=false;if(t.zBit_RtpStartsWithFragment&&n===0){l=true}t.obu_or_fragment.push({data:e.subarray(d,h),isFragment:l});s+=c+o});let i=false;if(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment){i=true}t.obu_or_fragment.push({data:e.subarray(s),isFragment:i});return t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){const t=[];const s=e.flatMap(c=>c.obu_or_fragment).reduce((c,d,h)=>{c[h]=d;return c},{});const i=Object.keys(s).length;for(const c of Object.keys(s).map(Number)){const d=s[c];if(!d)continue;const{data:h,isFragment:l}=d;if(l){let u=[];for(let g=c;g<i;g++){const S=s[g];if(S.isFragment){u.push(S.data);delete s[g]}else{break}}if(u.length<=1){Hl(\"fragment lost, maybe packet lost\");u=[]}t.push(Buffer.concat(u))}else{t.push(h)}}const n=t.map(c=>zo.deSerialize(c));const o=n.pop();return Buffer.concat([...n.map(c=>{c.obu_has_size_field=1;return c.serialize()}),o.serialize()])}};var zo=class r{static{a(this,\"AV1Obu\")}static deSerialize(e){const t=new r;let s=0;t.obu_forbidden_bit=k(e[s],0);t.obu_type=Gc[k(e[s],1,4)];t.obu_extension_flag=k(e[s],5);t.obu_has_size_field=k(e[s],6);t.obu_reserved_1bit=k(e[s],7);s++;t.payload=e.subarray(s);return t}serialize(){const e=new gt(8).set(this.obu_forbidden_bit).set(ql[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;let t=Buffer.alloc(0);if(this.obu_has_size_field){t=Kc(this.payload.length)}return Buffer.concat([e,t,this.payload])}};function zl(r){let e=0;let t=0;for(let s=0;s<8;s++){if(s>=r.length){throw new Error(\"LEB128 decode incomplete\")}const i=r.readUInt8(s);e+=(i&127)*128**s;t++;if(!(i&128)){if(!Number.isSafeInteger(e)){throw new Error(\"LEB128 value exceeds safe integer\")}return[e,t]}}throw new Error(\"LEB128 decode incomplete\")}a(zl,\"leb128decode\");var Gc={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\"};var ql=Object.entries(Gc).reduce((r,[e,t])=>{r[t]=Number(e);return r},{});var tS=Buffer.from([0,0,0,1]);function qo(r,e){const t=Buffer.alloc(e);r.copy(t);return t}a(qo,\"growBufferSize\");function ss(r){return Number.parseInt(r.toString(),10)}a(ss,\"Int\");function jc(r){const e=r[0];return e>127&&e<192}a(jc,\"isMedia\");var mr=4;var V=class r{static{a(this,\"RtcpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.count=0;this.type=0;this.length=0;Object.assign(this,e)}static serialize(e,t,s,i){const n=new r({type:e,count:t,version:2,length:i});const o=n.serialize();return Buffer.concat([o,s])}serialize(){const e=new ze(8);e.set(2,0,this.version);if(this.padding)e.set(1,2,1);e.set(5,3,this.count);const t=N([1,1,2],[e.value,this.type,this.length]);return t}static deSerialize(e){const[t,s,i]=F(e,[1,1,2]);const n=k(t,0,2);const o=k(t,2,1)>0;const c=k(t,3,5);return new r({version:n,padding:o,count:c,type:s,length:i})}};var gr=class r{static{a(this,\"FullIntraRequest\")}static{this.count=4}constructor(e={}){this.count=r.count;this.fir=[];Object.assign(this,e)}get length(){return this.serialize().length/4}static deSerialize(e){const[t,s]=F(e,[4,4]);const i=[];for(let n=8;n<e.length;n+=8){i.push({ssrc:e.readUInt32BE(n),sequenceNumber:e[n+4]})}return new r({senderSsrc:t,mediaSsrc:s,fir:i})}serialize(){const e=N([4,4],[this.senderSsrc,this.mediaSsrc]);const t=Buffer.alloc(this.fir.length*8);this.fir.forEach(({ssrc:s,sequenceNumber:i},n)=>{t.writeUInt32BE(s,n*8);t[n*8+4]=i});return Buffer.concat([e,t])}};var Fe=class r{static{a(this,\"PictureLossIndication\")}static{this.count=1}constructor(e={}){this.count=r.count;this.length=2;Object.assign(this,e)}static deSerialize(e){const[t,s]=F(e,[4,4]);return new r({senderSsrc:t,mediaSsrc:s})}serialize(){return N([4,4],[this.senderSsrc,this.mediaSsrc])}};var Ke=class r{static{a(this,\"ReceiverEstimatedMaxBitrate\")}static{this.count=15}constructor(e={}){this.count=r.count;this.uniqueID=\"REMB\";this.ssrcNum=0;this.ssrcFeedbacks=[];Object.assign(this,e)}static deSerialize(e){const[t,s,i,n,o]=F(e,[4,4,4,1,1]);const c=k(o,0,6);const d=(k(o,6,2)<<16)+(e[14]<<8)+e[15];const h=c>46?18446744073709551615n:BigInt(d)<<BigInt(c);const l=[];for(let u=16;u<e.length;u+=4){const g=e.slice(u).readUIntBE(0,4);l.push(g)}return new r({senderSsrc:t,mediaSsrc:s,uniqueID:N([4],[i]).toString(),ssrcNum:n,brExp:c,brMantissa:d,ssrcFeedbacks:l,bitrate:h})}serialize(){const e=Buffer.concat([N([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),N([1],[this.ssrcNum])]);const t=new ze(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);const s=Buffer.concat(this.ssrcFeedbacks.map(n=>N([4],[n])));const i=Buffer.concat([e,N([3],[t.value]),s]);this.length=i.length/4;return i}};var Kl=b(\"webrtc/rtp/rtcp/psfb/index\");var we=class r{static{a(this,\"RtcpPayloadSpecificFeedback\")}static{this.type=206}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return V.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case gr.count:s=gr.deSerialize(e);break;case Fe.count:s=Fe.deSerialize(e);break;case Ke.count:s=Ke.deSerialize(e);break;default:Kl(\"unknown psfb packet\",t.count);break}return new r({feedback:s})}};var be=class r{static{a(this,\"RtcpRrPacket\")}static{this.type=201}constructor(e={}){this.ssrc=0;this.reports=[];this.type=r.type;Object.assign(this,e)}serialize(){let e=N([4],[this.ssrc]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return V.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const[s]=F(e,[4]);let i=4;const n=[];for(let o=0;o<t;o++){n.push(wt.deSerialize(e.slice(i,i+24)));i+=24}return new r({ssrc:s,reports:n})}};var wt=class r{static{a(this,\"RtcpReceiverInfo\")}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 N([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){const[t,s,i,n,o,c,d]=F(e,[4,1,3,4,4,4,4]);return new r({ssrc:t,fractionLost:s,packetsLost:i,highestSequence:n,jitter:o,lsr:c,dlsr:d})}};var Mi=205;var Ge=class r{static{a(this,\"GenericNack\")}static{this.count=1}toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){this.count=r.count;this.lost=[];Object.assign(this,e);if(!this.header){this.header=new V({type:Mi,count:this.count,version:2})}}static deSerialize(e,t){const[s,i]=F(e,[4,4]);const n=[];for(let o=8;o<e.length;o+=4){const[c,d]=F(e.subarray(o),[2,2]);n.push(c);for(let h=0;h<16;h++){if(d>>h&1){n.push(c+h+1)}}}return new r({header:t,senderSsrc:s,mediaSourceSsrc:i,lost:n})}serialize(){const e=N([4,4],[this.senderSsrc,this.mediaSourceSsrc]);const t=[];if(this.lost.length>0){let i=this.lost[0],n=0;this.lost.slice(1).forEach(o=>{const c=o-i-1;if(c>=0&&c<16){n|=1<<c}else{t.push(N([2,2],[i,n]));i=o;n=0}});t.push(N([2,2],[i,n]))}const s=Buffer.concat([e,Buffer.concat(t)]);this.header.length=s.length/4;return Buffer.concat([this.header.serialize(),s])}};var Gl=b(\"webrtc/rtp/rtcp/rtpfb/twcc\");var je=class r{static{a(this,\"TransportWideCC\")}static{this.count=15}constructor(e={}){this.count=r.count;this.length=2;this.packetChunks=[];this.recvDeltas=[];Object.assign(this,e);if(!this.header){this.header=new V({type:205,count:this.count,version:2})}}static deSerialize(e,t){const[s,i,n,o,c,d]=F(e,[4,4,2,2,3,1]);const h=[];const l=[];let u=16;for(let S=0;S<o;){const p=k(e.slice(u,u+1)[0],0,1);let f;switch(p){case dt.TypeTCCRunLengthChunk:{const y=rs.deSerialize(e.slice(u,u+2));f=y;const m=Math.min(o-S,y.runLength);if(y.packetStatus===z.TypeTCCPacketReceivedSmallDelta||y.packetStatus===z.TypeTCCPacketReceivedLargeDelta){for(let T=0;T<m;T++){l.push(new bt({type:y.packetStatus}))}}S+=m}break;case dt.TypeTCCStatusVectorChunk:{const y=Sr.deSerialize(e.slice(u,u+2));f=y;if(y.symbolSize===0){y.symbolList.forEach(m=>{if(m===z.TypeTCCPacketReceivedSmallDelta){l.push(new bt({type:z.TypeTCCPacketReceivedSmallDelta}))}})}if(y.symbolSize===1){y.symbolList.forEach(m=>{if(m===z.TypeTCCPacketReceivedSmallDelta||m===z.TypeTCCPacketReceivedLargeDelta){l.push(new bt({type:m}))}})}S+=y.symbolList.length}break}if(!f)throw new Error;u+=2;h.push(f)}let g=u;l.forEach(S=>{if(S.type===z.TypeTCCPacketReceivedSmallDelta){S.deSerialize(e.slice(g,g+1));g++}if(S.type===z.TypeTCCPacketReceivedLargeDelta){S.deSerialize(e.slice(g,g+2));g+=2}});return new r({senderSsrc:s,mediaSourceSsrc:i,baseSequenceNumber:n,packetStatusCount:o,referenceTime:c,fbPktCount:d,recvDeltas:l,packetChunks:h,header:t})}serialize(){const e=N([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]);const t=Buffer.concat(this.packetChunks.map(o=>o.serialize()));const s=Buffer.concat(this.recvDeltas.map(o=>{try{return o.serialize()}catch(c){Gl(c?.message);return void 0}}).filter(o=>o));const i=Buffer.concat([e,t,s]);const n=i.length%4;this.header.padding=n!==0;if(n!==0){const o=Buffer.alloc(4-n);o[o.length-1]=o.length;this.header.length=(i.length+o.length)/4;return Buffer.concat([this.header.serialize(),i,o])}this.header.length=i.length/4;return Buffer.concat([this.header.serialize(),i])}get packetResults(){const e=[];for(const n of this.packetChunks){if(n instanceof rs){for(let o=0;o<n.runLength;o++)e.push(n.packetStatus)}else{e.push(...n.symbolList)}}if(e.length>this.packetStatusCount)e.length=this.packetStatusCount;const t=[];let s=this.referenceTime*64e3;let i=0;e.forEach((n,o)=>{const c=new Fo({sequenceNumber:this.baseSequenceNumber+o&65535});if(n===z.TypeTCCPacketReceivedSmallDelta||n===z.TypeTCCPacketReceivedLargeDelta){const d=this.recvDeltas[i++];if(d){s+=d.delta;c.received=true;c.delta=d.delta;c.receivedAtMs=s/1e3}}t.push(c)});return t}};var rs=class r{static{a(this,\"RunLengthChunk\")}constructor(e={}){Object.assign(this,e);this.type=dt.TypeTCCRunLengthChunk}static deSerialize(e){const t=k(e[0],1,2);const s=(k(e[0],3,5)<<8)+e[1];return new r({type:0,packetStatus:t,runLength:s})}serialize(){const e=new gt(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer;return e}};var Sr=class r{static{a(this,\"StatusVectorChunk\")}constructor(e={}){this.symbolList=[];Object.assign(this,e)}static deSerialize(e){const t=dt.TypeTCCStatusVectorChunk;let s=k(e[0],1,1);const i=[];function n(o,c){for(let d=0;d<o;d++){c(d)}}a(n,\"range\");switch(s){case 0:n(6,o=>i.push(k(e[0],2+o,1)));n(8,o=>i.push(k(e[1],o,1)));break;case 1:n(3,o=>i.push(k(e[0],2+o*2,2)));n(4,o=>i.push(k(e[1],o*2,2)));break;default:s=(k(e[0],2,6)<<8)+e[1]}return new r({type:t,symbolSize:s,symbolList:i})}serialize(){const e=Buffer.alloc(2);const t=new gt(16).set(1).set(this.symbolSize);const s=this.symbolSize===0?1:2;this.symbolList.forEach(i=>{t.set(i,s)});e.writeUInt16BE(t.value);return e}};var bt=class r{static{a(this,\"RecvDelta\")}constructor(e={}){this.parsed=false;Object.assign(this,e)}static deSerialize(e){let t;let s;if(e.length===1){t=z.TypeTCCPacketReceivedSmallDelta;s=250*e[0]}else if(e.length===2){t=z.TypeTCCPacketReceivedLargeDelta;s=250*e.readInt16BE()}if(t===void 0||s===void 0)throw new Error;return new r({type:t,delta:s})}deSerialize(e){const t=r.deSerialize(e);this.delta=t.delta}parseDelta(){this.delta=Math.floor(this.delta/250);if(this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=z.TypeTCCPacketReceivedLargeDelta}else{if(!this.type)this.type=z.TypeTCCPacketReceivedSmallDelta}this.parsed=true}serialize(){if(!this.parsed)this.parseDelta();if(this.type===z.TypeTCCPacketReceivedSmallDelta){const e=Buffer.alloc(1);e.writeUInt8(this.delta);return e}else if(this.type===z.TypeTCCPacketReceivedLargeDelta){const e=Buffer.alloc(2);e.writeInt16BE(this.delta);return e}throw new Error(\"errDeltaExceedLimit \"+this.delta+\" \"+this.type)}};var dt;(function(r){r[r[\"TypeTCCRunLengthChunk\"]=0]=\"TypeTCCRunLengthChunk\";r[r[\"TypeTCCStatusVectorChunk\"]=1]=\"TypeTCCStatusVectorChunk\";r[r[\"packetStatusChunkLength\"]=2]=\"packetStatusChunkLength\"})(dt||(dt={}));var z;(function(r){r[r[\"TypeTCCPacketNotReceived\"]=0]=\"TypeTCCPacketNotReceived\";r[r[\"TypeTCCPacketReceivedSmallDelta\"]=1]=\"TypeTCCPacketReceivedSmallDelta\";r[r[\"TypeTCCPacketReceivedLargeDelta\"]=2]=\"TypeTCCPacketReceivedLargeDelta\";r[r[\"TypeTCCPacketReceivedWithoutDelta\"]=3]=\"TypeTCCPacketReceivedWithoutDelta\"})(z||(z={}));var Fo=class{static{a(this,\"PacketResult\")}constructor(e){this.sequenceNumber=0;this.delta=0;this.received=false;this.receivedAtMs=0;Object.assign(this,e)}};var jl=b(\"webrtc/rtp/rtcp/rtpfb/index\");var Z=class r{static{a(this,\"RtcpTransportLayerFeedback\")}static{this.type=Mi}constructor(e={}){this.type=r.type;Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return e}static deSerialize(e,t){let s;switch(t.count){case Ge.count:s=Ge.deSerialize(e,t);break;case je.count:s=je.deSerialize(e,t);break;default:jl(\"unknown rtpfb packet\",t.count);break}return new r({feedback:s,header:t})}};var We=class r{static{a(this,\"RtcpSourceDescriptionPacket\")}static{this.type=202}constructor(e){this.type=r.type;this.chunks=[];Object.assign(this,e)}get length(){let e=0;this.chunks.forEach(t=>e+=t.length);return e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));while(e.length%4)e=Buffer.concat([e,Buffer.from([0])]);return V.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){const s=[];for(let i=0;i<e.length;){const n=yr.deSerialize(e.slice(i));s.push(n);i+=n.length}return new r({chunks:s})}};var yr=class r{static{a(this,\"SourceDescriptionChunk\")}constructor(e={}){this.items=[];Object.assign(this,e)}get length(){let e=4;this.items.forEach(t=>e+=t.length);e+=1;e+=Wc(e);return e}serialize(){const e=Buffer.concat([N([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);const t=Buffer.concat([e,Buffer.alloc(Wc(e.length))]);return t}static deSerialize(e){const t=e.readUInt32BE();const s=[];for(let i=4;i<e.length;){const n=e[i];if(n===0)break;const o=Tr.deSerialize(e.slice(i));s.push(o);i+=o.length}return new r({source:t,items:s})}};var Tr=class r{static{a(this,\"SourceDescriptionItem\")}constructor(e){Object.assign(this,e)}get length(){return 1+1+Buffer.from(this.text).length}serialize(){const e=Buffer.from(this.text);return Buffer.concat([N([1,1],[this.type,e.length]),e])}static deSerialize(e){const t=e[0];const s=e[1];const i=e.slice(2,2+s).toString();return new r({type:t,text:i})}};function Wc(r){if(r%4==0){return 0}return 4-r%4}a(Wc,\"getPadding\");var ue=class r{static{a(this,\"RtcpSrPacket\")}static{this.type=200}constructor(e){this.ssrc=0;this.reports=[];this.type=r.type;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);e.writeUInt32BE(this.ssrc);e=Buffer.concat([e,this.senderInfo.serialize()]);e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]);return V.serialize(r.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const s=e.readUInt32BE();const i=wr.deSerialize(e.subarray(4,24));let n=24;const o=[];for(let d=0;d<t;d++){o.push(wt.deSerialize(e.subarray(n,n+24)));n+=24}const c=new r({ssrc:s,senderInfo:i,reports:o});return c}};var wr=class r{static{a(this,\"RtcpSenderInfo\")}constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:Wl(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return N([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){const[t,s,i,n]=F(e,[8,4,4,4]);return new r({ntpTimestamp:t,rtpTimestamp:s,packetCount:i,octetCount:n})}};var Wl=a(r=>{const[e,t]=F(N([8],[r]),[4,4]);return Number(`${e}.${t}`)},\"ntpTime2Sec\");var $l=b(\"webrtc/rtp/rtcp/rtcp\");var Oi=class{static{a(this,\"RtcpPacketConverter\")}static deSerialize(e){let t=0;const s=[];while(t<e.length){const i=V.deSerialize(e.subarray(t,t+mr));t+=mr;let n=e.subarray(t,t+i.length*4);t+=i.length*4;if(i.padding){n=n.subarray(0,n.length-n.subarray(-1)[0])}try{switch(i.type){case ue.type:s.push(ue.deSerialize(n,i.count));break;case be.type:s.push(be.deSerialize(n,i.count));break;case We.type:s.push(We.deSerialize(n,i));break;case Z.type:s.push(Z.deSerialize(n,i));break;case we.type:s.push(we.deSerialize(n,i));break;default:break}}catch(o){$l(\"deSerialize RTCP\",o)}}return s}};function $c(r){return r.length>=2&&r[1]>=192&&r[1]<=208}a($c,\"isRtcp\");var M={sdesMid:\"urn:ietf:params:rtp-hdrext:sdes:mid\",sdesRTPStreamID:\"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\",repairedRtpStreamId:\"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\",transportWideCC:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\",absSendTime:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\",dependencyDescriptor:\"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension\",audioLevelIndication:\"urn:ietf:params:rtp-hdrext:ssrc-audio-level\",videoOrientation:\"urn:3gpp:video-orientation\"};function Vc(r,e){return r.map(t=>{const s=e[t.id];if(!s){return{uri:\"unknown\",value:t.payload}}switch(s){case M.sdesMid:case M.sdesRTPStreamID:case M.repairedRtpStreamId:return{uri:s,value:Vl(t.payload)};case M.transportWideCC:return{uri:s,value:Yl(t.payload)};case M.absSendTime:return{uri:s,value:Ql(t.payload)};case M.audioLevelIndication:{return{uri:s,value:Xl(t.payload)}}case M.videoOrientation:return{uri:s,value:Jl(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>{if(s)t[s.uri]=s.value;return t},{})}a(Vc,\"rtpHeaderExtensionsParser\");function Yc(r){return Buffer.from(r)}a(Yc,\"serializeSdesMid\");function Qc(r){return Buffer.from(r)}a(Qc,\"serializeSdesRTPStreamID\");function Xc(r){return Buffer.from(r)}a(Xc,\"serializeRepairedRtpStreamId\");function Ko(r){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(r);return e}a(Ko,\"serializeTransportWideCC\");function Vl(r){return r.toString()}a(Vl,\"deserializeString\");function Yl(r){return r.readUInt16BE()}a(Yl,\"deserializeUint16BE\");function Ql(r){return F(r,[3])[0]}a(Ql,\"deserializeAbsSendTime\");function Xl(r){const e=new Pe(r);const t={v:e.readBits(1)===1,level:e.readBits(7)};return t}a(Xl,\"deserializeAudioLevelIndication\");function Jl(r){const e=new Pe(r);e.readBits(4);const t={c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)};return t}a(Jl,\"deserializeVideoOrientation\");var Zl=b(\"packages/rtp/src/rtp/red/packet.ts\");var is=class r{static{a(this,\"Red\")}constructor(){this.blocks=[]}static deSerialize(e){const t=e instanceof ArrayBuffer?Buffer.from(e):e;const s=new r;let i=0;[s.header,i]=Ui.deSerialize(t);s.header.fields.forEach(({blockLength:n,timestampOffset:o,blockPT:c})=>{if(n&&o){const d=t.subarray(i,i+n);s.blocks.push({block:d,blockPT:c,timestampOffset:o});i+=n}else{const d=t.subarray(i);s.blocks.push({block:d,blockPT:c})}});return s}serialize(){this.header=new Ui;for(const{timestampOffset:t,blockPT:s,block:i}of this.blocks){if(t){this.header.fields.push({fBit:1,blockPT:s,blockLength:i.length,timestampOffset:t})}else{this.header.fields.push({fBit:0,blockPT:s})}}let e=this.header.serialize();for(const{block:t}of this.blocks){e=Buffer.concat([e,t])}return e}};var Ui=class r{static{a(this,\"RedHeader\")}constructor(){this.fields=[]}static deSerialize(e){let t=0;const s=new r;for(;;){const i={};s.fields.push(i);const n=new Pe(e.subarray(t));i.fBit=n.readBits(1);i.blockPT=n.readBits(7);t++;if(i.fBit===0){break}i.timestampOffset=n.readBits(14);i.blockLength=n.readBits(10);t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(const t of this.fields){try{if(t.timestampOffset&&t.blockLength){const s=new Pe(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,s.uint8Array])}else{const s=new Pe(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){Zl(s?.message)}}return e}};var Hi=class{static{a(this,\"RedEncoder\")}constructor(e=1){this.distance=e;this.cache=[];this.cacheSize=10}push(e){this.cache.push(e);if(this.cache.length>this.cacheSize){this.cache.shift()}}build(){const e=new is;const t=this.cache.slice(-(this.distance+1));const s=t.pop();if(!s){return e}t.forEach(i=>{const n=Ae(s.timestamp,-i.timestamp);if(n>ef){return}e.blocks.push({block:i.block,blockPT:i.blockPT,timestampOffset:n})});e.blocks.push({block:s.block,blockPT:s.blockPT});return e}};var ef=(1<<14)-1;var zi=class{static{a(this,\"RedHandler\")}constructor(){this.size=150;this.sequenceNumbers=[]}push(e,t){const s=[];e.blocks.forEach(({blockPT:n,timestampOffset:o,block:c},d)=>{const h=j(t.header.sequenceNumber,-(e.blocks.length-(d+1)));if(o){s.push(new W(new ee({timestamp:Ae(t.header.timestamp,-o),payloadType:n,ssrc:t.header.ssrc,sequenceNumber:h,marker:true}),c))}else{s.push(new W(new ee({timestamp:t.header.timestamp,payloadType:n,ssrc:t.header.ssrc,sequenceNumber:h,marker:true}),c))}});const i=s.filter(n=>{if(this.sequenceNumbers.includes(n.header.sequenceNumber)){return false}else{if(this.sequenceNumbers.length>this.size){this.sequenceNumbers.shift()}this.sequenceNumbers.push(n.header.sequenceNumber);return true}});return i}};var Ct={OneByte:48862,TwoByte:4096};var Jc=2;var Zc=4;var ed=8;var td=12;var sd=4;var ee=class r{static{a(this,\"RtpHeader\")}constructor(e={}){this.version=2;this.padding=false;this.paddingSize=0;this.extension=false;this.marker=false;this.payloadOffset=0;this.payloadType=0;this.sequenceNumber=0;this.timestamp=0;this.ssrc=0;this.csrcLength=0;this.csrc=[];this.extensionProfile=Ct.OneByte;this.extensions=[];Object.assign(this,e)}static deSerialize(e){const t=new r;let s=0;const i=e[s++];t.version=k(i,0,2);t.padding=k(i,2)>0;t.extension=k(i,3)>0;t.csrcLength=k(i,4,4);t.csrc=[...Array(t.csrcLength)].map(()=>{const o=e.readUInt32BE(s);s+=4;return o});s+=td-1;const n=e[1];t.marker=k(n,0)>0;t.payloadType=k(n,1,7);t.sequenceNumber=e.readUInt16BE(Jc);t.timestamp=e.readUInt32BE(Zc);t.ssrc=e.readUInt32BE(ed);for(let o=0;o<t.csrc.length;o++){const c=td+o*sd;t.csrc[o]=e.subarray(c).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE();s+=2;const o=e.subarray(s).readUInt16BE()*4;t.extensionLength=o;s+=2;switch(t.extensionProfile){case Ct.OneByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const d=e[s]>>4;const h=(e[s]&(e[s]^240))+1;s++;if(d===15){break}const l={id:d,payload:e.subarray(s,s+h)};t.extensions=[...t.extensions,l];s+=h}}break;case Ct.TwoByte:{const c=s+o;while(s<c){if(e[s]===0){s++;continue}const d=e[s];s++;const h=e[s];s++;const l={id:d,payload:e.subarray(s,s+h)};t.extensions=[...t.extensions,l];s+=h}}break;default:{const c={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,c];s+=t.extensions[0].payload.length}break}}t.payloadOffset=s;if(t.padding){t.paddingSize=e[e.length-1]}return t}get serializeSize(){const{csrc:e,extensionProfile:t,extensions:s}=this;let i=12+e.length*sd;if(s.length>0||this.extension===true){let n=4;switch(t){case Ct.OneByte:for(const o of s){n+=1+o.payload.length}break;case Ct.TwoByte:for(const o of s){n+=2+o.payload.length}break;default:n+=s[0].payload.length}i+=Math.floor((n+3)/4)*4}return i}serialize(e){const t=Buffer.alloc(e);let s=0;const i=new ze(8);i.set(2,0,this.version);if(this.padding)i.set(1,2,1);if(this.extensions.length>0)this.extension=true;if(this.extension)i.set(1,3,1);i.set(4,4,this.csrc.length);t.writeUInt8(i.value,s++);const n=new ze(8);if(this.marker)n.set(1,0,1);n.set(7,1,this.payloadType);t.writeUInt8(n.value,s++);t.writeUInt16BE(this.sequenceNumber,Jc);s+=2;t.writeUInt32BE(this.timestamp,Zc);s+=4;t.writeUInt32BE(this.ssrc,ed);s+=4;for(const o of this.csrc){t.writeUInt32BE(o,s);s+=4}if(this.extension){const o=s;t.writeUInt16BE(this.extensionProfile,s);s+=4;const c=s;switch(this.extensionProfile){case Ct.OneByte:for(const l of this.extensions){t.writeUInt8(l.id<<4|l.payload.length-1,s++);l.payload.copy(t,s);s+=l.payload.length}break;case Ct.TwoByte:for(const l of this.extensions){t.writeUInt8(l.id,s++);t.writeUInt8(l.payload.length,s++);l.payload.copy(t,s);s+=l.payload.length}break;default:{const l=this.extensions[0].payload.length;if(l%4!=0){throw new Error}this.extensions[0].payload.copy(t,s);s+=l}}const d=s-c;const h=Math.trunc((d+3)/4)*4;t.writeUInt16BE(Math.trunc(h/4),o+2);for(let l=0;l<h-d;l++){t.writeUInt8(0,s);s++}}this.payloadOffset=s;return t}};var W=class r{static{a(this,\"RtpPacket\")}constructor(e,t){this.header=e;this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new r(new ee({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length);const{payloadOffset:t}=this.header;this.payload.copy(e,t);if(this.header.padding){const 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){const t=ee.deSerialize(e);const s=new r(t,e.subarray(t.payloadOffset,e.length-t.paddingSize));return s}clear(){this.payload=null}};function rd(r,e,t){const s=new W(new ee({payloadType:e,marker:r.header.marker,sequenceNumber:r.payload.readUInt16BE(0),timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2));return s}a(rd,\"unwrapRtx\");function id(r,e,t,s){const i=Buffer.allocUnsafe(2);i.writeUInt16BE(r.header.sequenceNumber,0);const n=new W(new ee({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([i,r.payload]));return n}a(id,\"wrapRtx\");var cs=require(\"node:crypto\");var Ce=require(\"node:crypto\");var ns=class{static{a(this,\"CipherAesBase\")}constructor(e,t,s,i){this.srtpSessionKey=e;this.srtpSessionSalt=t;this.srtcpSessionKey=s;this.srtcpSessionSalt=i}encryptRtp(e,t,s){return Buffer.from([])}decryptRtp(e,t,s){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}};var le=class extends Error{static{a(this,\"SrtpAuthenticationError\")}constructor(e){super(e);this.name=\"SrtpAuthenticationError\"}};var nd=12;var tf=8;function os(r,e,t=\"Failed to authenticate SRTP packet\"){const s=r.length-e;br(r.length>=nd+e,t);const i=od(()=>ee.deSerialize(r.subarray(0,s)),t);i.paddingSize=0;br(i.payloadOffset>=nd&&i.payloadOffset<=s,t);return i}a(os,\"parseSrtpRtpHeader\");function qi(r,e,t,s=\"Failed to authenticate SRTCP packet\"){br(r.length>=tf+e+t,s);return od(()=>V.deSerialize(r.subarray(0,mr)),s)}a(qi,\"parseSrtcpHeader\");function br(r,e){if(!r){throw new le(e)}}a(br,\"assertAuthenticatedPacketLength\");function od(r,e){try{return r()}catch{throw new le(e)}}a(od,\"wrapAuthenticationError\");function Fi(r,e,t=\"Failed to authenticate SRTP packet\"){if(!r.padding){r.paddingSize=0;return r}br(e.length>r.payloadOffset,t);const s=e[e.length-1];br(s>0&&s<=e.length-r.payloadOffset,t);r.paddingSize=s;return r}a(Fi,\"finalizeSrtpRtpHeader\");var Ki=class extends ns{static{a(this,\"CipherAesCtr\")}constructor(e,t,s,i,n,o){super(e,t,s,i);this.srtpSessionAuthTag=n;this.srtcpSessionAuthTag=o;this.authTagLength=10}encryptRtp(e,t,s){const i=e.serialize(e.serializeSize);const n=this.generateCounter(e.sequenceNumber,s,e.ssrc,this.srtpSessionSalt);const o=(0,Ce.createCipheriv)(\"aes-128-ctr\",this.srtpSessionKey,n);const c=o.update(t);const d=this.generateSrtpAuthTag(s,i,c);return Buffer.concat([i,c,d])}decryptRtp(e,t,s=os(e,this.authTagLength)){const i=e.length-this.authTagLength;const n=e.subarray(0,i);const o=e.subarray(i);const c=this.generateSrtpAuthTag(t,n.subarray(0,s.payloadOffset),n.subarray(s.payloadOffset));cd(o,c,\"Failed to authenticate SRTP packet\");const d=this.generateCounter(s.sequenceNumber,t,s.ssrc,this.srtpSessionSalt);const h=(0,Ce.createDecipheriv)(\"aes-128-ctr\",this.srtpSessionKey,d);const l=n.subarray(s.payloadOffset);const u=h.update(l);const g=Buffer.concat([n.subarray(0,s.payloadOffset),u]);return[g,Fi(s,g,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){let s=Buffer.from(e);const i=s.readUInt32BE(4);const n=this.generateCounter(t&65535,t>>16,i,this.srtcpSessionSalt);const o=(0,Ce.createCipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,n);const c=o.update(s.slice(8));c.copy(s,8);s=Buffer.concat([s,Buffer.alloc(4)]);s.writeUInt32BE(t,s.length-4);s[s.length-4]|=128;const d=this.generateSrtcpAuthTag(s);s=Buffer.concat([s,d]);return s}decryptRTCP(e){const t=qi(e,this.authTagLength,ad);const s=e.length-(this.authTagLength+ad);const i=e.subarray(0,e.length-this.authTagLength);const n=e.subarray(e.length-this.authTagLength);const o=this.generateSrtcpAuthTag(i);cd(n,o,\"Failed to authenticate SRTCP packet\");const c=Buffer.from(e).slice(0,s);const d=e[s]>>>7;if(d===0)return[c,t];let h=e.readUInt32BE(s);h&=~(1<<31);const l=e.readUInt32BE(4);const u=this.generateCounter(h&65535,h>>16,l,this.srtcpSessionSalt);const g=(0,Ce.createDecipheriv)(\"aes-128-ctr\",this.srtcpSessionKey,u);const S=g.update(c.subarray(8));S.copy(c,8);return[c,t]}generateSrtcpAuthTag(e){const t=(0,Ce.createHmac)(\"sha1\",this.srtcpSessionAuthTag);return t.update(e).digest().slice(0,10)}generateCounter(e,t,s,i){const n=Buffer.alloc(16);n.writeUInt32BE(s,4);n.writeUInt32BE(t,8);n.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let o=0;o<i.length;o++){n[o]^=i[o]}return n}generateSrtpAuthTag(e,...t){const s=(0,Ce.createHmac)(\"sha1\",this.srtpSessionAuthTag);const i=Buffer.alloc(4);i.writeUInt32BE(e);for(const n of t){s.update(n)}return s.update(i).digest().subarray(0,10)}};var ad=4;function cd(r,e,t){if(r.length!==e.length||!(0,Ce.timingSafeEqual)(r,e)){throw new le(t)}}a(cd,\"assertAuthTag\");var as=require(\"node:crypto\");var Gi=class extends ns{static{a(this,\"CipherAesGcm\")}constructor(e,t,s,i){super(e,t,s,i);this.aeadAuthTagLen=16;this.rtpIvWriter=or([2,4,4,2],true);this.rtcpIvWriter=or([2,4,2,4],true);this.aadWriter=or([4],true)}encryptRtp(e,t,s){const i=e.serialize(e.serializeSize);const n=this.rtpInitializationVector(e,s);const o=(0,as.createCipheriv)(\"aes-128-gcm\",this.srtpSessionKey,n);o.setAAD(i);const c=o.update(t);o.final();const d=o.getAuthTag();const h=Buffer.concat([i,c,d]);return h}decryptRtp(e,t,s=os(e,this.aeadAuthTagLen)){const i=e.subarray(0,s.payloadOffset);const n=e.length-this.aeadAuthTagLen;const o=e.subarray(n);let c=Buffer.from([]);c=qo(c,e.length-this.aeadAuthTagLen);i.copy(c);const d=this.rtpInitializationVector(s,t);const h=e.slice(s.payloadOffset,n);const l=(0,as.createDecipheriv)(\"aes-128-gcm\",this.srtpSessionKey,d);l.setAAD(i);l.setAuthTag(o);const u=l.update(h);hd(l,\"SRTP\");u.copy(c,s.payloadOffset);return[c,Fi(s,c,\"Failed to authenticate SRTP packet\")]}encryptRTCP(e,t){const s=e.readUInt32BE(4);const i=e.length+this.aeadAuthTagLen;let n=Buffer.from([]);n=qo(n,i+Go);e.slice(0,8).copy(n);const o=this.rtcpInitializationVector(s,t);const c=this.rtcpAdditionalAuthenticatedData(e,t);const d=(0,as.createCipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,o);d.setAAD(c);const h=d.update(e.slice(8));d.final();h.copy(n,8);const l=d.getAuthTag();l.copy(n,8+h.length);c.slice(8,12).copy(n,i);return n}decryptRTCP(e){const t=qi(e,this.aeadAuthTagLen,Go);const s=e.length-Go;const i=s-this.aeadAuthTagLen;const n=e.readUInt32BE(4);const o=e.readUInt32BE(s);const c=o>>>31===1;const d=o&~(dd<<24);const h=this.rtcpInitializationVector(n,d);const l=c?Buffer.concat([e.subarray(0,8),e.subarray(s)]):Buffer.concat([e.subarray(0,i),e.subarray(s)]);const u=c?e.slice(8,i):Buffer.alloc(0);const g=c?Buffer.alloc(i):Buffer.from(e.subarray(0,i));if(c){e.slice(0,8).copy(g)}const S=(0,as.createDecipheriv)(\"aes-128-gcm\",this.srtcpSessionKey,h);S.setAAD(l);S.setAuthTag(e.subarray(i,s));const p=S.update(u);hd(S,\"SRTCP\");if(c){p.copy(g,8)}return[g,t]}rtpInitializationVector(e,t){const s=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let i=0;i<s.length;i++){s[i]^=this.srtpSessionSalt[i]}return s}rtcpInitializationVector(e,t){const s=this.rtcpIvWriter([0,e,0,t]);for(let i=0;i<s.length;i++){s[i]^=this.srtcpSessionSalt[i]}return s}rtcpAdditionalAuthenticatedData(e,t){const s=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);s[8]|=dd;return s}};var Go=4;var dd=128;function hd(r,e){try{r.final()}catch{throw new le(`Failed to authenticate ${e} packet`)}}a(hd,\"finalizeAuthenticatedDecryption\");function ji(r,e){const t=(0,cs.createCipheriv)(\"aes-128-ecb\",r,null);t.setAutoPadding(false);return Buffer.concat([t.update(e),t.final()])}a(ji,\"aes128EcbEncrypt\");var ds=class{static{a(this,\"Context\")}constructor(e,t,s){this.masterKey=e;this.masterSalt=t;this.profile=s;this.srtpSSRCStates={};this.srtcpSSRCStates={};{const i=14-t.length;if(i>0){this.masterSalt=Buffer.concat([t,Buffer.alloc(i)])}}this.srtpSessionKey=this.generateSessionKey(0);this.srtpSessionSalt=this.generateSessionSalt(2);this.srtpSessionAuthTag=this.generateSessionAuthTag(1);this.srtpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtpSessionAuthTag);this.srtcpSessionKey=this.generateSessionKey(3);this.srtcpSessionSalt=this.generateSessionSalt(5);this.srtcpSessionAuthTag=this.generateSessionAuthTag(4);this.srtcpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtcpSessionAuthTag);switch(s){case ts:this.cipher=new Ki(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case ct:this.cipher=new Gi(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}generateSessionKey(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let i=s.length-1,n=t.length-1;i>=0;i--,n--){t[n]=t[n]^s[i]}t=Buffer.concat([t,Buffer.from([0,0])]);return ji(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let i=s.length-1,n=t.length-1;i>=0;i--,n--){t[n]=t[n]^s[i]}t=Buffer.concat([t,Buffer.from([0,0])]);t=ji(this.masterKey,t);return t.subarray(0,14)}generateSessionAuthTag(e){const t=Buffer.from(this.masterSalt);const s=Buffer.from([e,0,0,0,0,0,0]);for(let o=s.length-1,c=t.length-1;o>=0;o--,c--){t[c]=t[c]^s[o]}let i=Buffer.concat([t,Buffer.from([0,0])]);let n=Buffer.concat([t,Buffer.from([0,1])]);i=ji(this.masterKey,i);n=ji(this.masterKey,n);return Buffer.concat([i,n.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];if(t)return t;t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0};this.srtpSSRCStates[e]=t;return t}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];if(t)return t;t={srtcpIndex:0,ssrc:e};this.srtcpSSRCStates[e]=t;return t}updateRolloverCount(e,t){if(!t.rolloverHasProcessed){t.rolloverHasProcessed=true}else if(e===0){if(t.lastSequenceNumber>Cr){t.rolloverCounter++}}else if(t.lastSequenceNumber<Cr&&e>ud-Cr){if(t.rolloverCounter>0){t.rolloverCounter--}}else if(e<Cr&&t.lastSequenceNumber>ud-Cr){t.rolloverCounter++}t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=(0,cs.createHmac)(\"sha1\",this.srtpSessionAuthTag);const s=Buffer.alloc(4);s.writeUInt32BE(t);return this.srtpSessionAuth.update(e).update(s).digest().slice(0,10)}index(e){const t=this.srtcpSSRCStates[e];if(!t){return 0}return t.srtcpIndex}setIndex(e,t){const s=this.getSrtcpSsrcState(e);s.srtcpIndex=t%2147483647}};var Cr=100;var ud=65535;var Wi=class extends ds{static{a(this,\"SrtcpContext\")}constructor(e,t,s){super(e,t,s)}encryptRTCP(e){const t=e.readUInt32BE(4);const s=this.getSrtcpSsrcState(t);s.srtcpIndex++;if(s.srtcpIndex>>sf){s.srtcpIndex=0}const i=this.cipher.encryptRTCP(e,s.srtcpIndex);return i}decryptRTCP(e){const t=this.cipher.decryptRTCP(e);return t}};var sf=2147483647;var hs=class{static{a(this,\"Session\")}constructor(e){this.ContextCls=e}start(e,t,s,i,n){this.localContext=new this.ContextCls(e,t,n);this.remoteContext=new this.ContextCls(s,i,n)}};var $i=class extends hs{static{a(this,\"SrtcpSession\")}constructor(e){super(Wi);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRTCP(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e){const t=this.localContext.encryptRTCP(e);return t}};var Vi=class extends ds{static{a(this,\"SrtpContext\")}constructor(e,t,s){super(e,t,s)}encryptRtp(e,t){const s=this.getSrtpSsrcState(t.ssrc);this.updateRolloverCount(t.sequenceNumber,s);const i=this.cipher.encryptRtp(t,e,s.rolloverCounter);return i}decryptRtp(e){const t=os(e,this.rtpAuthTagLength);const s=this.srtpSSRCStates[t.ssrc];const i=s?{...s}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,i);const n=this.cipher.decryptRtp(e,i.rolloverCounter,t);if(s){Object.assign(s,i)}else{this.srtpSSRCStates[t.ssrc]=i}return n}get rtpAuthTagLength(){return this.profile===ct?16:10}};var Yi=class extends hs{static{a(this,\"SrtpSession\")}constructor(e){super(Vi);this.config=e;this.decrypt=t=>{const[s]=this.remoteContext.decryptRtp(t);return s};this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}encrypt(e,t){return this.localContext.encryptRtp(e,t)}};var Qi=new WeakMap;var Xi=new WeakSet;function rf(r,e){Xi.add(r);if(e==void 0)Qi.delete(r);else Qi.set(r,e)}a(rf,\"setTrackSourceCodecs\");function Le(r){return r==void 0?void 0:Qi.get(r)}a(Le,\"getTrackSourceCodecs\");function Et(r){if(Xi.has(r))return;Xi.add(r);if(r.codec!=void 0){Qi.set(r,[r.codec])}}a(Et,\"captureTrackSourceCodecs\");var jo=class{static{a(this,\"TrackBroadcastSource\")}constructor(){this.tracks=new Set;this.upstreamStops=new Set}attach(e){this.tracks.add(e)}detach(e){this.tracks.delete(e);if(this.tracks.size>0){return}for(const t of[...this.upstreamStops]){t()}this.upstreamStops.clear()}addUpstreamStop(e){const t=a(()=>{this.upstreamStops.delete(t);e()},\"once\");this.upstreamStops.add(t)}deliverRtp(e,t){const s=[...this.tracks].filter(i=>!i.stopped);for(const i of s){i.applyIncomingRtp(e.clone(),t)}}deliverRtcp(e){for(const t of this.tracks){if(!t.stopped){t.onReceiveRtcp.execute(e)}}}deliverSourceChanged(e){for(const t of this.tracks){if(!t.stopped){t.onSourceChanged.execute(e)}}}stopAllTracks(){for(const e of[...this.tracks]){e.stop()}}};var Be=class r extends he{static{a(this,\"MediaStreamTrack\")}constructor(e){super();this.uuid=(0,Wo.randomUUID)().toString();this.remote=false;this.enabled=true;this.onReceiveRtp=new w;this.onReceiveRtcp=new w;this.onSourceChanged=new w;this.stopped=false;this.muted=true;this.stop=()=>{if(this.stopped){return}this.stopped=true;this.muted=true;this.onReceiveRtp.complete();this.emit(\"ended\");this.broadcastSource.detach(this)};this.writeRtp=s=>{if(this.remote){throw new Error(\"this is remoteTrack\")}const i=Buffer.isBuffer(s)?W.deSerialize(s):s.clone();i.header.payloadType=this.codec?.payloadType??i.header.payloadType;this.broadcastSource.deliverRtp(i)};this.writeRtcp=s=>{this.broadcastSource.deliverRtcp(s)};const t=e.broadcastSource;Object.assign(this,e);this.id??=this.uuid;this.broadcastSource=t??new jo;if(!this.stopped){this.broadcastSource.attach(this)}this.onReceiveRtp.subscribe(s=>{this.muted=false;this.header=s.header});this.label=`${this.remote?\"remote\":\"local\"} ${this.kind}`}get readyState(){return this.stopped?\"ended\":\"live\"}notifySourceChanged(e){this.broadcastSource.deliverSourceChanged(e)}applyIncomingRtp(e,t){if(this.stopped){return}this.onReceiveRtp.execute(e,t)}bindUpstreamStop(e){this.broadcastSource.addUpstreamStop(e)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){const e=new r({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(Xi.has(this)){rf(e,Le(this))}else{Et(e)}return e}};var us=class r{static{a(this,\"MediaStream\")}constructor(e={}){this.tracks=[];if(Array.isArray(e)){this.tracks=e}else{Object.assign(this,e)}this.id??=(0,Wo.randomUUID)().toString()}addTrack(e){e.streamId=this.id;this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e);if(e.streamId===this.id){e.streamId=void 0}}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===\"audio\")}getVideoTracks(){return this.tracks.filter(e=>e.kind===\"video\")}getTrackById(e){return this.tracks.find(t=>t.id===e)}get active(){return this.tracks.some(e=>!e.stopped)}clone(){const e=new r;for(const t of this.tracks){e.addTrack(t.clone())}return e}};var pc=require(\"node:crypto\");var $o;(function(r){r[r[\"DCEP\"]=50]=\"DCEP\";r[r[\"STRING\"]=51]=\"STRING\";r[r[\"BINARY\"]=53]=\"BINARY\";r[r[\"STRING_EMPTY\"]=56]=\"STRING_EMPTY\";r[r[\"BINARY_EMPTY\"]=57]=\"BINARY_EMPTY\"})($o||($o={}));var A;(function(r){r[r[\"CLOSED\"]=1]=\"CLOSED\";r[r[\"COOKIE_WAIT\"]=2]=\"COOKIE_WAIT\";r[r[\"COOKIE_ECHOED\"]=3]=\"COOKIE_ECHOED\";r[r[\"ESTABLISHED\"]=4]=\"ESTABLISHED\";r[r[\"SHUTDOWN_PENDING\"]=5]=\"SHUTDOWN_PENDING\";r[r[\"SHUTDOWN_SENT\"]=6]=\"SHUTDOWN_SENT\";r[r[\"SHUTDOWN_RECEIVED\"]=7]=\"SHUTDOWN_RECEIVED\";r[r[\"SHUTDOWN_ACK_SENT\"]=8]=\"SHUTDOWN_ACK_SENT\"})(A||(A={}));var _r=require(\"node:crypto\");var Er=4;var De=12;var Ji=4;var ld=12;var ht=Ji+ld;var fe=class r{static{a(this,\"Chunk\")}get body(){return this._body}set body(e){this._body=e}static{this.type=-1}constructor(e=0,t=Buffer.from(\"\")){this.flags=e;this._body=t}get type(){return r.type}get bytes(){if(!this.body)throw new Error;const e=Buffer.alloc(Ji);e.writeUInt8(this.type,0);e.writeUInt8(this.flags,1);e.writeUInt16BE(this.body.length+Ji,2);const t=Buffer.concat([e,this.body,...[...Array(It(this.body.length))].map(()=>Buffer.from(\"\\0\"))]);return t}};var Rr=class extends fe{static{a(this,\"BaseInitChunk\")}constructor(e=0,t){super(e,t);this.flags=e;if(t){this.initiateTag=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);this.outboundStreams=t.readUInt16BE(8);this.inboundStreams=t.readUInt16BE(10);this.initialTsn=t.readUInt32BE(12);this.params=pd(t.slice(16))}else{this.initiateTag=0;this.advertisedRwnd=0;this.outboundStreams=0;this.inboundStreams=0;this.initialTsn=0;this.params=[]}}get body(){const e=Buffer.alloc(16);e.writeUInt32BE(this.initiateTag,0);e.writeUInt32BE(this.advertisedRwnd,4);e.writeUInt16BE(this.outboundStreams,8);e.writeUInt16BE(this.inboundStreams,10);e.writeUInt32BE(this.initialTsn,12);return Buffer.concat([e,fd(this.params)])}};var Rt=class r extends Rr{static{a(this,\"InitChunk\")}static{this.type=1}get type(){return r.type}};var ls=class r extends Rr{static{a(this,\"InitAckChunk\")}static{this.type=2}get type(){return r.type}};var Zi=class r extends Rr{static{a(this,\"ReConfigChunk\")}static{this.type=130}get type(){return r.type}};var xt=class r extends fe{static{a(this,\"ForwardTsnChunk\")}static{this.type=192}constructor(e=0,t){super(e,t);this.flags=e;this.streams=[];if(t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;while(s<t.length){this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]);s+=4}}else{this.cumulativeTsn=0}}get type(){return r.type}set body(e){}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return Buffer.concat([e,...this.streams.map(([t,s])=>{const i=Buffer.alloc(4);i.writeUInt16BE(t,0);i.writeUInt16BE(s,2);return i})])}};var Ee=class r extends fe{static{a(this,\"DataChunk\")}static{this.type=0}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.tsn=0;this.streamId=0;this.streamSeqNum=0;this.protocol=0;this.userData=Buffer.from(\"\");this.abandoned=false;this.acked=false;this.misses=0;this.retransmit=false;this.sentCount=0;this.bookSize=0;if(t){this.tsn=t.readUInt32BE(0);this.streamId=t.readUInt16BE(4);this.streamSeqNum=t.readUInt16BE(6);this.protocol=t.readUInt32BE(8);this.userData=t.slice(12)}}get bytes(){const e=ht+this.userData.length;const t=Buffer.alloc(ht);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.tsn,4);t.writeUInt16BE(this.streamId,8);t.writeUInt16BE(this.streamSeqNum,10);t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);if(e%4){s=Buffer.concat([s,...[...Array(It(e))].map(()=>Buffer.from(\"\\0\"))])}return s}};var fs=class r extends fe{static{a(this,\"CookieEchoChunk\")}static{this.type=10}get type(){return r.type}};var ps=class r extends fe{static{a(this,\"CookieAckChunk\")}static{this.type=11}get type(){return r.type}};var kt=class extends fe{static{a(this,\"BaseParamsChunk\")}constructor(e=0,t=void 0){super(e,t);this.flags=e;this.params=[];if(t){this.params=pd(t)}}get body(){return fd(this.params)}};var ms=class r extends kt{static{a(this,\"AbortChunk\")}static{this.type=6}get type(){return r.type}};var vt=class r extends kt{static{a(this,\"ErrorChunk\")}static{this.type=9}static{this.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 r.type}get descriptions(){return this.params.map(([e,t])=>{const s=(Object.entries(r.CODE).find(([,i])=>i===e)||[])[0];return{name:s,body:t}})}};var gs=class r extends kt{static{a(this,\"HeartbeatChunk\")}static{this.type=4}get type(){return r.type}};var xr=class r extends kt{static{a(this,\"HeartbeatAckChunk\")}static{this.type=5}get type(){return r.type}};var Ss=class r extends kt{static{a(this,\"ReconfigChunk\")}static{this.type=130}get type(){return r.type}};var ys=class r extends fe{static{a(this,\"SackChunk\")}static{this.type=3}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.gaps=[];this.duplicates=[];this.cumulativeTsn=0;this.advertisedRwnd=0;if(t){this.cumulativeTsn=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);const s=t.readUInt16BE(8);const i=t.readUInt16BE(10);let n=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(n),t.readUInt16BE(n+2)]);n+=4});[...Array(i)].forEach(()=>{this.duplicates.push(t.readUInt32BE(n));n+=4})}}get bytes(){const e=16+4*(this.gaps.length+this.duplicates.length);const t=Buffer.alloc(16);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.cumulativeTsn,4);t.writeUInt32BE(this.advertisedRwnd,8);t.writeUInt16BE(this.gaps.length,12);t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...this.gaps.map(i=>{const n=Buffer.alloc(4);n.writeUInt16BE(i[0],0);n.writeUInt16BE(i[1],2);return n})]);s=Buffer.concat([s,...this.duplicates.map(i=>{const n=Buffer.alloc(4);n.writeUInt32BE(i,0);return n})]);return s}};var kr=class r extends fe{static{a(this,\"ShutdownChunk\")}static{this.type=7}get type(){return r.type}constructor(e=0,t){super(e,t);this.flags=e;this.cumulativeTsn=0;if(t){this.cumulativeTsn=t.readUInt32BE(0)}}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return e}};var vr=class r extends fe{static{a(this,\"ShutdownAckChunk\")}static{this.type=8}get type(){return r.type}};var Ir=class r extends fe{static{a(this,\"ShutdownCompleteChunk\")}static{this.type=14}get type(){return r.type}};var nf=[Ee,Rt,ls,ys,gs,xr,ms,kr,vr,vt,fs,ps,Ir,Ss,xt];var of=nf.reduce((r,e)=>{r[e.type]=e;return r},{});function It(r){const e=r%Er;return e?Er-e:0}a(It,\"padL\");function fd(r){let e=Buffer.from(\"\");let t=Buffer.from(\"\");r.forEach(([s,i])=>{const n=i.length+4;const o=Buffer.alloc(4);o.writeUInt16BE(s,0);o.writeUInt16BE(n,2);e=Buffer.concat([e,t,o,i]);t=Buffer.concat([...Array(It(n))].map(()=>Buffer.from(\"\\0\")))});return e}a(fd,\"encodeParams\");function pd(r){const e=[];let t=0;while(t<=r.length-4){const s=r.readUInt16BE(t);const i=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+i)]);t+=i+It(i)}return e}a(pd,\"decodeParams\");function md(r){if(r.length<De)throw new Error(\"SCTP packet length is less than 12 bytes\");const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);const s=r.readUInt32BE(4);const i=r.readUInt32LE(8);let n=ar(r.subarray(0,8));n=ar(af,n);n=ar(r.subarray(De),n);if(i!==n>>>0)throw new Error(\"SCTP packet has invalid checksum\");const o=[];let c=De;while(c+4<=r.length){const d=r.readUInt8(c);const h=r.readUInt8(c+1);const l=r.readUInt16BE(c+2);const u=r.slice(c+4,c+l);const g=of[d.toString()];if(g){o.push(new g(h,u))}else{throw new Error(\"unknown\")}c+=l+It(l)}return[e,t,s,o]}a(md,\"parsePacket\");var af=Buffer.alloc(4);function gd(r,e){if(r instanceof Ee){const t=ht+r.userData.length;return t+It(t)}return e.length}a(gd,\"wireLength\");function Vo(r,e,t,s){const i=s.map(d=>d instanceof Ee?void 0:d.bytes);let n=De;for(let d=0;d<s.length;d++){n+=gd(s[d],i[d])}const o=Buffer.allocUnsafe(n);o.writeUInt16BE(r,0);o.writeUInt16BE(e,2);o.writeUInt32BE(t,4);o.writeUInt32LE(0,8);let c=De;for(let d=0;d<s.length;d++){const h=s[d];const l=i[d];if(l){l.copy(o,c);c+=l.length;continue}const u=h;const g=ht+u.userData.length;o.writeUInt8(u.type,c);o.writeUInt8(u.flags,c+1);o.writeUInt16BE(g,c+2);o.writeUInt32BE(u.tsn,c+4);o.writeUInt16BE(u.streamId,c+8);o.writeUInt16BE(u.streamSeqNum,c+10);o.writeUInt32BE(u.protocol,c+12);u.userData.copy(o,c+ht);const S=It(g);if(S)o.fill(0,c+g,c+g+S);c+=g+S}o.writeUInt32LE(ar(o)>>>0,8);return o}a(Vo,\"serializePackets\");function Sd(r){return gd(r,r instanceof Ee?void 0:r.bytes)}a(Sd,\"chunkWireLength\");function yd(r,e,t,s){return Vo(r,e,t,[s])}a(yd,\"serializePacket\");function Td(r){return r.map((e,t)=>[t,e])}a(Td,\"enumerate\");function wd(r){return r.reduce((e,t)=>{e[t]=new w;return e},{})}a(wd,\"createEventsFromList\");var Ts=class r{static{a(this,\"OutgoingSSNResetRequestParam\")}static{this.type=13}constructor(e,t,s,i){this.requestSequence=e;this.responseSequence=t;this.lastTsn=s;this.streams=i}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(12);e.writeUInt32BE(this.requestSequence,0);e.writeUInt32BE(this.responseSequence,4);e.writeUInt32BE(this.lastTsn,8);return Buffer.concat([e,...this.streams.map(t=>{const s=Buffer.allocUnsafe(2);s.writeUInt16BE(t,0);return s})])}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);const i=e.readUInt32BE(8);const n=[];for(let o=12;o<e.length;o+=2){n.push(e.readUInt16BE(o))}return new r(t,s,i,n)}};var Pr=class r{static{a(this,\"StreamAddOutgoingParam\")}static{this.type=17}constructor(e,t){this.requestSequence=e;this.newStreams=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.requestSequence,0);e.writeUInt16BE(this.newStreams,4);e.writeUInt16BE(0,6);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt16BE(4);return new r(t,s)}};var Ar={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5};var Pt=class r{static{a(this,\"ReconfigResponseParam\")}static{this.type=16}constructor(e,t){this.responseSequence=e;this.result=t}get type(){return r.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.responseSequence,0);e.writeUInt32BE(this.result,4);return e}static parse(e){const t=e.readUInt32BE(0);const s=e.readUInt32BE(4);return new r(t,s)}};var Yo={13:Ts,16:Pt,17:Pr};var v=b(\"webrtc/sctp/sctp\");var cf=24;var df=60;var bd=65535;var bs=1191;function Jo(r,e=ht){const t=De+e;if(r<=t)return 0;const s=r-t;return s-s%Er}a(Jo,\"maxPayloadSizeForMtu\");function sn(r){if(!Number.isSafeInteger(r)||r<=0){throw new Error(\"SCTP MTU must be a positive integer\")}if(Jo(r)===0){throw new Error(\"SCTP MTU is too small for a DATA chunk\")}}a(sn,\"validateSctpMtu\");var ws=1;var en=2;var tn=4;var Cd=10;var hf=8;var uf=10;var lf=2;var Ed=1/8;var Rd=1/4;var xd=3;var ff=1;var pf=60;var $e=2**32;var mf=20;var gf=4096;var Sf=30;var kd=135;var vd=7;var Id=32776;var Pd=49152;var yf=[\"new\",\"closed\",\"connected\",\"connecting\"];var Br=class r{static{a(this,\"SCTP\")}get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}constructor(e,t=5e3,s={}){this.transport=e;this.port=t;this.flush=new w;this.stateChanged=wd(yf);this.onReconfigStreams=new w;this.onReceive=new w;this.onSackReceived=async()=>{};this.associationState=A.CLOSED;this.started=false;this.state=\"new\";this.isServer=true;this.isStopping=false;this.isClosed=false;this.hmacKey=(0,_r.randomBytes)(16);this.localPartialReliability=true;this.localVerificationTag=Ci();this.remoteExtensions=[];this.remotePartialReliability=true;this.remoteVerificationTag=0;this.advertisedRwnd=1024*1024;this.lastAdvertisedRwnd=this.advertisedRwnd;this.peerAdvertisedRwnd=this.advertisedRwnd;this.inboundStreams={};this._inboundStreamsCount=0;this._inboundStreamsMax=bd;this.pendingChunks=0;this.sackDuplicates=[];this.sackMisOrdered=new Set;this.sackNeeded=false;this.sackPacketCount=0;this.sackHasNewDataInPacket=false;this.sackImmediate=false;this.fastRecoveryTransmit=false;this.flightSize=0;this.outboundQueue=new fr;this.outboundStreamSeq={};this._outboundStreamsCount=bd;this.localTsn=Number(Ci());this.lastSackedTsn=At(this.localTsn);this.advancedPeerAckTsn=At(this.localTsn);this.partialBytesAcked=0;this.sentQueue=new fr;this.retransmitPending=false;this.transmitting=false;this.transmitRequested=false;this.transmitScheduled=false;this.reconfigRequestSeq=this.localTsn;this.reconfigResponseSeq=0;this.reconfigQueue=[];this.rto=xd;this.timer1Failures=0;this.timer2Failures=0;this.timerReconfigFailures=0;this.heartbeatInterval=Sf;this.send=async(i,n,o,{expiry:c,maxRetransmits:d,ordered:h}={expiry:void 0,maxRetransmits:void 0,ordered:true})=>{const l=h?this.outboundStreamSeq[i]||0:0;const u=Math.ceil(o.length/this.maxPayloadSize);let g=0;const S=[];for(let p=0;p<u;p++){const f=new Ee(0,void 0);f.flags=0;if(!h){f.flags=tn}if(p===0){f.flags|=en}if(p===u-1){f.flags|=ws}f.tsn=this.localTsn;f.streamId=i;f.streamSeqNum=l;f.protocol=n;f.userData=o.subarray(g,g+this.maxPayloadSize);f.bookSize=f.userData.length;f.expiry=c;f.maxRetransmits=d;g+=this.maxPayloadSize;this.localTsn=_t(this.localTsn);S.push(f)}for(const p of S){this.outboundQueue.push(p)}if(h){this.outboundStreamSeq[i]=j(l,1)}this.transmitSoon()};this.timer1Expired=()=>{if(this.isStopped)return;this.timer1Failures++;this.timer1Handle=void 0;if(this.timer1Failures>hf){this.setState(A.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch(i=>{v(\"send timer1 chunk failed\",i.message)})});if(this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};this.timer2Expired=()=>{if(this.isStopped)return;this.timer2Failures++;this.timer2Handle=void 0;if(this.timer2Failures>Cd){this.setState(A.CLOSED)}else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch(i=>{v(\"send timer2Chunk failed\",i.message)})});if(this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};this.timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0;for(const i of this.sentQueue){if(!this.maybeAbandon(i)){i.retransmit=true;this.retransmitPending=true}}this.updateAdvancedPeerAckPoint();this.fastRecoveryExit=void 0;this.flightSize=0;this.partialBytesAcked=0;this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.maxPayloadSize;this.transmit().catch(i=>v(\"transmit failed\",i))};this.timerReconfigHandleExpired=async()=>{if(this.isStopped)return;this.timerReconfigFailures++;this.rto=Math.ceil(this.rto*1.5);if(this.timerReconfigFailures>Cd){v(\"timerReconfigFailures\",this.timerReconfigFailures);this.setState(A.CLOSED);this.timerReconfigHandle=void 0}else if(this.reconfigRequest){v(\"timerReconfigHandleExpired\",this.timerReconfigFailures,this.rto);await this.sendReconfigParam(this.reconfigRequest);if(this.isStopped)return;this.timerReconfigHandle=setTimeout(ye(this.timerReconfigHandleExpired,i=>v(\"reconfig timer failed\",i)),this.rto*1e3)}};this.timerHeartbeatExpired=async()=>{this.timerHeartbeatHandle=void 0;if(this.associationState!==A.ESTABLISHED)return;if(this.flightSize===0&&this.outboundQueue.length===0){const i=new gs;const n=Buffer.allocUnsafe(4);n.writeUInt32BE(Math.floor(Date.now()/1e3),0);i.params.push([1,n]);await this.sendChunk(i).catch(o=>{v(\"send heartbeat failed\",o.message)})}this.heartbeatStart()};this.mtu=s.mtu??bs;sn(this.mtu);this.maxPayloadSize=Jo(this.mtu);this.cwnd=uf*this.maxPayloadSize;this.localPort=this.port;this.transport.onData=i=>{this.handleData(i).catch(n=>v(\"receive failed\",n))}}get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0){return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}return void 0}static client(e,t=5e3,s={}){const i=new r(e,t,s);i.isServer=false;return i}static server(e,t=5e3,s={}){const i=new r(e,t,s);i.isServer=true;return i}async handleData(e){if(this.isStopped)return;let t;const[,,s,i]=md(e);const n=i.filter(o=>o.type===Rt.type).length;if(n>0){if(i.length!=1){throw new Error}t=0}else{t=this.localVerificationTag}if(s!==t){return}this.sackHasNewDataInPacket=false;for(const o of i){if(o.type===Ee.type)this.receiveDataChunk(o);else await this.receiveChunk(o)}if(this.sackNeeded){if(this.sackHasNewDataInPacket){this.sackPacketCount++}if(this.sackPacketCount>=2){this.sackImmediate=true}await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0;this.sendSack().catch(e=>{v(\"send delayed sack failed\",e.message)})},mf)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;await this.sendChunk(this.takeSack()).catch(e=>{v(\"send sack failed\",e.message)})}takeSack(){const e=[];let t;const s=[...this.sackMisOrdered].sort((n,o)=>(n-this.lastReceivedTsn+$e)%$e-(o-this.lastReceivedTsn+$e)%$e);for(const n of s){const o=(n-this.lastReceivedTsn+$e)%$e;if(n===t){e[e.length-1][1]=o}else{e.push([o,o])}t=_t(n)}const i=new ys(0,void 0);i.cumulativeTsn=this.lastReceivedTsn;i.advertisedRwnd=Math.max(0,this.advertisedRwnd);this.lastAdvertisedRwnd=i.advertisedRwnd;i.duplicates=[...this.sackDuplicates];i.gaps=e;this.sackDuplicates=[];this.sackNeeded=false;this.sackPacketCount=0;this.sackImmediate=false;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}return i}async receiveChunk(e){switch(e.type){case Ee.type:{this.receiveDataChunk(e)}break;case Rt.type:{if(!this.isServer)return;const t=e;v(\"receive init\",t);this.lastReceivedTsn=At(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=At(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new ls;s.initiateTag=this.localVerificationTag;s.advertisedRwnd=this.advertisedRwnd;s.outboundStreams=this._outboundStreamsCount;s.inboundStreams=this._inboundStreamsCount;s.initialTsn=this.localTsn;this.setExtensions(s.params);const i=Math.floor(Date.now()/1e3);const n=Buffer.allocUnsafe(4);n.writeUInt32BE(i,0);let o=n;o=Buffer.concat([o,(0,_r.createHmac)(\"sha1\",this.hmacKey).update(o).digest()]);s.params.push([vd,o]);v(\"send initAck\",s);await this.sendChunk(s).catch(c=>{v(\"send initAck failed\",c.message)})}break;case ls.type:{if(this.associationState!=A.COOKIE_WAIT)return;const t=e;this.timer1Cancel();this.lastReceivedTsn=At(t.initialTsn);this.highestReceivedTsn=this.lastReceivedTsn;this.reconfigResponseSeq=At(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const s=new fs;for(const[i,n]of t.params){if(i===vd){s.body=n;break}}await this.sendChunk(s).catch(i=>{v(\"send echo failed\",i.message)});this.timer1Start(s);this.setState(A.COOKIE_ECHOED)}break;case ys.type:{await this.receiveSackChunk(e)}break;case gs.type:{const t=new xr;t.params=e.params;await this.sendChunk(t).catch(s=>{v(\"send heartbeat ack failed\",s.message)})}break;case ms.type:{this.setState(A.CLOSED)}break;case kr.type:{this.timer2Cancel();this.setState(A.SHUTDOWN_RECEIVED);const t=new vr;await this.sendChunk(t).catch(s=>{v(\"send shutdown ack failed\",s.message)});this.t2Start(t);this.setState(A.SHUTDOWN_SENT)}break;case vt.type:{v(\"ErrorChunk\",e.descriptions)}break;case fs.type:{if(!this.isServer)return;const t=e;const s=t.body;const i=(0,_r.createHmac)(\"sha1\",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=cf||!s.slice(4).equals(i)){v(\"x State cookie is invalid\");return}const n=Math.floor(Date.now()/1e3);const o=s.readUInt32BE(0);if(o<n-df||o>n){const d=new vt(0,void 0);d.params.push([vt.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(\"\\0\")))]);await this.sendChunk(d).catch(h=>{v(\"send errorChunk failed\",h.message)});return}const c=new ps;await this.sendChunk(c).catch(d=>{v(\"send cookieAck failed\",d.message)});this.setState(A.ESTABLISHED)}break;case ps.type:{if(this.associationState!=A.COOKIE_ECHOED)return;this.timer1Cancel();this.setState(A.ESTABLISHED)}break;case Ir.type:{if(this.associationState!=A.SHUTDOWN_ACK_SENT)return;this.timer2Cancel();this.setState(A.CLOSED)}break;case Ss.type:{if(this.associationState!=A.ESTABLISHED)return;const t=e;for(const[s,i]of t.params){const n=Yo[s];if(n){await this.receiveReconfigParam(n.parse(i))}}}break;case xt.type:{this.receiveForwardTsnChunk(e)}break}}getExtensions(e){for(const[t,s]of e){if(t===Pd){this.remotePartialReliability=true}else if(t===Id){this.remoteExtensions=[...s]}}}async receiveReconfigParam(e){v(\"receiveReconfigParam\",Yo[e.type]);switch(e.type){case Ts.type:{const t=e;const s=new Pt(t.requestSequence,Ar.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s);await Promise.all(t.streams.map(async i=>{const n=this.inboundStreams[i];if(n){this.pendingChunks-=n.reassembly.length;this.advertisedRwnd+=n.reassembly.reduce((o,c)=>o+c.userData.length,0)}delete this.inboundStreams[i];if(this.outboundStreamSeq[i]){if(!this.reconfigQueue.includes(i)){this.reconfigQueue.push(i)}}}));await this.transmitReconfigRequest();this.onReconfigStreams.execute(t.streams)}break;case Pt.type:{const t=e;if(t.result!==Ar.ReconfigResultSuccessPerformed){v(\"OutgoingSSNResetRequestParam failed\",Object.keys(Ar).find(s=>Ar[s]===t.result))}else if(t.responseSequence===this.reconfigRequest?.requestSequence){const s=this.reconfigRequest.streams.map(i=>{delete this.outboundStreamSeq[i];return i});this.onReconfigStreams.execute(s);this.reconfigRequest=void 0;this.timerReconfigCancel();this.rto=xd;this.timerReconfigFailures=0;if(this.reconfigQueue.length>0){await this.transmitReconfigRequest()}}}break;case Pr.type:{const t=e;this._inboundStreamsCount+=t.newStreams;const s=new Pt(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(s)}break}}receiveDataChunk(e){this.sackNeeded=true;if((this.advertisedRwnd<=0||this.pendingChunks>=gf)&&ae(e.tsn,this.highestReceivedTsn)){this.sackImmediate=true;return}if(this.markReceived(e.tsn)){this.sackImmediate=true;return}this.sackHasNewDataInPacket=true;if(this.sackMisOrdered.size>0){this.sackImmediate=true}const t=this.getInboundStream(e.streamId);if((e.flags&(en|ws))===(en|ws)){if(e.flags&tn){this.receive(e.streamId,e.protocol,e.userData);return}if(t.reassembly.length===0&&e.streamSeqNum===t.streamSequenceNumber){t.streamSequenceNumber=j(t.streamSequenceNumber,1);this.receive(e.streamId,e.protocol,e.userData);return}}const s=t.reassembly.length;t.addChunk(e);this.advertisedRwnd-=e.userData.length;for(const i of t.popMessages()){this.advertisedRwnd+=i[2].length;this.receive(...i)}this.pendingChunks+=t.reassembly.length-s}async receiveSackChunk(e){if(ae(this.lastSackedTsn,e.cumulativeTsn))return;const t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;const s=this.flightSize>=this.cwnd;let i=0,n=0;while(this.sentQueue.length>0&&Xt(this.lastSackedTsn,this.sentQueue.at(0).tsn)){const c=this.sentQueue.shift();i++;if(!c?.acked){n+=c.bookSize;this.flightSizeDecrease(c)}if(i===1&&c.sentCount===1){this.updateRto(t-c.sentTime)}}let o=false;if(e.gaps.length>0){const c=new Set;let d;e.gaps.forEach(l=>{for(let u=l[0];u<l[1]+1;u++){d=(e.cumulativeTsn+u)%$e;c.add(d)}});let h=e.cumulativeTsn;for(const l of this.sentQueue){if(ae(l.tsn,d)){break}if(c.has(l.tsn)&&!l.acked){n+=l.bookSize;l.acked=true;this.flightSizeDecrease(l);h=l.tsn}}for(const l of this.sentQueue){if(ae(l.tsn,h)){break}if(!c.has(l.tsn)){l.misses++;if(l.misses===3){l.misses=0;if(!this.maybeAbandon(l)){l.retransmit=true;this.retransmitPending=true}l.acked=false;this.flightSizeDecrease(l);o=true}}}}if(this.fastRecoveryExit===void 0){if(i&&s){if(this.cwnd<=this.ssthresh){this.cwnd+=Math.min(n,lf*this.maxPayloadSize)}else{this.partialBytesAcked+=n;if(this.partialBytesAcked>=this.cwnd){this.partialBytesAcked-=this.cwnd;this.cwnd+=this.maxPayloadSize}}}if(o){this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.ssthresh;this.partialBytesAcked=0;this.fastRecoveryExit=this.sentQueue.at(-1).tsn;this.fastRecoveryTransmit=true}}else if(Xt(e.cumulativeTsn,this.fastRecoveryExit)){this.fastRecoveryExit=void 0}if(this.sentQueue.length===0){this.timer3Cancel()}else if(i>0){this.timer3Restart()}this.peerAdvertisedRwnd=e.advertisedRwnd;this.updateAdvancedPeerAckPoint();await this.onSackReceived();await this.transmit()}receiveForwardTsnChunk(e){this.sackNeeded=true;this.sackImmediate=true;if(Xt(this.lastReceivedTsn,e.cumulativeTsn)){return}const t=a(s=>ae(s,this.lastReceivedTsn),\"isObsolete\");this.lastReceivedTsn=e.cumulativeTsn;this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const s of[...this.sackMisOrdered].sort()){if(s===_t(this.lastReceivedTsn)){this.lastReceivedTsn=s}else{break}}this.sackDuplicates=this.sackDuplicates.filter(t);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(const[s,i]of e.streams){const n=this.getInboundStream(s);n.streamSequenceNumber=j(i,1);for(const o of n.popMessages()){this.advertisedRwnd+=o[2].length;this.receive(...o)}}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)});this.pendingChunks=Object.values(this.inboundStreams).reduce((s,i)=>s+i.reassembly.length,0);if(ae(this.lastReceivedTsn,this.highestReceivedTsn))this.highestReceivedTsn=this.lastReceivedTsn}updateRto(e){if(!this.srtt){this.rttvar=e/2;this.srtt=e}else{this.rttvar=(1-Rd)*this.rttvar+Rd*Math.abs(this.srtt-e);this.srtt=(1-Ed)*this.srtt+Ed*e}this.rto=Math.max(ff,Math.min(this.srtt+4*this.rttvar,pf))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){if(!this.inboundStreams[e]){this.inboundStreams[e]=new Qo}return this.inboundStreams[e]}markReceived(e){if(Xt(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e)){this.sackDuplicates.push(e);return true}if(ae(e,this.highestReceivedTsn))this.highestReceivedTsn=e;if(e===_t(this.lastReceivedTsn)){this.lastReceivedTsn=e;while(this.sackMisOrdered.size>0){const t=_t(this.lastReceivedTsn);if(!this.sackMisOrdered.delete(t))break;this.lastReceivedTsn=t}if(this.sackDuplicates.length>0){const t=a(s=>ae(s,this.lastReceivedTsn),\"isObsolete\");this.sackDuplicates=this.sackDuplicates.filter(t)}}else{this.sackMisOrdered.add(e)}return false}holdReceived(e){this.advertisedRwnd-=e}releaseReceived(e){this.advertisedRwnd+=e;if(this.associationState!==A.ESTABLISHED||this.lastReceivedTsn===void 0)return;if(this.lastAdvertisedRwnd*2<this.advertisedRwnd){this.sackNeeded=true;this.sackImmediate=true;this.scheduleSack().catch(t=>v(\"send window update failed\",t.message))}}transmitSoon(){if(this.transmitScheduled)return;this.transmitScheduled=true;queueMicrotask(()=>{this.transmitScheduled=false;this.transmit().catch(e=>v(\"transmit failed\",e))})}async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=true;return}this.transmitting=true;try{do{this.transmitRequested=false;this.transmitOnce()}while(this.transmitRequested)}finally{this.transmitting=false}}transmitOnce(){if(this.isStopped)return;const e=[];let t=De;let s=false;const i=a(()=>{if(e.length===0)return;this.sendChunks(e.splice(0,e.length));t=De},\"flush\");const n=a(h=>{const l=Sd(h);if(e.length>0&&t+l>this.mtu)i();e.push(h);t+=l},\"add\");const o=a(h=>{if(!s&&this.sackNeeded&&this.lastReceivedTsn!==void 0){n(this.takeSack());s=true}n(h)},\"addData\");if(this.forwardTsnChunk){n(this.forwardTsnChunk);this.forwardTsnChunk=void 0;if(!this.timer3Handle){this.timer3Start()}}const c=this.fastRecoveryExit!=void 0?2*this.maxPayloadSize:4*this.maxPayloadSize;const d=Math.min(this.flightSize+c,this.cwnd);if(this.retransmitPending){let h=true;let l=true;for(const u of this.sentQueue){if(u.retransmit){if(this.fastRecoveryTransmit){this.fastRecoveryTransmit=false}else if(this.flightSize>=d){l=false;break}this.flightSizeIncrease(u);u.misses=0;u.retransmit=false;u.sentCount++;o(u);if(h){this.timer3Restart()}}h=false}if(l)this.retransmitPending=false}while(this.outboundQueue.length>0&&this.flightSize<d&&(this.peerRwnd>0||this.flightSize===0)){const h=this.outboundQueue.shift();if(!h)break;if(h.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(h);break}this.sentQueue.push(h);this.flightSizeIncrease(h);h.sentCount++;h.sentTime=Date.now()/1e3;o(h);this.onSent?.(h.streamId,h.protocol,h.userData.length);if(!this.timer3Handle){this.timer3Start()}}i();this.flush.execute()}sendChunks(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){v(\"send chunks failed\",\"invalid remote port\");return}const t=Vo(this.localPort,this.remotePort,this.remoteVerificationTag,e);this.transport.send(t).catch(s=>{v(\"send packet failed\",s.message)})}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===A.ESTABLISHED&&!this.reconfigRequest){const e=[...new Set(this.reconfigQueue)];const t=e.slice(0,kd);this.reconfigQueue=e.slice(kd);const s=new Ts(this.reconfigRequestSeq,this.reconfigResponseSeq,At(this.localTsn),t);this.reconfigRequestSeq=_t(this.reconfigRequestSeq);this.reconfigRequest=s;await this.sendReconfigParam(s);this.timerReconfigHandleStart()}}async sendReconfigParam(e){v(\"sendReconfigParam\",e);const t=new Ss;t.params.push([e.type,e.bytes]);await this.sendChunk(t).catch(s=>{v(\"send reconfig failed\",s.message)})}async sendResetRequest(e){v(\"sendResetRequest\",e);const t=new Ee(0,void 0);t.streamId=e;this.outboundQueue.push(t);if(!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)}timer1Cancel(){if(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)}timer2Cancel(){if(this.timer2Handle){clearTimeout(this.timer2Handle);this.timer2Handle=void 0;this.timer2Chunk=void 0}}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Cancel(){if(this.timer3Handle){clearTimeout(this.timer3Handle);this.timer3Handle=void 0}}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;v(\"timerReconfigHandleStart\",{rto:this.rto});this.timerReconfigFailures=0;this.timerReconfigHandle=setTimeout(ye(this.timerReconfigHandleExpired,e=>v(\"reconfig timer failed\",e)),this.rto*1e3)}timerReconfigCancel(){if(this.timerReconfigHandle){v(\"timerReconfigCancel\");clearTimeout(this.timerReconfigHandle);this.timerReconfigHandle=void 0;this.timerReconfigFailures=0}}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==A.ESTABLISHED){return}this.timerHeartbeatHandle=setTimeout(ye(this.timerHeartbeatExpired,e=>v(\"heartbeat failed\",e)),(this.rto+this.heartbeatInterval)*1e3)}heartbeatRestart(){this.heartbeatCancel();this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle){clearTimeout(this.timerHeartbeatHandle);this.timerHeartbeatHandle=void 0}}setHeartbeatInterval(e){if(e<=0){throw new Error(\"heartbeat interval must be > 0\")}this.heartbeatInterval=e;this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(ae(this.lastSackedTsn,this.advancedPeerAckTsn)){this.advancedPeerAckTsn=this.lastSackedTsn}let e=0;const t={};while(this.sentQueue.length>0&&this.sentQueue.at(0).abandoned){const s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn;e++;if(!(s.flags&tn)){t[s.streamId]=s.streamSeqNum}}if(e){this.forwardTsnChunk=new xt(0,void 0);this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn;this.forwardTsnChunk.streams=Object.entries(t).map(([s,i])=>[Number(s),i])}}maybeAbandon(e){if(e.abandoned)return true;const t=!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3;if(!t)return false;const s=this.sentQueue.findIndex(i=>i===e);for(let i=s;i>=0;i--){const n=this.sentQueue.at(i);n.abandoned=true;n.retransmit=false;if(n.flags&ws){break}}for(let i=s;i<this.sentQueue.length;i++){const n=this.sentQueue.at(i);n.abandoned=true;n.retransmit=false;if(n.flags&ws){break}}return true}static getCapabilities(){return new Xo(65536)}setRemotePort(e){this.remotePort=e}async start(e){if(!this.started){this.started=true;this.setConnectionState(\"connecting\");if(e){this.setRemotePort(e)}if(!this.isServer){await this.init()}}}async init(){const e=new Rt;e.initiateTag=this.localVerificationTag;e.advertisedRwnd=this.advertisedRwnd;e.outboundStreams=this._outboundStreamsCount;e.inboundStreams=this._inboundStreamsMax;e.initialTsn=this.localTsn;this.setExtensions(e.params);v(\"send init\",e);try{await this.sendChunk(e);this.timer1Start(e);this.setState(A.COOKIE_WAIT)}catch(t){v(\"send init failed\",t.message)}}setExtensions(e){const t=[];if(this.localPartialReliability){e.push([Pd,Buffer.from(\"\")]);t.push(xt.type)}t.push(Zi.type);e.push([Id,Buffer.from(t)])}async sendChunk(e){if(this.state===\"closed\")return;if(this.remotePort===void 0){throw new Error(\"invalid remote port\")}const t=yd(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){if(e!=this.associationState){this.associationState=e}if(e===A.ESTABLISHED){this.isStopping=false;this.isClosed=false;this.setConnectionState(\"connected\");this.heartbeatStart()}else if(e===A.CLOSED){this.isClosed=true;this.timer1Cancel();this.timer2Cancel();this.timer3Cancel();this.timerReconfigCancel();this.heartbeatCancel();if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}this.setConnectionState(\"closed\");this.removeAllListeners()}}setConnectionState(e){this.state=e;v(\"setConnectionState\",e);this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(A.CLOSED);return}this.isStopping=true;this.transport.onData=void 0;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}if(this.associationState!==A.CLOSED){await this.abort()}this.setState(A.CLOSED);clearTimeout(this.timer1Handle);clearTimeout(this.timer2Handle);clearTimeout(this.timer3Handle);clearTimeout(this.timerReconfigHandle);clearTimeout(this.timerHeartbeatHandle);clearTimeout(this.sackTimeout)}async abort(){const e=new ms;await this.sendChunk(e).catch(t=>{v(\"send abort failed\",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}};var Qo=class{static{a(this,\"InboundStream\")}constructor(){this.reassembly=[];this.streamSequenceNumber=0}addChunk(e){if(this.reassembly.length===0||ae(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(const[t,s]of Td(this.reassembly)){if(s.tsn===e.tsn)throw new Error(\"duplicate chunk in reassembly\");if(ae(s.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0;let t;let s;let i;while(e<this.reassembly.length){const n=this.reassembly[e];if(t===void 0){i=!(n.flags&tn);if(!(n.flags&en)){if(i){break}else{e++;continue}}if(i&&Ei(n.streamSeqNum,this.streamSequenceNumber)){break}s=n.tsn;t=e}else if(n.tsn!==s){if(i){break}else{t=void 0;e++;continue}}if(n.flags&ws){const o=this.reassembly.slice(t,e+1).map(d=>d.userData);const c=o.length===1?o[0]:Buffer.concat(o);this.reassembly.splice(t,e+1-t);if(i&&n.streamSeqNum===this.streamSequenceNumber){this.streamSequenceNumber=j(this.streamSequenceNumber,1)}e=t;yield[n.streamId,n.protocol,c]}else{e++}s=_t(s)}}pruneChunks(e){let t=-1,s=0;for(const[i,n]of this.reassembly.entries()){if(Xt(e,n.tsn)){t=i;s+=n.userData.length}else{break}}this.reassembly=this.reassembly.slice(t+1);return s}};var Xo=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};function At(r){return(r-1)%$e}a(At,\"tsnMinusOne\");function _t(r){return(r+1)%$e}a(_t,\"tsnPlusOne\");function _(r,e=r){return new DOMException(e,r)}a(_,\"createWebRtcDomException\");function Re(r){return new TypeError(r)}a(Re,\"createWebRtcTypeError\");var Lr=a(()=>({type:\"nack\"}),\"useNACK\");var Bt=a(()=>({type:\"nack\",parameter:\"pli\"}),\"usePLI\");var Dr=a(()=>({type:\"goog-remb\"}),\"useREMB\");var rn=a(()=>({type:\"transport-cc\"}),\"useTWCC\");var Zo=a((r={})=>new re({mimeType:\"video/h264\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],parameters:\"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1\",...r}),\"useH264\");var nn=a((r={})=>new re({mimeType:\"video/VP8\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useVP8\");var ea=a((r={})=>new re({mimeType:\"video/VP9\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useVP9\");var Tf=a((r={})=>new re({mimeType:\"video/AV1X\",clockRate:9e4,rtcpFeedback:[Lr(),Bt(),Dr()],...r}),\"useAV1X\");var on=a((r={})=>new re({mimeType:\"audio/OPUS\",clockRate:48e3,channels:2,...r}),\"useOPUS\");var an=a((r={})=>new re({mimeType:\"audio/PCMU\",clockRate:8e3,channels:1,payloadType:0,...r}),\"usePCMU\");function Ad(){return{audio:[on(),an()],video:[nn()]}}a(Ad,\"defaultCodecs\");function _d(r){return new re({mimeType:r.mimeType,clockRate:r.clockRate,...r.channels!=void 0?{channels:r.channels}:{},...r.payloadType!=void 0?{payloadType:r.payloadType}:{},rtcpFeedback:r.rtcpFeedback.map(e=>({...e})),...r.parameters!=void 0?{parameters:r.parameters}:{},direction:r.direction})}a(_d,\"cloneCodecParameters\");var Bd=[Tf(),ea(),nn(),Zo(),on(),an()].map(r=>r.mimeType);var db=Bd.filter(r=>r.toLowerCase().startsWith(\"video/\"));var hb=Bd.filter(r=>r.toLowerCase().startsWith(\"audio/\"));var $u=require(\"node:crypto\");var Vu=require(\"node:net\");var ia=require(\"node:crypto\");var ce={rsa_1:1,ecdsa_3:3};var cn={sha256_4:4};var dn={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199};var Ld=Object.values(dn);var Ve={x25519_29:29,secp256r1_23:23};var hn=Object.values(Ve);var un={named_curve_3:3};var ta={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027};var Dd=[1,64];var ln=[{hash:cn.sha256_4,signature:ce.rsa_1},{hash:cn.sha256_4,signature:ce.ecdsa_3}];var Ye=require(\"node:crypto\");function Qe(r,e){const t=e.length;if(t<128)return Buffer.concat([Buffer.from([r,t]),e]);const s=[];for(let i=t;i>0;i=Math.floor(i/256))s.unshift(i&255);return Buffer.concat([Buffer.from([r,128|s.length,...s]),e])}a(Qe,\"der\");var Lt=a((...r)=>Qe(48,Buffer.concat(r)),\"sequence\");var wf=a((...r)=>Qe(49,Buffer.concat(r)),\"set\");var bf=Buffer.from([5,0]);var Cf=a(r=>Qe(12,Buffer.from(r,\"utf8\")),\"utf8String\");var Ef=a(r=>Qe(3,Buffer.concat([Buffer.from([0]),r])),\"bitString\");var Rf=a((r,e)=>Qe(160|r,e),\"explicit\");function Nd(r){let e=0;while(e<r.length-1&&r[e]===0)e++;const t=r.subarray(e);return Qe(2,t[0]&128?Buffer.concat([Buffer.from([0]),t]):t)}a(Nd,\"integer\");function sa(r){const e=r.split(\".\").map(Number);const t=[e[0]*40+e[1]];for(const s of e.slice(2)){const i=[s&127];for(let n=Math.floor(s/128);n>0;n=Math.floor(n/128))i.unshift(128|n&127);t.push(...i)}return Qe(6,Buffer.from(t))}a(sa,\"oid\");function Md(r){const e=r.toISOString().replace(/[-:T]/g,\"\").slice(0,14);return r.getUTCFullYear()<2050?Qe(23,Buffer.from(`${e.slice(2)}Z`)):Qe(24,Buffer.from(`${e}Z`))}a(Md,\"time\");var xf=a(r=>Lt(wf(Lt(sa(\"2.5.4.3\"),Cf(r)))),\"commonName\");function Od(r=\"ecdsa\",e=\"WebRTC\",t=30){const{privateKey:s,publicKey:i}=r===\"ecdsa\"?(0,Ye.generateKeyPairSync)(\"ec\",{namedCurve:\"prime256v1\"}):(0,Ye.generateKeyPairSync)(\"rsa\",{modulusLength:2048,publicExponent:65537});const n=r===\"ecdsa\"?Lt(sa(\"1.2.840.10045.4.3.2\")):Lt(sa(\"1.2.840.113549.1.1.11\"),bf);const o=new Date(Date.now()-24*60*60*1e3);const c=new Date(o.getTime()+(t+1)*24*60*60*1e3);const d=(0,Ye.randomBytes)(8);d[0]&=127;const h=xf(e);const l=Lt(Rf(0,Nd(Buffer.from([2]))),Nd(d),n,h,Lt(Md(o),Md(c)),h,i.export({type:\"spki\",format:\"der\"}));const u=(0,Ye.sign)(\"sha256\",l,s);const g=Lt(l,n,Ef(u));return{certPem:kf(g,\"CERTIFICATE\"),keyPem:s.export({type:\"pkcs8\",format:\"pem\"})}}a(Od,\"createDtlsCertificate\");function kf(r,e){const t=r.toString(\"base64\").match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----\n${t.join(\"\\n\")}\n-----END ${e}-----\n`}a(kf,\"toPem\");function fn(r){const e=r.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);if(!e)throw new Error(\"no certificate in the PEM text\");return Buffer.from(e[1].replace(/\\s+/g,\"\"),\"base64\")}a(fn,\"certificateDer\");function Ud(r){return(0,Ye.createPrivateKey)(r)}a(Ud,\"privateKeyFromPem\");var pn=require(\"node:crypto\");var xe=require(\"node:crypto\");var Hd=a(()=>{const r=(0,xe.createECDH)(\"prime256v1\");const e=r.generateKeys();return{privateKey:r.getPrivateKey(),publicKey:e}},\"p256Keypair\");var zd=a(({publicKey:r,privateKey:e})=>{const t=(0,xe.createECDH)(\"prime256v1\");t.setPrivateKey(e);return t.computeSecret(r)},\"p256PreMasterSecret\");var qd=Buffer.from(\"302e020100300506032b656e04220420\",\"hex\");var Fd=Buffer.from(\"302a300506032b656e032100\",\"hex\");var Kd=a(()=>{const{privateKey:r,publicKey:e}=(0,xe.generateKeyPairSync)(\"x25519\");return{privateKey:r.export({type:\"pkcs8\",format:\"der\"}).subarray(qd.length),publicKey:e.export({type:\"spki\",format:\"der\"}).subarray(Fd.length)}},\"x25519Keypair\");var Gd=a(({publicKey:r,privateKey:e})=>(0,xe.diffieHellman)({privateKey:(0,xe.createPrivateKey)({key:Buffer.concat([qd,e]),format:\"der\",type:\"pkcs8\"}),publicKey:(0,xe.createPublicKey)({key:Buffer.concat([Fd,r]),format:\"der\",type:\"spki\"})}),\"x25519PreMasterSecret\");function mn(r,e,t){switch(t){case Ve.secp256r1_23:return zd({publicKey:r,privateKey:e});case Ve.x25519_29:return Gd({publicKey:r,privateKey:e});default:throw new Error}}a(mn,\"prfPreMasterSecret\");function jd(r,e,t){const s=(0,pn.createHmac)(r,e);s.update(t);return s.digest()}a(jd,\"hmac\");function Nr(r,e,t,s=\"sha256\"){const i=t;const n=[];let o=e;do{o=jd(s,r,o);const c=jd(s,r,Buffer.concat([o,e]));n.push(c);t-=c.length}while(t>0);return Buffer.concat(n,i)}a(Nr,\"prfPHash\");function gn(r,e,t){const s=Buffer.concat([Buffer.from(\"master secret\"),e,t]);return Nr(r,s,48)}a(gn,\"prfMasterSecret\");function Sn(r,e){const t=$d(\"sha256\",e);const s=\"extended master secret\";return Nr(r,Buffer.concat([Buffer.from(s),t]),48)}a(Sn,\"prfExtendedMasterSecret\");function Wd(r,e,t,s,i,n){const o=n?s:i;const c=n?i:s;const d=Buffer.concat([Buffer.from(r),o,c]);return Nr(t,d,e)}a(Wd,\"exportKeyingMaterial\");function $d(r,e){return(0,pn.createHash)(r).update(e).digest()}a($d,\"hash\");function Vd(r,e,t,s=12){const i=$d(\"sha256\",e);return Nr(r,Buffer.concat([Buffer.from(t),i]),s)}a(Vd,\"prfVerifyData\");function Yd(r,e){return Vd(r,e,\"client finished\")}a(Yd,\"prfVerifyDataClient\");function Qd(r,e){return Vd(r,e,\"server finished\")}a(Qd,\"prfVerifyDataServer\");function Xd(r,e,t,s,i,n,o=\"sha256\"){const c=s*2+i*2;const d=r;const h=Buffer.concat([t,e]);const l=Nr(d,Buffer.concat([Buffer.from(\"key expansion\"),h]),c,o);const u=new x.BinaryReader(l);const g=u.readBuffer(s);const S=u.readBuffer(s);const p=u.readBuffer(i);const f=u.readBuffer(i);const y=Buffer.alloc(n,0);const m=Buffer.alloc(n,0);p.copy(y,0);f.copy(m,0);return{clientWriteKey:g,serverWriteKey:S,clientNonce:y,serverNonce:m}}a(Xd,\"prfEncryptionKeys\");var ie={CLIENT:1,SERVER:2};var Mr=class{static{a(this,\"AbstractCipher\")}constructor(){this.id=0;this.verifyDataLength=12}init(...e){throw new Error(\"not implemented\")}encrypt(...e){throw new Error(\"not implemented\")}decrypt(...e){throw new Error(\"not implemented\")}toString(){return this.name}};var{encode:vf,types:ra}=x;var Xe=class{static{a(this,\"CipherContext\")}constructor(e,t,s,i){this.sessionType=e;this.certPem=t;this.keyPem=s;if(t&&s&&i){this.parseX509(t,s,i)}}static{this.createSelfSignedCertificateWithKey=async(e,t)=>{const{certPem:s,keyPem:i}=Od(e.signature===ce.rsa_1?\"rsa\":\"ecdsa\");return{certPem:s,keyPem:i,signatureHash:e}}}encryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const i=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});e.fragment=i;e.recordLayerHeader.contentLen=i.length;return e}decryptPacket(e){const t=e.recordLayerHeader;const s=t.protocolVersion.major<<8|t.protocolVersion.minor;const i=this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:s,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return i}verifyData(e){if(this.sessionType===ie.CLIENT)return Yd(this.masterSecret,e);else return Qd(this.masterSecret,e)}signatureData(e,t){return(0,ia.sign)(t,e,this.localPrivateKey)}generateKeySignature(e){const t=this.sessionType===ie.CLIENT?this.localRandom:this.remoteRandom;const s=this.sessionType===ie.SERVER?this.localRandom:this.remoteRandom;const i=this.valueKeySignature(t.serialize(),s.serialize(),this.localKeyPair.publicKey,this.namedCurve);return(0,ia.sign)(e,i,this.localPrivateKey)}parseX509(e,t,s){this.localCert=fn(e);this.localPrivateKey=Ud(t);this.signatureHashAlgorithm=s}valueKeySignature(e,t,s,i){const n=vf({type:un.named_curve_3,curve:i,len:s.length},{type:ra.uint8,curve:ra.uint16be,len:ra.uint8});return Buffer.concat([e,t,n,s])}};var Je=class{static{a(this,\"SrtpContext\")}static findMatchingSRTPProfile(e,t){for(const s of t){if(e.includes(s))return s}}};var Or=a(r=>\"0x\"+r.toString(\"hex\").replace(/(.)(.)/g,\"$1$2 \").split(\" \").filter(e=>e!=void 0&&e.length>0).join(\",0x\"),\"dumpBuffer\");var yn=a(r=>Object.entries({...r}).reduce((e,[t,s])=>{if(typeof s===\"number\"||typeof s===\"string\"){e[t]=s}if(Buffer.isBuffer(s)){e[t]=Or(s)}return e},{}),\"getObjectSummary\");var{decode:If,encode:Pf,types:Cs}=x;var O=class r{static{a(this,\"FragmentedHandshake\")}static{this.spec={msg_type:Cs.uint8,length:Cs.uint24be,message_seq:Cs.uint16be,fragment_offset:Cs.uint24be,fragment_length:Cs.uint24be,fragment:Cs.buffer(e=>e.current.fragment_length)}}constructor(e,t,s,i,n,o){this.msg_type=e;this.length=t;this.message_seq=s;this.fragment_offset=i;this.fragment_length=n;this.fragment=o}get summary(){return yn(this)}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(If(e,r.spec)))}serialize(){return Pf(this,r.spec)}chunk(e){let t=0;const s=this.fragment.length;if(s===0)return[new r(this.msg_type,s,this.message_seq,t,0,this.fragment)];const i=[];if(!e){e=1280-(20+8)-(1+3+2+3+3)}while(t<s){const n=Math.min(e,s-t);const o=Buffer.from(this.fragment.slice(t,t+n));if(o.length<=0){throw new Error(`Zero or less bytes processed while fragmenting handshake message.`)}i.push(new r(this.msg_type,s,this.message_seq,t,o.length,o));t+=o.length}return i}static assemble(e){if(!e?.length){throw new Error(\"cannot reassemble handshake from empty array\")}e=e.sort((s,i)=>s.fragment_offset-i.fragment_offset);const t=Buffer.alloc(e[0].length);for(const s of e){s.fragment.copy(t,s.fragment_offset)}return new r(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){const s=e.find(i=>i.msg_type===t);if(!s)return[];if(!e?.length)return[];return e.filter(i=>{return i.msg_type===s.msg_type&&i.message_seq===s.message_seq&&i.length===s.length})}};var{types:Af}=x;var{uint16be:Tn,uint24be:_f,buffer:Jd,array:Bf,uint8:Ur,string:Lf}=Af;var Df={type:Tn,data:Jd(Tn)};var Hr=Bf(Df,Tn,\"bytes\");var Zd=Jd(_f);var eh=Ur;var th=Lf(Tn);var sh={hash:Ur,signature:Ur};var Es={major:Ur,minor:Ur};var R;(function(r){r[r[\"hello_request_0\"]=0]=\"hello_request_0\";r[r[\"client_hello_1\"]=1]=\"client_hello_1\";r[r[\"server_hello_2\"]=2]=\"server_hello_2\";r[r[\"hello_verify_request_3\"]=3]=\"hello_verify_request_3\";r[r[\"certificate_11\"]=11]=\"certificate_11\";r[r[\"server_key_exchange_12\"]=12]=\"server_key_exchange_12\";r[r[\"certificate_request_13\"]=13]=\"certificate_request_13\";r[r[\"server_hello_done_14\"]=14]=\"server_hello_done_14\";r[r[\"certificate_verify_15\"]=15]=\"certificate_verify_15\";r[r[\"client_key_exchange_16\"]=16]=\"client_key_exchange_16\";r[r[\"finished_20\"]=20]=\"finished_20\"})(R||(R={}));var ih=require(\"node:crypto\");var{decode:Nf,encode:Mf,types:rh}=x;var ne=class r{static{a(this,\"DtlsRandom\")}static{this.spec={gmt_unix_time:rh.uint32be,random_bytes:rh.buffer(28)}}constructor(e=Math.floor(Date.now()/1e3),t=(0,ih.randomBytes)(28)){this.gmt_unix_time=e;this.random_bytes=t}static deSerialize(e){return new r(...Object.values(Nf(e,r.spec)))}static from(e){return new r(...Object.values(e))}serialize(){return Mf(this,r.spec)}};var{decode:Of,encode:Uf,types:pe}=x;var Rs=class r{static{a(this,\"ClientHello\")}static{this.spec={clientVersion:{major:pe.uint8,minor:pe.uint8},random:ne.spec,sessionId:pe.buffer(pe.uint8),cookie:pe.buffer(pe.uint8),cipherSuites:pe.array(pe.uint16be,pe.uint16be,\"bytes\"),compressionMethods:pe.array(pe.uint8,pe.uint8,\"bytes\"),extensions:Hr}}constructor(e,t,s,i,n,o,c){this.clientVersion=e;this.random=t;this.sessionId=s;this.cookie=i;this.cipherSuites=n;this.compressionMethods=o;this.extensions=c;this.msgType=R.client_hello_1;this.messageSeq=0}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(Of(e,r.spec)))}serialize(){return Uf(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var oh=require(\"node:timers/promises\");var{decode:Hf,encode:zf,types:wn}=x;var bn=class r{static{a(this,\"MACHeader\")}static{this.spec={epoch:wn.uint16be,sequenceNumber:wn.uint48be,contentType:wn.uint8,protocolVersion:Es,contentLen:wn.uint16be}}constructor(e,t,s,i,n){this.epoch=e;this.sequenceNumber=t;this.contentType=s;this.protocolVersion=i;this.contentLen=n}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(Hf(e,r.spec)))}serialize(){return zf(this,r.spec)}};var xs=class r{static{a(this,\"DtlsPlaintext\")}constructor(e,t){this.recordLayerHeader=e;this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:Or(this.fragment)}}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){if(e.length<13){throw new Error(\"Invalid DTLS record: buffer is too short\")}const t=e.readUInt8(0);const s=e.readUInt8(1);const i=e.readUInt8(2);const n=e.readUInt16BE(3);const o=e.slice(5,11).readUIntBE(0,6);const c=e.readUInt16BE(11);if(e.length<13+c){throw new Error(\"Invalid DTLS record: fragment length exceeds buffer\")}const d=e.slice(13,13+c);const h=new r({contentType:t,protocolVersion:{major:s,minor:i},epoch:n,sequenceNumber:o,contentLen:c},d);return h}serialize(){const e=this.fragment.length;const t=13+e;const s=Buffer.alloc(t);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);return s}computeMACHeader(){return new bn(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}};var Cn=a(r=>e=>{r.lastFlight=e;return e.flatMap(t=>{t.messageSeq=r.sequenceNumber++;const s=t.toFragment();const i=s.chunk();return i})},\"createFragments\");var Ne=a(r=>(e,t)=>{return e.map(s=>{const i=new xs({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment);return i})},\"createPlaintext\");var H;(function(r){r[r[\"changeCipherSpec\"]=20]=\"changeCipherSpec\";r[r[\"alert\"]=21]=\"alert\";r[r[\"handshake\"]=22]=\"handshake\";r[r[\"applicationData\"]=23]=\"applicationData\"})(H||(H={}));var zr;(function(r){r[r[\"CloseNotify\"]=0]=\"CloseNotify\";r[r[\"UnexpectedMessage\"]=10]=\"UnexpectedMessage\";r[r[\"BadRecordMac\"]=20]=\"BadRecordMac\";r[r[\"DecryptionFailed\"]=21]=\"DecryptionFailed\";r[r[\"RecordOverflow\"]=22]=\"RecordOverflow\";r[r[\"DecompressionFailure\"]=30]=\"DecompressionFailure\";r[r[\"HandshakeFailure\"]=40]=\"HandshakeFailure\";r[r[\"NoCertificate\"]=41]=\"NoCertificate\";r[r[\"BadCertificate\"]=42]=\"BadCertificate\";r[r[\"UnsupportedCertificate\"]=43]=\"UnsupportedCertificate\";r[r[\"CertificateRevoked\"]=44]=\"CertificateRevoked\";r[r[\"CertificateExpired\"]=45]=\"CertificateExpired\";r[r[\"CertificateUnknown\"]=46]=\"CertificateUnknown\";r[r[\"IllegalParameter\"]=47]=\"IllegalParameter\";r[r[\"UnknownCa\"]=48]=\"UnknownCa\";r[r[\"AccessDenied\"]=49]=\"AccessDenied\";r[r[\"DecodeError\"]=50]=\"DecodeError\";r[r[\"DecryptError\"]=51]=\"DecryptError\";r[r[\"ExportRestriction\"]=60]=\"ExportRestriction\";r[r[\"ProtocolVersion\"]=70]=\"ProtocolVersion\";r[r[\"InsufficientSecurity\"]=71]=\"InsufficientSecurity\";r[r[\"InternalError\"]=80]=\"InternalError\";r[r[\"UserCanceled\"]=90]=\"UserCanceled\";r[r[\"NoRenegotiation\"]=100]=\"NoRenegotiation\";r[r[\"UnsupportedExtension\"]=110]=\"UnsupportedExtension\"})(zr||(zr={}));var qf=b(\"webrtc/dtls/flight/flight:warn\");var nh=b(\"webrtc/dtls/flight/flight:err\");var me=class r{static{a(this,\"Flight\")}static{this.RetransmitCount=10}constructor(e,t,s,i){this.transport=e;this.dtls=t;this.flight=s;this.nextFlight=i;this.state=\"PREPARING\";this.send=n=>Promise.all(n.map(o=>this.transport.send(o)))}createPacket(e){const t=Cn(this.dtls)(e);this.dtls.bufferHandshakeCache(t,true,this.flight);const s=Ne(this.dtls)(t.map(i=>({type:H.handshake,fragment:i.serialize()})),++this.dtls.recordSequenceNumber);return s}async transmit(e){const t=this.transport.closing.signal;let s=0;for(;s<=r.RetransmitCount;s++){if(t.aborted)return;this.setState(\"SENDING\");this.send(e).catch(i=>{nh(\"fail to send\",i)});this.setState(\"WAITING\");if(this.nextFlight===void 0){this.setState(\"FINISHED\");break}try{await(0,oh.setTimeout)(1e3*((s+1)/2),void 0,{signal:t})}catch{return}if(this.dtls.flight>=this.nextFlight){this.setState(\"FINISHED\");break}else{qf(this.dtls.sessionId,\"retransmit\",s,this.dtls.flight)}}if(s>r.RetransmitCount){nh(this.dtls.sessionId,\"retransmit failed\",s);throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}}setState(e){this.state=e}};var En=class extends me{static{a(this,\"Flight1\")}constructor(e,t,s){super(e,t,1,3);this.cipher=s}async exec(e){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;const t=new Rs({major:255-1,minor:255-2},new ne,Buffer.from([]),Buffer.from([]),Ld,[0],e);this.dtls.version=t.clientVersion;this.cipher.localRandom=ne.from(t.random);const s=this.createPacket([t]);const i=Buffer.concat(s.map(n=>n.serialize()));await this.transmit([i])}};var Ff=b(\"webrtc/dtls/flight/client/flight3:log\");var Rn=class extends me{static{a(this,\"Flight3\")}constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3;this.dtls.handshakeCache=[];const[t]=this.dtls.lastFlight;Ff(\"dtls version\",t.clientVersion);t.cookie=e.cookie;this.dtls.cookie=e.cookie;const s=this.createPacket([t]);const i=Buffer.concat(s.map(n=>n.serialize()));await this.transmit([i])}};var xn={NULL:0,ECDHE:1};var qr={NULL:0,RSA:1,ECDSA:2,PSK:3};var Fr={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5};var Dt=class{static{a(this,\"KeyExchange\")}constructor(){this.id=0}toString(){return this.name}};function ah(){const r=new Dt;r.id=Fr.RSA;r.name=\"RSA\";r.keyType=qr.RSA;return r}a(ah,\"createRSAKeyExchange\");function ch(){const r=new Dt;r.id=Fr.ECDHE_RSA;r.name=\"ECDHE_RSA\";r.signType=xn.ECDHE;r.keyType=qr.RSA;return r}a(ch,\"createECDHERSAKeyExchange\");function dh(){const r=new Dt;r.id=Fr.ECDHE_ECDSA;r.name=\"ECDHE_ECDSA\";r.signType=xn.ECDHE;r.keyType=qr.ECDSA;return r}a(dh,\"createECDHEECDSAKeyExchange\");function hh(){const r=new Dt;r.id=Fr.PSK;r.name=\"PSK\";r.signType=xn.NULL;r.keyType=qr.PSK;return r}a(hh,\"createPSKKeyExchange\");function uh(){const r=new Dt;r.id=Fr.ECDHE_PSK;r.name=\"ECDHE_PSK\";r.signType=xn.ECDHE;r.keyType=qr.PSK;return r}a(uh,\"createECDHEPSKKeyExchange\");var kn=require(\"node:crypto\");var Kf=b(\"webrtc/dtls/cipher/suites/aead:err\");var Kr=class extends Mr{static{a(this,\"AEADCipher\")}constructor(){super();this.keyLength=0;this.nonceLength=0;this.ivLength=0;this.authTagLength=0;this.nonceImplicitLength=0;this.nonceExplicitLength=0}get summary(){return yn(this)}init(e,t,s){const i=Xd(e,s,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=i.clientWriteKey;this.serverWriteKey=i.serverWriteKey;this.clientNonce=i.clientNonce;this.serverNonce=i.serverNonce}encrypt(e,t,s){const i=e===ie.CLIENT;const n=i?this.clientNonce:this.serverNonce;const o=i?this.clientWriteKey:this.serverWriteKey;if(!n||!o)throw new Error;n.writeUInt16BE(s.epoch,this.nonceImplicitLength);n.writeUIntBE(s.sequenceNumber,this.nonceImplicitLength+2,6);const c=n.slice(this.nonceImplicitLength);const d=this.encodeAdditionalBuffer(s,t.length);const h=(0,kn.createCipheriv)(this.blockAlgorithm,o,n,{authTagLength:this.authTagLength});h.setAAD(d,{plaintextLength:t.length});const l=h.update(t);const u=h.final();const g=h.getAuthTag();return Buffer.concat([c,l,u,g])}encodeAdditionalBuffer(e,t){const s=Buffer.alloc(13);s.writeUInt16BE(e.epoch,0);s.writeUintBE(e.sequenceNumber,2,6);s.writeUInt8(e.type,8);s.writeUInt16BE(e.version,9);s.writeUInt16BE(t,11);return s}decrypt(e,t,s){const i=e===ie.CLIENT;const n=i?this.serverNonce:this.clientNonce;const o=i?this.serverWriteKey:this.clientWriteKey;if(!n||!o)throw new Error;const c=t.subarray(0,this.nonceExplicitLength);c.copy(n,this.nonceImplicitLength);const d=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength);const h=t.subarray(t.length-this.authTagLength);const l=this.encodeAdditionalBuffer(s,d.length);const u=(0,kn.createDecipheriv)(this.blockAlgorithm,o,n,{authTagLength:this.authTagLength});u.setAuthTag(h);u.setAAD(l,{plaintextLength:d.length});const g=u.update(d);try{const S=u.final();return S.length>0?Buffer.concat([g,S]):g}catch(S){Kf(\"decrypt failed\",S,e,Or(t),s,this.summary);throw S}}};var G={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};var Gr={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var jr={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var lh=ah();var fh=ch();var ph=dh();var mh=hh();var gh=uh();function vn(r){switch(r){case G.TLS_RSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_RSA_WITH_AES_128_GCM_SHA256,\"TLS_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",lh,Gr);case G.TLS_RSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_RSA_WITH_AES_256_GCM_SHA384,\"TLS_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",lh,jr,\"sha384\");case G.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",fh,Gr);case G.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",fh,jr,\"sha384\");case G.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",ph,Gr);case G.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",ph,jr,\"sha384\");case G.TLS_PSK_WITH_AES_128_GCM_SHA256:return Me(G.TLS_PSK_WITH_AES_128_GCM_SHA256,\"TLS_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",mh,Gr,\"sha256\");case G.TLS_PSK_WITH_AES_256_GCM_SHA384:return Me(G.TLS_PSK_WITH_AES_256_GCM_SHA384,\"TLS_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",mh,jr,\"sha384\");case G.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Me(G.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,\"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256\",\"aes-128-gcm\",gh,Gr,\"sha256\");case G.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Me(G.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,\"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384\",\"aes-256-gcm\",gh,jr,\"sha384\");default:break}return null}a(vn,\"createCipher\");function Me(r,e,t,s,i,n=\"sha256\"){const o=new Kr;o.id=r;o.name=e;o.blockAlgorithm=t;o.kx=s;o.hashAlgorithm=n;o.keyLength=i.K_LEN;o.nonceLength=i.N_MAX;o.nonceImplicitLength=4;o.nonceExplicitLength=8;o.ivLength=o.nonceImplicitLength;o.authTagLength=16;return o}a(Me,\"createAEADCipher\");function In(r){switch(r){case Ve.secp256r1_23:{const{privateKey:e,publicKey:t}=Hd();return{curve:r,privateKey:e,publicKey:t}}case Ve.x25519_29:{const{privateKey:e,publicKey:t}=Kd();return{curve:r,privateKey:e,publicKey:t}}default:throw new Error}}a(In,\"generateKeyPair\");var Oe=class{static{a(this,\"ExtendedMasterSecret\")}static{this.type=23}};var{decode:Gf,encode:jf,types:Sh}=x;var Ue=class r{static{a(this,\"RenegotiationIndication\")}static{this.type=65281}static{this.spec={type:Sh.uint16be,data:Sh.uint8}}constructor(e={}){this.type=r.type;this.data=0;Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(Gf(e,r.spec))}serialize(){return jf(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:Wf,encode:$f,types:na}=x;var ge=class r{static{a(this,\"UseSRTP\")}static{this.type=14}static{this.spec={type:na.uint16be,data:na.buffer(na.uint16be)}}constructor(e={}){this.type=r.type;this.data=Buffer.from([]);this.profiles=[];this.mki=Buffer.from([0]);Object.assign(this,e)}static create(e,t){const s=new r({profiles:e,mki:t});return s}static deSerialize(e){const t=new r(Wf(e,r.spec));const s=t.data.readUInt16BE();const i=new Array(s/2);for(let n=0;n<i.length;n++){i[n]=t.data.readUInt16BE(n*2+2)}t.profiles=i;t.mki=t.data.slice(s+2);return t}serialize(){const e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);const t=Buffer.concat([e,...this.profiles.map(s=>{const i=Buffer.alloc(2);i.writeUInt16BE(s);return i}),this.mki]);this.data=t;return $f(this,r.spec)}static fromData(e){const t=Buffer.alloc(4);t.writeUInt16BE(r.type);t.writeUInt16BE(e.length,2);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}};var{decode:Vf,encode:Yf,types:yh}=x;var Ze=class r{static{a(this,\"Certificate\")}static{this.spec={certificateList:yh.array(Zd,yh.uint24be,\"bytes\")}}constructor(e){this.certificateList=e;this.msgType=R.certificate_11}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(...Object.values(Vf(e,r.spec)))}serialize(){return Yf(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:Qf,encode:Xf,types:Jf}=x;var ks=class r{static{a(this,\"ChangeCipherSpec\")}static{this.spec={type:Jf.uint8}}constructor(e=1){this.type=e}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(Qf(e,r.spec)))}serialize(){return Xf(this,r.spec)}};var{decode:Zf,encode:ep,types:oa}=x;var vs=class r{static{a(this,\"CertificateVerify\")}static{this.spec={algorithm:oa.uint16be,signature:oa.buffer(oa.uint16be)}}constructor(e,t){this.algorithm=e;this.signature=t;this.msgType=R.certificate_verify_15}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){const t=Zf(e,r.spec);return new r(...Object.values(t))}serialize(){return ep(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:tp,encode:sp,types:Th}=x;var Is=class r{static{a(this,\"ClientKeyExchange\")}static{this.spec={publicKey:Th.buffer(Th.uint8)}}constructor(e){this.publicKey=e;this.msgType=R.client_key_exchange_16}static createEmpty(){return new r(void 0)}static deSerialize(e){const t=tp(e,r.spec);return new r(...Object.values(t))}serialize(){return sp(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Nt=class r{static{a(this,\"Finished\")}constructor(e){this.verifyData=e;this.msgType=R.finished_20}static createEmpty(){return new r(void 0)}static deSerialize(e){return new r(e)}serialize(){return this.verifyData}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:rp,encode:ip,types:Ps}=x;var As=class r{static{a(this,\"ServerCertificateRequest\")}static{this.spec={certificateTypes:Ps.array(eh,Ps.uint8,\"bytes\"),signatures:Ps.array(sh,Ps.uint16be,\"bytes\"),authorities:Ps.array(th,Ps.uint16be,\"bytes\")}}constructor(e,t,s){this.certificateTypes=e;this.signatures=t;this.authorities=s;this.msgType=R.certificate_request_13}static createEmpty(){return new r(void 0,void 0,void 0)}static deSerialize(e){return new r(...Object.values(rp(e,r.spec)))}serialize(){return ip(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:wh,encode:bh,types:Pn}=x;var _s=class r{static{a(this,\"ServerHello\")}static{this.spec={serverVersion:Es,random:ne.spec,sessionId:Pn.buffer(Pn.uint8),cipherSuite:Pn.uint16be,compressionMethod:Pn.uint8}}constructor(e,t,s,i,n,o){this.serverVersion=e;this.random=t;this.sessionId=s;this.cipherSuite=i;this.compressionMethod=n;this.extensions=o;this.msgType=R.server_hello_2}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=wh(e,r.spec);const s=new r(...Object.values(t));const i=s.serialize();if(i.length<e.length){return new r(...Object.values(wh(e,{...r.spec,extensions:Hr})))}return s}serialize(){return this.extensions===void 0?bh(this,r.spec):bh(this,{...r.spec,extensions:Hr})}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:np,encode:op}=x;var Bs=class r{static{a(this,\"ServerHelloDone\")}constructor(){this.msgType=R.server_hello_done_14}static{this.spec={}}static createEmpty(){return new r}static deSerialize(e){return new r(...Object.values(np(e,r.spec)))}serialize(){return op(this,r.spec)}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{encode:ap}=x;function Ch(r,e){return ap(r,e)}a(Ch,\"encodeBuffer\");var{decode:cp,types:ut}=x;var Ls=class r{static{a(this,\"ServerKeyExchange\")}static{this.spec={ellipticCurveType:ut.uint8,namedCurve:ut.uint16be,publicKeyLength:ut.uint8,publicKey:ut.buffer(e=>e.current.publicKeyLength),hashAlgorithm:ut.uint8,signatureAlgorithm:ut.uint8,signatureLength:ut.uint16be,signature:ut.buffer(e=>e.current.signatureLength)}}constructor(e,t,s,i,n,o,c,d){this.ellipticCurveType=e;this.namedCurve=t;this.publicKeyLength=s;this.publicKey=i;this.hashAlgorithm=n;this.signatureAlgorithm=o;this.signatureLength=c;this.signature=d;this.msgType=R.server_key_exchange_12}static createEmpty(){return new r(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=cp(e,r.spec);return new r(...Object.values(t))}serialize(){const e=Ch(this,r.spec);return e}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var X=b(\"webrtc/dtls/flight/client/flight5:log\");var An=class extends me{static{a(this,\"Flight5\")}constructor(e,t,s,i){super(e,t,5,7);this.cipher=s;this.srtp=i}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,4);const t=(()=>{switch(e.msg_type){case R.server_hello_2:return _s.deSerialize(e.fragment);case R.certificate_11:return Ze.deSerialize(e.fragment);case R.server_key_exchange_12:return Ls.deSerialize(e.fragment);case R.certificate_request_13:return As.deSerialize(e.fragment);case R.server_hello_done_14:return Bs.deSerialize(e.fragment)}})();if(t){Ds[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}}async exec(){if(this.dtls.flight===5){X(this.dtls.sessionId,\"flight5 twice\");this.send(this.dtls.lastMessage).catch(s=>X(\"send failed\",s));return}this.dtls.flight=5;const e=this.dtls.requestedCertificateTypes.length>0;X(this.dtls.sessionId,\"send flight5\",e);const t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(s=>s);this.dtls.lastMessage=t;await this.transmit(t)}sendCertificate(){const e=new Ze([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;const e=new Is(this.cipher.localKeyPair.publicKey);const t=this.createPacket([e]);const s=Buffer.concat(t.map(d=>d.serialize()));const i=this.cipher.localKeyPair;const n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error(\"not exist\");const o=mn(n.publicKey,i.privateKey,i.curve);X(this.dtls.sessionId,\"extendedMasterSecret\",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);const c=Buffer.concat(this.dtls.sortedHandshakeCache.map(d=>d.serialize()));this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?Sn(o,c):gn(o,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize());this.cipher.cipher=vn(this.cipher.cipherSuite);this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize());X(this.dtls.sessionId,\"cipher\",this.cipher.cipher.summary);return s}sendCertificateVerify(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(c=>c.serialize()));const t=this.cipher.signatureData(e,\"sha256\");const s=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case ce.ecdsa_3:return ta.ecdsa_secp256r1_sha256;case ce.rsa_1:return ta.rsa_pkcs1_sha256}})();if(!s)throw new Error;X(this.dtls.sessionId,\"signatureScheme\",this.cipher.signatureHashAlgorithm?.signature,s);const i=new vs(s,t);const n=this.createPacket([i]);const o=Buffer.concat(n.map(c=>c.serialize()));return o}sendChangeCipherSpec(){const e=ks.createEmpty().serialize();const t=Ne(this.dtls)([{type:H.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Nt(t);this.dtls.epoch=1;const[i]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const n=this.cipher.encryptPacket(i).serialize();X(this.dtls.sessionId,\"finished\",this.cipher.cipher.summary);return n}};var Ds={};Ds[R.server_hello_2]=({cipher:r,srtp:e,dtls:t})=>s=>{X(t.sessionId,\"serverHello\",s.cipherSuite);r.remoteRandom=ne.from(s.random);r.cipherSuite=s.cipherSuite;X(t.sessionId,\"selected cipherSuite\",r.cipherSuite);if(s.extensions){s.extensions.forEach(i=>{switch(i.type){case ge.type:{const n=ge.fromData(i.data);const o=Je.findMatchingSRTPProfile(n.profiles,t.options.srtpProfiles||[]);X(t.sessionId,\"selected srtp profile\",o);if(o==void 0)return;e.srtpProfile=o}break;case Oe.type:t.remoteExtendedMasterSecret=true;break;case Ue.type:X(t.sessionId,\"RenegotiationIndication\");break}})}};Ds[R.certificate_11]=({cipher:r,dtls:e})=>t=>{X(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Ds[R.server_key_exchange_12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;X(e.sessionId,\"ServerKeyExchange\",t);X(e.sessionId,\"selected curve\",t.namedCurve);r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey};r.localKeyPair=In(t.namedCurve)};Ds[R.certificate_request_13]=({dtls:r})=>e=>{X(r.sessionId,\"certificate_request\",e);r.requestedCertificateTypes=e.certificateTypes;r.requestedSignatureAlgorithms=e.signatures};Ds[R.server_hello_done_14]=({dtls:r})=>e=>{X(r.sessionId,\"server_hello_done\",e)};var{decode:dp,encode:hp,types:Eh}=x;var Ns=class r{static{a(this,\"ServerHelloVerifyRequest\")}static{this.spec={serverVersion:Es,cookie:Eh.buffer(Eh.uint8)}}constructor(e,t){this.serverVersion=e;this.cookie=t;this.msgType=R.hello_verify_request_3}static createEmpty(){return new r(void 0,void 0)}static deSerialize(e){return new r(...Object.values(dp(e,r.spec)))}serialize(){return hp(this,r.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){const e=this.serialize();return new O(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Ah=require(\"node:timers/promises\");var up=b(\"webrtc/dtls/context/dtls:log\");var Wr=class{static{a(this,\"DtlsContext\")}constructor(e,t){this.options=e;this.sessionType=t;this.version={major:255-1,minor:255-2};this.lastFlight=[];this.lastMessage=[];this.recordSequenceNumber=0;this.sequenceNumber=0;this.epoch=0;this.flight=0;this.handshakeCache={};this.requestedCertificateTypes=[];this.requestedSignatureAlgorithms=[];this.remoteExtendedMasterSecret=false;this.checkHandshakesExist=s=>!s.find(i=>this.sortedHandshakeCache.find(n=>n.msg_type===i)==void 0)}get sessionId(){return this.cookie?this.cookie.toString(\"hex\").slice(0,10):\"\"}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((t,s)=>t.message_seq-s.message_seq))}bufferHandshakeCache(e,t,s){if(!this.handshakeCache[s]){this.handshakeCache[s]={data:[],isLocal:t,flight:s}}const i=e.filter(n=>{const o=this.handshakeCache[s].data.find(c=>c.msg_type===n.msg_type);if(o){up(this.sessionId,\"exist\",o.summary,t,s);return false}return true});this.handshakeCache[s].data=[...this.handshakeCache[s].data,...i]}};var _n=class{static{a(this,\"TransportContext\")}constructor(e){this.socket=e;this.closing=new AbortController;this.send=(t,s)=>{return this.socket.send(t,s)}}close(){this.closing.abort()}};var{decode:Rh,encode:lp,types:Bn}=x;var Mt=class r{static{a(this,\"EllipticCurves\")}static{this.type=10}static{this.spec={type:Bn.uint16be,data:Bn.array(Bn.uint16be,Bn.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){return new r}static fromData(e){return new r({type:r.type,data:Rh(e,r.spec.data)})}static deSerialize(e){return new r(Rh(e,r.spec))}serialize(){return lp(this,r.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:fp,encode:pp,types:$r}=x;var Ot=class r{static{a(this,\"Signature\")}static{this.type=13}static{this.spec={type:$r.uint16be,data:$r.array({hash:$r.uint8,signature:$r.uint8},$r.uint16be,\"bytes\")}}constructor(e={}){this.type=r.type;this.data=[];Object.assign(this,e)}static createEmpty(){const e=new r;return e}static deSerialize(e){return new r(fp(e,r.spec))}serialize(){return pp(this,r.spec)}static fromData(e){const t=Buffer.alloc(2);t.writeUInt16BE(r.type);return r.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:mp,encode:gp,types:xh}=x;var Vr=class r{static{a(this,\"Alert\")}static{this.spec={level:xh.uint8,description:xh.uint8}}constructor(e,t){this.level=e;this.description=t}static deSerialize(e){return new r(...Object.values(mp(e,r.spec)))}serialize(){return gp(this,r.spec)}};var kh=b(\"webrtc/dtls/record/receive:log\");var aa=b(\"webrtc/dtls/record/receive:err\");var vh=a(r=>{let e=0;const t=[];while(r.length>e){const s=r.readUInt16BE(e+11);if(r.length<e+(12+s)){break}const i=xs.deSerialize(r.subarray(e));t.push(i);e+=13+s}return t},\"parsePacket\");var Ih=a((r,e)=>t=>{const s=t.recordLayerHeader.contentType;switch(s){case H.changeCipherSpec:{kh(r.sessionId,\"change cipher spec\");return[{type:H.changeCipherSpec,data:void 0}]}case H.handshake:{let i=t.fragment;try{if(t.recordLayerHeader.epoch>0){kh(r.sessionId,\"decrypt handshake\");i=e.decryptPacket(t)}}catch(n){aa(r.sessionId,\"decrypt failed\",n);throw n}try{let n=0;const o=[];while(i.length>n){const c=O.deSerialize(i.subarray(n));o.push({type:H.handshake,data:c});n+=c.fragment_length+12}return o}catch(n){aa(r.sessionId,\"decSerialize failed\",n,i);throw n}}case H.applicationData:{return[{type:H.applicationData,data:e.decryptPacket(t)}]}case H.alert:{let i=Vr.deSerialize(t.fragment);if(zr[i.description]==void 0){const n=e.decryptPacket(t);i=Vr.deSerialize(n)}aa(r.sessionId,\"ContentType.alert\",i,zr[i.description],\"flight\",r.flight,\"lastFlight\",r.lastFlight);if(i.level>1){throw new Error(\"alert fatal error\")}return[{type:H.alert,data:void 0}]}default:{return[{type:H.alert,data:void 0}]}}},\"parsePlainText\");var{decode:Sp,types:Ln}=x;var ca=b(\"webrtc/dtls/socket:log\");var Ph=b(\"webrtc/dtls/socket:err\");var Ut=class{static{a(this,\"DtlsSocket\")}constructor(e,t){this.options=e;this.sessionType=t;this.onConnect=new w;this.onData=new w;this.onError=new w;this.onClose=new w;this.srtp=new Je;this.connected=false;this.extensions=[];this.bufferFragmentedHandshakes=[];this.udpOnMessage=s=>{const i=vh(s);for(const n of i){try{const o=Ih(this.dtls,this.cipher)(n);for(const c of o){switch(c.type){case H.handshake:{const d=c.data;const h=this.handleFragmentHandshake([d]);const l=Object.values(h.reduce((u,g)=>{if(!u[g.msg_type])u[g.msg_type]=[];u[g.msg_type].push(g);return u},{})).map(u=>O.assemble(u)).sort((u,g)=>u.msg_type-g.msg_type);this.onHandleHandshakes(l).catch(u=>{Ph(this.dtls.sessionId,\"onHandleHandshakes error\",u);this.onError.execute(u)})}break;case H.applicationData:{this.onData.execute(c.data)}break;case H.alert:this.onClose.execute();break}}}catch(o){Ph(this.dtls.sessionId,\"catch udpOnMessage error\",o)}}};this.waitForReady=async s=>{for(let i=0;i<10;i++){if(s())return;await(0,Ah.setTimeout)(100*i)}throw new Error(\"waitForReady timeout\")};this.send=async(s,i)=>{const n=Ne(this.dtls)([{type:H.applicationData,fragment:s}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(n).serialize(),i)};this.dtls=new Wr(this.options,this.sessionType);this.cipher=new Xe(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.transport=new _n(this.options.transport);this.setupExtensions();this.transport.socket.onData=this.udpOnMessage}renegotiation(){ca(\"renegotiation\",this.sessionType);this.connected=false;this.cipher=new Xe(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.dtls=new Wr(this.options,this.sessionType);this.srtp=new Je;this.extensions=[];this.bufferFragmentedHandshakes=[]}setupExtensions(){ca(this.dtls.sessionId,\"support srtpProfiles\",this.options.srtpProfiles);if(this.options.srtpProfiles&&this.options.srtpProfiles.length>0){const e=ge.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{const e=Mt.createEmpty();e.data=hn;this.extensions.push(e.extension)}{const e=Ot.createEmpty();e.data=ln;this.extensions.push(e.extension)}if(this.options.extendedMasterSecret){this.extensions.push({type:Oe.type,data:Buffer.alloc(0)})}{const e=Ue.createEmpty();this.extensions.push(e.extension)}}handleFragmentHandshake(e){let t=e.filter(s=>{if(s.fragment_length!==s.length){this.bufferFragmentedHandshakes.push(s);return false}return true});if(this.bufferFragmentedHandshakes.length>1){const[s]=this.bufferFragmentedHandshakes.slice(-1);if(s.fragment_offset+s.fragment_length===s.length){t=[...this.bufferFragmentedHandshakes,...t];this.bufferFragmentedHandshakes=[]}}return t}close(){this.transport.close();K(()=>this.transport.socket.close(),e=>ca(\"close failed\",e))}extractSessionKeys(e,t){const s=this.exportKeyingMaterial(\"EXTRACTOR-dtls_srtp\",e*2+t*2);const{clientKey:i,serverKey:n,clientSalt:o,serverSalt:c}=Sp(s,{clientKey:Ln.buffer(e),serverKey:Ln.buffer(e),clientSalt:Ln.buffer(t),serverSalt:Ln.buffer(t)});if(this.sessionType===ie.CLIENT){return{localKey:i,localSalt:o,remoteKey:n,remoteSalt:c}}else{return{localKey:n,localSalt:c,remoteKey:i,remoteSalt:o}}}exportKeyingMaterial(e,t){return Wd(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===ie.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}};var da=b(\"webrtc/dtls/client:log\");var Ms=class extends Ut{static{a(this,\"DtlsClient\")}constructor(e){super(e,ie.CLIENT);this.handleHandshakes=async t=>{da(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case R.hello_verify_request_3:{const i=Ns.deSerialize(s.fragment);await new Rn(this.transport,this.dtls).exec(i)}break;case R.server_hello_2:{if(this.connected)return;this.flight5=new An(this.transport,this.dtls,this.cipher,this.srtp);this.flight5.handleHandshake(s)}break;case R.certificate_11:case R.server_key_exchange_12:case R.certificate_request_13:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s)}break;case R.server_hello_done_14:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(s);const i=[11,12,this.options.certificateRequest&&13].filter(n=>typeof n===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(i));await this.flight5?.exec()}break;case R.finished_20:{this.dtls.flight=7;this.connected=true;this.onConnect.execute();da(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;da(this.dtls.sessionId,\"start client\")}async connect(){await new En(this.transport,this.dtls,this.cipher).exec(this.extensions)}};var _h=require(\"node:crypto\");var ke=b(\"webrtc/dtls/flight/server/flight2:log\");var Bh=a((r,e,t,s)=>i=>{ke(\"dtls version\",i.clientVersion);e.flight=2;e.recordSequenceNumber=0;e.sequenceNumber=0;i.extensions.forEach(u=>{switch(u.type){case Mt.type:{const g=Mt.fromData(u.data).data;ke(e.sessionId,\"curves\",g);const S=g.filter(p=>hn.includes(p))[0];t.namedCurve=S;ke(e.sessionId,\"curve selected\",t.namedCurve)}break;case Ot.type:{if(!t.signatureHashAlgorithm)throw new Error(\"need to set certificate\");const g=Ot.fromData(u.data).data;ke(e.sessionId,\"hash,signature\",g);const S=g.find(f=>f.signature===t.signatureHashAlgorithm?.signature)?.signature;const p=g.find(f=>f.hash===t.signatureHashAlgorithm?.hash)?.hash;if(S==void 0||p==void 0){throw new Error(\"invalid signatureHash\")}}break;case ge.type:{if(!e.options?.srtpProfiles)return;if(e.options.srtpProfiles.length===0)return;const g=ge.fromData(u.data);ke(e.sessionId,\"srtp profiles\",g.profiles);const S=Je.findMatchingSRTPProfile(g.profiles,e.options?.srtpProfiles);if(!S){throw new Error}s.srtpProfile=S;ke(e.sessionId,\"srtp profile selected\",s.srtpProfile)}break;case Oe.type:{e.remoteExtendedMasterSecret=true}break;case Ue.type:{ke(e.sessionId,\"RenegotiationIndication\",u.data)}break;case 43:{const g=u.data.subarray(1);const S=[...g].map(p=>p.toString(10));ke(\"dtls supported version\",S)}break}});t.localRandom=new ne;t.remoteRandom=ne.from(i.random);const n=i.cipherSuites;ke(e.sessionId,\"cipher suites\",n);const o=(()=>{switch(t.signatureHashAlgorithm?.signature){case ce.ecdsa_3:return dn.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case ce.rsa_1:return dn.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!n.includes(o)){throw new Error(\"dtls cipher suite negotiation failed\")}t.cipherSuite=o;ke(e.sessionId,\"selected cipherSuite\",t.cipherSuite);t.localKeyPair=In(t.namedCurve);e.cookie||=(0,_h.randomBytes)(20);const c=new Ns({major:255-1,minor:255-2},e.cookie);const d=Cn(e)([c]);const h=Ne(e)(d.map(u=>({type:H.handshake,fragment:u.serialize()})),++e.recordSequenceNumber);const l=h.map(u=>u.serialize());for(const u of l){r.send(u).catch(g=>ke(\"send failed\",g))}},\"flight2\");var ha=b(\"webrtc/dtls/flight/server/flight4:log\");var Dn=class extends me{static{a(this,\"Flight4\")}constructor(e,t,s,i){super(e,t,4,6);this.cipher=s;this.srtp=i}async exec(e,t=false){if(this.dtls.flight===4){ha(this.dtls.sessionId,\"flight4 twice\");this.send(this.dtls.lastMessage).catch(i=>ha(\"send failed\",i));return}this.dtls.flight=4;this.dtls.sequenceNumber=1;this.dtls.bufferHandshakeCache([e],false,4);const s=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(i=>i);this.dtls.lastMessage=s;await this.transmit(s)}sendServerHello(){const e=[];if(this.srtp.srtpProfile){e.push(ge.create([this.srtp.srtpProfile],Buffer.from([0])).extension)}if(this.dtls.options.extendedMasterSecret){e.push({type:Oe.type,data:Buffer.alloc(0)})}const t=Ue.createEmpty();e.push(t.extension);const s=new _s(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e);const i=this.createPacket([s]);return Buffer.concat(i.map(n=>n.serialize()))}sendCertificate(){const e=new Ze([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerKeyExchange(){const e=this.cipher.generateKeySignature(\"sha256\");if(!this.cipher.signatureHashAlgorithm)throw new Error(\"not exist\");const t=new Ls(un.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e);const s=this.createPacket([t]);return Buffer.concat(s.map(i=>i.serialize()))}sendCertificateRequest(){const e=new As(Dd,ln,[]);ha(this.dtls.sessionId,\"sendCertificateRequest\",e);const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendServerHelloDone(){const e=new Bs;const t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}};var Ht=b(\"webrtc/dtls/flight/server/flight6\");var Nn=class extends me{static{a(this,\"Flight6\")}constructor(e,t,s){super(e,t,6);this.cipher=s}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,5);const t=(()=>{switch(e.msg_type){case R.certificate_11:return Ze.deSerialize(e.fragment);case R.certificate_verify_15:return vs.deSerialize(e.fragment);case R.client_key_exchange_16:return Is.deSerialize(e.fragment);case R.finished_20:return Nt.deSerialize(e.fragment)}})();if(t){const s=Yr[t.msgType];if(!s){return}s({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){Ht(this.dtls.sessionId,\"flight6 twice\");this.send(this.dtls.lastMessage).catch(t=>Ht(\"send failed\",t));return}this.dtls.flight=6;const e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e;await this.transmit(e)}sendChangeCipherSpec(){const e=ks.createEmpty().serialize();const t=Ne(this.dtls)([{type:H.changeCipherSpec,fragment:e}],++this.dtls.recordSequenceNumber);const s=Buffer.concat(t.map(i=>i.serialize()));return s}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize()));const t=this.cipher.verifyData(e);const s=new Nt(t);this.dtls.epoch=1;const[i]=this.createPacket([s]);this.dtls.recordSequenceNumber=0;const n=this.cipher.encryptPacket(i).serialize();return n}};var Yr={};Yr[R.client_key_exchange_16]=({cipher:r,dtls:e})=>t=>{r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey};if(!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error(\"not exist\");const s=mn(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);Ht(e.sessionId,\"extendedMasterSecret\",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);const i=Buffer.concat(e.sortedHandshakeCache.map(n=>n.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?Sn(s,i):gn(s,r.remoteRandom.serialize(),r.localRandom.serialize());r.cipher=vn(r.cipherSuite);r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize());Ht(e.sessionId,\"setup cipher\",r.cipher.summary)};Yr[R.certificate_11]=({cipher:r,dtls:e})=>t=>{Ht(e.sessionId,\"handshake certificate\",t);r.remoteCertificate=t.certificateList[0]};Yr[R.certificate_verify_15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate){throw new Error(\"client certificate missing before certificate verify\")}Ht(e.sessionId,\"certificate_verify\",t.algorithm)};Yr[R.finished_20]=({dtls:r})=>e=>{Ht(r.sessionId,\"finished\",e)};var Os=b(\"webrtc/dtls/server:log\");var Qr=class extends Ut{static{a(this,\"DtlsServer\")}constructor(e){super(e,ie.SERVER);this.handleHandshakes=async t=>{Os(this.dtls.sessionId,\"handleHandshakes\",t.map(s=>s.msg_type));for(const s of t){switch(s.msg_type){case R.client_hello_1:{if(this.connected){this.renegotiation()}const i=Rs.deSerialize(s.fragment);if(i.cookie.length===0){Os(this.dtls.sessionId,\"send flight2\");Bh(this.transport,this.dtls,this.cipher,this.srtp)(i)}else if(this.dtls.cookie&&i.cookie.equals(this.dtls.cookie)){Os(this.dtls.sessionId,\"send flight4\");await new Dn(this.transport,this.dtls,this.cipher,this.srtp).exec(s,this.options.certificateRequest)}else{Os(\"wrong state\",{dtlsCookie:this.dtls.cookie?.toString(\"hex\").slice(10),helloCookie:i.cookie.toString(\"hex\").slice(10)})}}break;case R.certificate_11:case R.certificate_verify_15:case R.client_key_exchange_16:{if(this.connected)return;this.flight6=new Nn(this.transport,this.dtls,this.cipher);this.flight6.handleHandshake(s)}break;case R.finished_20:{await this.waitForReady(()=>!!this.flight6);this.flight6?.handleHandshake(s);const i=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(n=>typeof n===\"number\");await this.waitForReady(()=>this.dtls.checkHandshakesExist(i));await this.flight6?.exec();this.connected=true;this.onConnect.execute();Os(this.dtls.sessionId,\"dtls connected\")}break}}};this.onHandleHandshakes=this.handleHandshakes;Os(this.dtls.sessionId,\"start server\")}};var ua=2;var la=3;var Lh=0;var Us=50;var fa=51;var pa=53;var On=56;var Un=57;var ma=\"0.0.0.0\";var ga=9;var Mn={auto:\"actpass\",client:\"active\",server:\"passive\"};var Sa=Object.keys(Mn).reduce((r,e)=>{const t=Mn[e];r[t]=e;return r},{});var Dh=[\"apt\",\"max-fr\",\"max-fs\",\"maxplaybackrate\",\"minptime\",\"packetization-mode\",\"level-asymmetry-allowed\",\"stereo\",\"useinbandfec\"];var ya=[\"cname\",\"msid\",\"mslabel\",\"label\"];var Ta={SRTP_AES128_CM_HMAC_SHA1_80:ts,SRTP_AEAD_AES_128_GCM:ct};var zt=[\"sendonly\",\"sendrecv\"];var Nh=[\"sendrecv\",\"recvonly\"];var Hs=554869826;var Mh=8;var Oh=1398035790;var et=20;var wa=24;var ba=1;var Ca=2;var Uh=6;var Hh=50;var B;(function(r){r[r[\"REQUEST\"]=0]=\"REQUEST\";r[r[\"INDICATION\"]=16]=\"INDICATION\";r[r[\"RESPONSE\"]=256]=\"RESPONSE\";r[r[\"ERROR\"]=272]=\"ERROR\"})(B||(B={}));var Y;(function(r){r[r[\"BINDING\"]=1]=\"BINDING\";r[r[\"SHARED_SECRET\"]=2]=\"SHARED_SECRET\";r[r[\"ALLOCATE\"]=3]=\"ALLOCATE\";r[r[\"REFRESH\"]=4]=\"REFRESH\";r[r[\"SEND\"]=6]=\"SEND\";r[r[\"DATA\"]=7]=\"DATA\";r[r[\"CREATE_PERMISSION\"]=8]=\"CREATE_PERMISSION\";r[r[\"CHANNEL_BIND\"]=9]=\"CHANNEL_BIND\"})(Y||(Y={}));function zh(r){if(r.length<et){return false}if((r[0]&192)!==0){return false}if(r.readUInt32BE(4)!==Hs){return false}const e=r.readUInt16BE(2);if(e%4!==0){return false}return r.length===et+e}a(zh,\"isStunMessage\");var qh=3e3;function Fh(r){const e=Buffer.alloc(2);e.writeUInt16BE(r.length,0);return Buffer.concat([e,r])}a(Fh,\"encodeTcpFrame\");function Kh(r){const e=[];let t=0;while(r.length-t>=2){const s=r.readUInt16BE(t);if(r.length-t<s+2){break}e.push(r.subarray(t+2,t+2+s));t+=2+s}return{frames:e,rest:r.subarray(t)}}a(Kh,\"splitTcpFrames\");var $n=require(\"node:net\");var ei=require(\"node:crypto\");var zs=require(\"node:net\");function Ea(r){if((0,zs.isIPv4)(r)){const i=Buffer.allocUnsafe(4);const n=r.split(\".\");for(let o=0;o<4;o++){i[o]=Number(n[o])&255}return i}if(!(0,zs.isIPv6)(r)){throw new Error(`Invalid ip address: ${r}`)}const e=r.split(\":\",8);for(let i=0;i<e.length;i++){let n;if((0,zs.isIPv4)(e[i])){n=Ea(e[i]);e[i]=n.subarray(0,2).toString(\"hex\")}if(n&&++i<8){e.splice(i,0,n.subarray(2,4).toString(\"hex\"))}}if(e[0]===\"\"){while(e.length<8)e.unshift(\"0\")}else if(e[e.length-1]===\"\"){while(e.length<8)e.push(\"0\")}else if(e.length<8){let i=0;for(;i<e.length&&e[i]!==\"\";i++);const n=[];for(let o=9-e.length;o>0;o--){n.push(\"0\")}e.splice(i,1,...n)}const t=Buffer.allocUnsafe(16);let s=0;for(const i of e){const n=Number.parseInt(i,16)||0;t[s++]=n>>8&255;t[s++]=n&255}return t}a(Ea,\"ipAddressToBuffer\");function Ra(r){if(r.length===4){return`${r[0]}.${r[1]}.${r[2]}.${r[3]}`}if(r.length!==16){throw new Error(`Invalid ip address buffer length: ${r.length}`)}const e=[];for(let s=0;s<16;s+=2){e.push(r.readUInt16BE(s).toString(16))}let t=e.join(\":\");t=t.replace(/(^|:)0(:0)*:0(:|$)/,\"$1::$3\");t=t.replace(/:{3,4}/,\"::\");return t}a(Ra,\"bufferToIpAddress\");function Gh(r){return(0,zs.isIPv4)(r)}a(Gh,\"isIpV4Address\");function qt(r){const[e]=r;const t=Gh(e)?ba:Ca;const s=Buffer.alloc(4);s.writeUInt8(0,0);s.writeUInt8(t,1);s.writeUInt16BE(r[1],2);return Buffer.concat([s,Ea(e)])}a(qt,\"packAddress\");function yp(r){if(r.length<4){throw new Error(\"STUN error code is less than 4 bytes\")}const e=r.readUInt8(2);const t=r.readUInt8(3);const s=r.slice(4).toString(\"utf8\");return[e*100+t,s]}a(yp,\"unpackErrorCode\");function Ft(r){if(r.length<4){throw new Error(\"STUN address length is less than 4 bytes\")}const e=r.readUInt8(1);const t=r.readUInt16BE(2);const s=r.slice(4);switch(e){case ba:if(s.length!==4){throw new Error(\"STUN address has invalid length for IPv4\")}return[Ra(s),t];case Ca:if(s.length!==16){throw new Error(\"STUN address has invalid length for IPv6\")}return[Ra(s),t];default:throw new Error(\"STUN address has unknown protocol\")}}a(Ft,\"unpackAddress\");var xa=Buffer.alloc(6);xa.writeUInt16BE(Hs>>16,0);xa.writeUInt32BE(Hs,2);function $h(r,e){const t=[...xa,...e];let s=r.slice(0,2);for(let i=2;i<r.length;i++){const n=r[i]^t[i-2];const o=Buffer.alloc(1);o.writeUIntBE(n,0,1);s=Buffer.concat([s,o])}return s}a($h,\"xorAddress\");function Xr(r,e){return Ft($h(r,e))}a(Xr,\"unpackXorAddress\");function Tp(r){const e=Buffer.alloc(4);e.writeUInt16BE(0,0);e.writeUInt8(Math.floor(r[0]/100),2);e.writeUInt8(r[0]%100,3);const t=Buffer.from(r[1],\"utf8\");return Buffer.concat([e,t])}a(Tp,\"packErrorCode\");function wp(r){const e=Buffer.alloc(r.length*2);r.forEach((t,s)=>{e.writeUInt16BE(t,s*2)});return e}a(wp,\"packUnknownAttributes\");function bp(r){if(r.length%2!==0){throw new Error(\"UNKNOWN-ATTRIBUTES must have an even length\")}const e=[];for(let t=0;t<r.length;t+=2){e.push(r.readUInt16BE(t))}return e}a(bp,\"unpackUnknownAttributes\");function Jr(r,e){return $h(qt(r),e)}a(Jr,\"packXorAddress\");var qs=a(r=>{const e=Buffer.alloc(4);e.writeUInt32BE(r,0);return e},\"packUnsigned\");var Fs=a(r=>r.readUInt32BE(0),\"unpackUnsigned\");var Cp=a(r=>{const e=Buffer.alloc(4);e.writeUInt16BE(r,0);return e},\"packUnsignedShort\");var Ep=a(r=>r.readUInt16BE(0),\"unpackUnsignedShort\");var jh=a(r=>{const e=Buffer.allocUnsafe(8);e.writeBigUInt64BE(r,0);return e},\"packUnsigned64\");var Wh=a(r=>r.readBigUInt64BE(0),\"unpackUnsigned64\");var zn=a(r=>Buffer.from(r,\"utf8\"),\"packString\");var Hn=a(r=>r.toString(\"utf8\"),\"unpackString\");var Rp=a(r=>{if([...r].length>=128){throw new Error(\"SOFTWARE must be shorter than 128 characters\")}return zn(r)},\"packSoftware\");var tt=a(r=>r,\"packBytes\");var st=a(r=>r,\"unpackBytes\");var xp=a(()=>Buffer.alloc(0),\"packNone\");var kp=a(()=>null,\"unpackNone\");var Vh=[[1,\"MAPPED-ADDRESS\",qt,Ft],[3,\"CHANGE-REQUEST\",qs,Fs],[4,\"SOURCE-ADDRESS\",qt,Ft],[5,\"CHANGED-ADDRESS\",qt,Ft],[6,\"USERNAME\",zn,Hn],[8,\"MESSAGE-INTEGRITY\",tt,st],[9,\"ERROR-CODE\",Tp,yp],[10,\"UNKNOWN-ATTRIBUTES\",wp,bp],[12,\"CHANNEL-NUMBER\",Cp,Ep],[13,\"LIFETIME\",qs,Fs],[18,\"XOR-PEER-ADDRESS\",Jr,Xr],[19,\"DATA\",tt,st],[20,\"REALM\",zn,Hn],[21,\"NONCE\",tt,st],[22,\"XOR-RELAYED-ADDRESS\",Jr,Xr],[23,\"REQUESTED-ADDRESS-FAMILY\",qs,Fs],[24,\"EVEN-PORT\",tt,st],[25,\"REQUESTED-TRANSPORT\",qs,Fs],[28,\"MESSAGE-INTEGRITY-SHA256\",tt,st],[29,\"PASSWORD-ALGORITHM\",tt,st],[30,\"USERHASH\",tt,st],[32,\"XOR-MAPPED-ADDRESS\",Jr,Xr],[34,\"RESERVATION-TOKEN\",tt,st],[36,\"PRIORITY\",qs,Fs],[37,\"USE-CANDIDATE\",xp,kp],[32770,\"PASSWORD-ALGORITHMS\",tt,st],[32771,\"ALTERNATE-DOMAIN\",zn,Hn],[32802,\"SOFTWARE\",Rp,Hn],[32803,\"ALTERNATE-SERVER\",qt,Ft],[32808,\"FINGERPRINT\",qs,Fs],[32809,\"ICE-CONTROLLED\",jh,Wh],[32810,\"ICE-CONTROLLING\",jh,Wh],[32811,\"RESPONSE-ORIGIN\",qt,Ft],[32812,\"OTHER-ADDRESS\",qt,Ft]];var Zr=class{static{a(this,\"AttributeRepository\")}constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){const s=this.attributes.find(i=>i[0]===e);if(s){s[1]=t}else{this.attributes.push([e,t])}return this}getAttributeValue(e){const t=this.attributes.find(s=>s[0]===e);return t?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}removeAttribute(e){this.attributes=this.attributes.filter(t=>t[0]!==e);return this}clear(){this.attributes=[]}};var Yh=Vh.reduce((r,e)=>{r[e[0]]=e;return r},{});var Qh=Vh.reduce((r,e)=>{r[e[1]]=e;return r},{});function ve(r,e){if(!zh(r)){return void 0}const t=r.readUInt16BE(0);const s=Buffer.from(r.slice(et-12,et));const i=new Zr;const n=[];let o=false;for(let c=et;c<r.length;){if(c+4>r.length){return void 0}const d=r.readUInt16BE(c);const h=r.readUInt16BE(c+2);const l=c+4;const u=l+h;if(u>r.length){return void 0}const g=r.slice(l,u);const S=Ks(h);if(u+S>r.length){return void 0}const p=Yh[d];if(p){const[,f,,y]=p;let m;try{m=y.name===Xr.name?y(g,s):y(g)}catch{return void 0}i.setAttribute(f,m);if(f===\"FINGERPRINT\"){const T=Xh(r.slice(0,c));if(i.getAttributeValue(\"FINGERPRINT\")!==T){return void 0}}else if(f===\"MESSAGE-INTEGRITY\"&&e){const T=Ip(r.slice(0,c),e);const C=i.getAttributeValue(\"MESSAGE-INTEGRITY\");if(!T.equals(C)){return void 0}o=true}}else{n.push({type:d,length:h,value:Buffer.from(g)})}c=u+S}if(e&&!o){return void 0}return new Q(t&16111,t&272,s,i.getAttributes(),n)}a(ve,\"parseMessage\");var Q=class extends Zr{static{a(this,\"Message\")}constructor(e,t,s=(0,ei.randomBytes)(12),i=[],n=[]){super(i);this.messageMethod=e;this.messageClass=t;this.transactionId=s;this.rawAttributes=n}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(\"hex\")}appendRawAttribute(e,t){this.rawAttributes.push({type:e,value:Buffer.from(t)});return this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){const e=Buffer.concat(this.serializedAttributes.map(s=>vp(s.type,s.value)));const t=Buffer.alloc(8);t.writeUInt16BE(this.messageMethod|this.messageClass,0);t.writeUInt16BE(e.length,2);t.writeUInt32BE(Hs,4);return Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){this.removeAttribute(\"FINGERPRINT\").removeAttribute(\"MESSAGE-INTEGRITY\");this.setAttribute(\"MESSAGE-INTEGRITY\",this.messageIntegrity(e));return this}messageIntegrity(e){const t=ka(this.bytes,this.bytes.length-et+wa);return Buffer.from((0,ei.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}addFingerprint(){this.removeAttribute(\"FINGERPRINT\");this.setAttribute(\"FINGERPRINT\",Xh(this.bytes));return this}get serializedAttributes(){const e=[];for(const t of this.attributesKeys){const s=this.getAttributeValue(t);const[i,,n]=Qh[t];const o=n.name===Jr.name?n(s,this.transactionId):n(s);e.push({type:i,value:o})}e.push(...this.rawAttributes.map(t=>({type:t.type,value:Buffer.from(t.value)})));return e}};function vp(r,e){const t=e.length;const s=Ks(t);const i=Buffer.alloc(4);i.writeUInt16BE(r,0);i.writeUInt16BE(t,2);return Buffer.concat([i,e,Buffer.alloc(s)])}a(vp,\"serializeAttribute\");var ka=a((r,e)=>{const t=Buffer.alloc(r.length);r.copy(t,0,0,2);t.writeUInt16BE(e,2);r.copy(t,4,4);return t},\"setBodyLength\");function Xh(r){const e=ka(r,r.length-et+Mh);return(Ec(e)^Oh)>>>0}a(Xh,\"messageFingerprint\");function Ip(r,e){const t=ka(r,r.length-et+wa);return Buffer.from((0,ei.createHmac)(\"sha1\",e).update(t).digest(\"hex\"),\"hex\")}a(Ip,\"messageIntegrity\");function Ks(r){const e=r%4;return e===0?0:4-e}a(Ks,\"paddingLength\");var Zh=require(\"node:dns\");var va=require(\"node:net\");var qn=class extends Error{static{a(this,\"TransactionError\")}};var Gs=class extends qn{static{a(this,\"TransactionFailed\")}constructor(e,t){super();this.response=e;this.addr=t}get str(){let e=\"STUN transaction failed\";const t=this.response.getAttributeValue(\"ERROR-CODE\");if(t){const[s,i]=t;e+=` (${s} - ${i})`}return e}};var ti=class extends qn{static{a(this,\"TransactionTimeout\")}get str(){return\"STUN transaction timed out\"}};var Fn=class extends Error{static{a(this,\"AddressFamilyMismatch\")}constructor(e,t){super(`cannot reach ${e[0]}:${e[1]} from an IPv${t} socket`);this.addr=e;this.socketFamily=t}};var si=b(\"webrtc/ice/stun/transaction\");async function it(r,e=0){const t=(0,va.isIP)(r[0]);if(t){if(e!==0&&t!==e){throw new Fn(r,e)}return r}const s=await Zh.promises.lookup(r[0],{family:e});return[s.address,r[1]]}a(it,\"resolveRequestAddress\");function eu(r,e){if(r!==null&&typeof r===\"object\"){return r}const t=typeof r===\"number\"?r:void 0;return{retransmissions:t,onRequestSent:e}}a(eu,\"normalizeTransactionOptions\");function Ia(r,e){return r[1]===e[1]&&Jh(r[0])===Jh(e[0])}a(Ia,\"addressEquals\");function Jh(r){if((0,va.isIP)(r)!==6)return r;return new URL(`http://[${r.split(\"%\")[0]}]/`).hostname.slice(1,-1)}a(Jh,\"canonicalHost\");var rt=class{static{a(this,\"Transaction\")}constructor(e,t,s,i,n){this.request=e;this.addr=t;this.protocol=s;this.ended=false;this.tries=0;this.onResponse=new w;this.responseReceived=(c,d)=>{if(this.ended||this.onResponse.length===0){return}if(!Ia(this.expectedAddr,d)){si(\"ignore STUN response from unexpected address\",d,\"expected\",this.expectedAddr);return}if(this.integrityKey){const h=c.attributesKeys.includes(\"MESSAGE-INTEGRITY\")||c.attributesKeys.includes(\"MESSAGE-INTEGRITY-SHA256\");if(!h&&!Pa(c)){si(\"ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)\");return}}if(c.messageClass===B.RESPONSE){this.onResponse.execute(c,d);this.onResponse.complete()}else{this.onResponse.error(new Gs(c,d))}};this.run=async()=>{try{if(this.signal?.aborted){throw new ti}this.attachAbortListener();this.retry().catch(d=>{si(\"retry failed\",d)});const c=await this.onResponse.asPromise();return c}finally{this.cancel()}};this.retry=async()=>{while(this.tries<this.triesMax&&!this.ended){this.onRequestSent?.(this.tries);this.protocol.sendStun(this.request,this.addr).catch(c=>{si(\"send stun failed\",c);if(this.failOnSendError){this.fail(c)}});await this.wait(this.timeoutDelay);if(this.ended){break}this.timeoutDelay*=2;this.tries++}if(this.tries>=this.triesMax&&!this.ended){si(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);this.failWithTimeout()}};const o=eu(i,n);this.triesMax=1+(o.retransmissions??Uh);this.timeoutDelay=o.responseTimeout??Hh;this.onRequestSent=o.onRequestSent;this.signal=o.signal;this.failOnSendError=o.failOnSendError??false;this.expectedAddr=t;this.integrityKey=o.integrityKey}attachAbortListener(){if(!this.signal){return}this.onAbort=()=>{this.failWithTimeout()};this.signal.addEventListener(\"abort\",this.onAbort,{once:true})}failWithTimeout(){this.fail(new ti)}fail(e){if(this.ended){return}this.ended=true;this.clearWait();if(this.onResponse.length>0){this.onResponse.error(e)}}clearWait(){if(this.waitTimer!==void 0){clearTimeout(this.waitTimer);this.waitTimer=void 0}const e=this.waitResolve;this.waitResolve=void 0;e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t;this.waitTimer=setTimeout(()=>{this.waitTimer=void 0;this.waitResolve=void 0;t()},e)})}cancel(){this.ended=true;this.clearWait();if(this.signal&&this.onAbort){this.signal.removeEventListener(\"abort\",this.onAbort);this.onAbort=void 0}}};function Pa(r){if(r.messageClass!==B.ERROR||!r.getAttributeValue(\"NONCE\")){return false}const[e]=r.getAttributeValue(\"ERROR-CODE\")??[];return e===401||e===438}a(Pa,\"isChallenge\");function Kt(r,e,t){const s=eu(e,t);if(r&&!s.integrityKey){s.integrityKey=r}return s}a(Kt,\"buildTransactionOptions\");var Kn=b(\"webrtc/ice/stun/tcpProtocol\");function ri(r){return`${r[0]}:${r[1]}`}a(ri,\"socketKey\");function Pp(r){return r.destroyed||r.writableEnded}a(Pp,\"isSocketClosed\");function su(r){if(!r.remoteAddress||!r.remotePort){return}return[r.remoteAddress,r.remotePort]}a(su,\"addressFromSocket\");async function tu(r,e,t){return await new Promise((s,i)=>{const n=a(c=>{r.off(\"listening\",o);i(c)},\"onError\");const o=a(()=>{r.off(\"error\",n);s()},\"onListening\");r.once(\"error\",n);r.once(\"listening\",o);r.listen({host:e,port:t??0,exclusive:true})})}a(tu,\"waitForListening\");var Gn=class r{static{a(this,\"BaseTcpProtocol\")}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new w;this.onDataReceived=new w;this.onConnectionClosed=new w;this.sockets=new Map}static{this.type=\"tcp\"}rememberSocket(e){const t=e.remoteAddr;if(!t){return}this.sockets.set(ri(t),e)}forgetSocket(e){const t=e.remoteAddr;if(!t){return false}const s=ri(t);if(this.sockets.get(s)!==e){return false}this.sockets.delete(s);return true}getOpenSocket(e){const t=this.sockets.get(ri(e));if(!t){return}if(Pp(t.socket)){this.dropSocket(t);return}return t}dropSocket(e){e.socket.destroy();if(this.forgetSocket(e)&&e.remoteAddr){this.onConnectionClosed.execute(e.remoteAddr)}}registerSocket(e,t){const s={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};if(t){this.rememberSocket(s)}e.on(\"data\",i=>{s.buffer=Buffer.concat([s.buffer,i]);const{frames:n,rest:o}=Kh(s.buffer);s.buffer=o;const c=s.remoteAddr??su(e);if(!s.remoteAddr&&c){s.remoteAddr=c;this.rememberSocket(s)}if(!c){return}for(const d of n){if(d.length===0){continue}this.handleFrame(d,c)}});e.on(\"close\",()=>{if(this.forgetSocket(s)&&s.remoteAddr){this.onConnectionClosed.execute(s.remoteAddr)}});e.on(\"error\",i=>{Kn(\"tcp socket error\",i)});return s}handleFrame(e,t){try{const s=ve(e);if(!s){this.onDataReceived.execute(e);return}if((s.messageClass===B.RESPONSE||s.messageClass===B.ERROR)&&this.transactions[s.transactionIdHex]){const i=this.transactions[s.transactionIdHex];const n=i.integrityKey?ve(e,i.integrityKey):s;if(!n){Kn(\"STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}else if(s.messageClass===B.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Kn(\"tcp frame parse error\",s)}}async sendFrame(e,t){const s=await this.getSocket(t);try{await new Promise((i,n)=>{s.socket.write(Fh(e),o=>{if(o){n(o);return}i()})})}catch(i){Kn(\"tcp write failed\",t,i);this.dropSocket(s);throw i}}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,s,i,n){if(this.transactions[e.transactionIdHex]){throw new Error(\"already requested\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t);const c={failOnSendError:true,...Kt(s,i,n)};const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(const[t,s]of this.sockets.entries()){if(e&&t===ri(e)){continue}s.socket.destroy();this.sockets.delete(t)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.pruneForSelection();this.onRequestReceived.complete();this.onDataReceived.complete();this.onConnectionClosed.complete()}};var jn=class extends Gn{static{a(this,\"TcpActiveProtocol\")}constructor(){super(...arguments);this.pendingSockets=new Map}async connectionMade(e){this.localIp=e}async getSocket(e){const t=ri(e);const s=this.getOpenSocket(e);if(s){return s}const i=this.pendingSockets.get(t);if(i){return await i}const n=new Promise((o,c)=>{const d=(0,$n.connect)({host:e[0],port:e[1],localAddress:this.localIp});const h=this.registerSocket(d,e);const l=a(g=>{d.off(\"connect\",u);c(g)},\"onError\");const u=a(()=>{d.off(\"error\",l);o(h)},\"onConnect\");d.once(\"error\",l);d.once(\"connect\",u)});this.pendingSockets.set(t,n);try{return await n}finally{this.pendingSockets.delete(t)}}};var Wn=class extends Gn{static{a(this,\"TcpPassiveProtocol\")}constructor(){super(...arguments);this.server=(0,$n.createServer)(e=>{this.registerSocket(e,su(e))})}async connectionMade(e,t){this.localIp=e;if(t){let s;for(let i=t[0];i<=t[1];i++){try{await tu(this.server,e,i);return}catch(n){s=n}}throw s??new Error(\"tcp port not found\")}await tu(this.server,e)}async getSocket(e){const t=this.getOpenSocket(e);if(!t){throw new Error(\"tcp passive connection not established\")}return t}get listeningPort(){const e=this.server.address();if(!e||typeof e===\"string\"){throw new Error(\"tcp passive protocol is not listening\")}return e.port}async close(){await super.close();await new Promise(e=>{this.server.close(()=>e())})}};var Aa=b(\"webrtc/ice/stun/protocol\");var Gt=class r{static{a(this,\"StunProtocol\")}static{this.type=\"stun\"}get transactionsKeys(){return Object.keys(this.transactions)}constructor(){this.type=r.type;this.transactions={};this.onRequestReceived=new w;this.onDataReceived=new w;this.connectionMade=async(e,t,s)=>{if(e){this.transport=await yt.init(\"udp4\",{portRange:t,interfaceAddresses:s})}else{this.transport=await yt.init(\"udp6\",{portRange:t,interfaceAddresses:s})}this.transport.onData=(i,n)=>{this.datagramReceived(i,n)}}}datagramReceived(e,t){try{const s=ve(e);if(!s){if(this.localCandidate){this.onDataReceived.execute(e)}return}if((s.messageClass===B.RESPONSE||s.messageClass===B.ERROR)&&this.transactionsKeys.includes(s.transactionIdHex)){const i=this.transactions[s.transactionIdHex];const n=i.integrityKey?ve(e,i.integrityKey):s;if(!n){Aa(\"STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}else if(s.messageClass===B.REQUEST){this.onRequestReceived.execute(s,t,e)}}catch(s){Aa(\"datagramReceived error\",s)}}getExtraInfo(){const{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed){return}const s=e.bytes;await this.transport.send(s,t).catch(()=>{Aa(\"sendStun failed\",t,e)})}async sendData(e,t){if(this.transport.closed){return}await this.transport.send(e,t)}connectTo(e){this.transport?.connectTo(e)}disconnect(){this.transport?.disconnect()}async request(e,t,s,i,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error(\"already request ed\");if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t,this.transport.addressFamily);const c=Kt(s,i,n);const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}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()}};var uu=require(\"node:net\");var lu=require(\"node:timers/promises\");var ru=require(\"node:crypto\");function iu(r,e,t){return(0,ru.createHash)(\"md5\").update(Buffer.from([r,e,t].join(\":\"))).digest()}a(iu,\"makeTurnIntegrityKey\");var _a=require(\"node:crypto\");function js(r){return(0,_a.randomBytes)(r).toString(\"hex\").substring(0,r)}a(js,\"randomString\");function nu(){return(0,_a.randomBytes)(12)}a(nu,\"randomTransactionId\");var ii=class{static{a(this,\"PQueue\")}constructor(){this.queue=[];this.wait=new w}put(e){this.queue.push(e);if(this.queue.length===1){this.wait.execute(e)}}get(){const e=this.queue.shift();if(!e){return new Promise(t=>{this.wait.subscribe(s=>{void this.queue.shift();t(s)})})}return e}};var ni=a(r=>{let e;let t;const s=new Promise((n,o)=>{e=n;t=o});s.then(()=>{i.execute(void 0);i.complete()}).catch(n=>{i.execute(n??new Error);i.complete()});const i=new w;r(e,t,i).catch(()=>{});return{awaitable:s,resolve:e,reject:t}},\"cancelable\");function Vn(r){return r.length>=4&&(r[0]&192)===64}a(Vn,\"isChannelData\");function ou(r,e){const t=Buffer.alloc(4);t.writeUInt16BE(r,0);t.writeUInt16BE(e.length,2);return Buffer.concat([t,e])}a(ou,\"encodeChannelData\");function au(r){if(!Vn(r)||r.length<4){return void 0}const e=r.readUInt16BE(0);const t=r.readUInt16BE(2);if(r.length<4+t){return void 0}return{channelNumber:e,data:r.subarray(4,4+t)}}a(au,\"decodeChannelData\");function cu(r){const e=Ks(r.length);return e>0?Buffer.concat([r,Buffer.alloc(e)]):r}a(cu,\"padTurnFrame\");function du(r){const e=[];let t=0;let s=false;while(r.length-t>=4){let i;if(Vn(r.subarray(t))){const n=r.readUInt16BE(t+2);i=4+n+Ks(n)}else if((r[t]&192)===0){if(r.length-t<20){break}const n=r.readUInt16BE(t+2);i=20+n+Ks(n)}else{s=true;break}if(r.length-t<i){break}e.push(r.subarray(t,t+i));t+=i}return{frames:e,malformed:s,rest:r.subarray(t)}}a(du,\"splitTurnTcpFrames\");var $=b(\"webrtc/ice/turn/protocol\");var Ap=500;var _p=1e3;var Bp=600;var Lp=285212672;function Yn(r){return r.type===\"tcp\"||r.type===\"tls\"}a(Yn,\"isStreamTransport\");function Dp(r){return r[0]}a(Dp,\"permissionKey\");function hu(r){return JSON.stringify(r)}a(hu,\"channelKey\");var Ba=class r{static{a(this,\"StunOverTurnProtocol\")}static{this.type=\"turn\"}constructor(e){this.turn=e;this.type=r.type;this.disposer=new Ii;this.onRequestReceived=new w;this.onDataReceived=new w;this.handleStunMessage=(t,s)=>{try{const i=ve(t);if(!i){this.onDataReceived.execute(t);return}if(i.messageClass===B.RESPONSE||i.messageClass===B.ERROR){const n=this.turn.transactions[i.transactionIdHex];if(n){const o=n.integrityKey?ve(t,n.integrityKey):i;if(!o){$(\"STUN over TURN response failed MESSAGE-INTEGRITY check\");return}n.responseReceived(o,s)}}else if(i.messageClass===B.REQUEST){this.onRequestReceived.execute(i,s,t)}}catch(i){$(\"datagramReceived error\",i)}};e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}async request(e,t,s,i,n){if(this.turn.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(s){e.addMessageIntegrity(s);e.addFingerprint()}const o=await it(t);const c=Kt(s,i,n);const d=new rt(e,o,this,c);this.turn.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){this.disposer.dispose();return this.turn.close()}};var La=class r{static{a(this,\"TurnProtocol\")}static{this.type=\"turn\"}constructor(e,t,s,i,n,o={}){this.server=e;this.username=t;this.password=s;this.lifetime=i;this.transport=n;this.options=o;this.type=r.type;this.onData=new w;this.onRequestReceived=new w;this.onDataReceived=new w;this.transactions={};this.expiresAt=0;this.channelNumber=16384;this.channelByAddr={};this.addrByChannel={};this.channelBindQueue=Promise.resolve();this.channelBindingByAddr=new Map;this.tcpBuffer=Buffer.alloc(0);this.permissionByAddr={};this.permissionQueue=Promise.resolve();this.creatingPermissionByAddr=new Map;this.refresh=c=>{this.refreshHandle=ni(async(d,h,l)=>{const u=new AbortController;l.once(()=>{u.abort()});while(!u.signal.aborted){const g=5/6*c*1e3;$(\"refresh delay\",g,{exp:c});try{await(0,lu.setTimeout)(g,void 0,{signal:u.signal})}catch(p){if(u.signal.aborted){return}throw p}if(u.signal.aborted){return}const S=new Q(Y.REFRESH,B.REQUEST);S.setAttribute(\"LIFETIME\",c);try{const[p]=await this.requestWithRetry(S,this.server,u.signal);c=p.getAttributeValue(\"LIFETIME\");$(\"refresh\",{exp:c});this.expiresAt=Date.now()+c*1e3}catch(p){if(u.signal.aborted){return}$(\"refresh error\",p)}}})};this.channelRefreshTime=this.options.channelRefreshTime??Ap}async connectionMade(){this.transport.onData=(i,n)=>{this.dataReceived(i,n)};const e=new Q(Y.ALLOCATE,B.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime).setAttribute(\"REQUESTED-TRANSPORT\",Lp);const[t]=await this.requestWithRetry(e,this.server).catch(i=>{$(\"connect error\",i);throw i});this.relayedAddress=t.getAttributeValue(\"XOR-RELAYED-ADDRESS\");this.mappedAddress=t.getAttributeValue(\"XOR-MAPPED-ADDRESS\");const s=t.getAttributeValue(\"LIFETIME\");$(\"connect\",this.relayedAddress,this.mappedAddress,{exp:s});this.expiresAt=Date.now()+s*1e3;this.refresh(s)}handleChannelData(e){const t=au(e);const s=t&&this.addrByChannel[t.channelNumber];if(s&&t){this.onData.execute(t.data,s)}}handleSTUNMessage(e,t){try{const s=ve(e);if(!s){throw new Error(\"not stun message\")}if(s.messageClass===B.RESPONSE||s.messageClass===B.ERROR){const i=this.transactions[s.transactionIdHex];if(i){const n=i.integrityKey&&!Pa(s)?ve(e,i.integrityKey):s;if(!n){$(\"TURN STUN response failed MESSAGE-INTEGRITY check\");return}i.responseReceived(n,t)}}else if(s.messageClass===B.REQUEST){this.onData.execute(e,t)}if(s.getAttributeValue(\"DATA\")){const i=s.getAttributeValue(\"DATA\");const n=s.getAttributeValue(\"XOR-PEER-ADDRESS\")??t;this.onData.execute(i,n)}}catch(s){$(\"parse error\",e.toString())}}dataReceived(e,t){const s=a((i,n)=>{if(i.length>=4&&Vn(i)){this.handleChannelData(i)}else{this.handleSTUNMessage(i,n)}},\"datagramReceived\");if(Yn(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);const{frames:i,rest:n}=du(this.tcpBuffer);this.tcpBuffer=n;for(const o of i){s(o,t)}}else{s(e,t)}}async send(e,t){if(this.transport.closed){return}await this.transport.send(Yn(this.transport)?cu(e):e,t)}async createPermission(e){const t=new Q(Y.CREATE_PERMISSION,B.REQUEST);t.setAttribute(\"XOR-PEER-ADDRESS\",e).setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce);await this.requestWithRetry(t,this.server)}async request(e,t,s,i,n){if(this.transactions[e.transactionIdHex]){throw new Error(\"exist\")}if(this.integrityKey){e.setAttribute(\"USERNAME\",this.username).setAttribute(\"REALM\",this.realm).setAttribute(\"NONCE\",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint()}const o=await this.resolveRequestTarget(t);const c=Kt(this.integrityKey,i,n);const d=new rt(e,o,this,c);this.transactions[e.transactionIdHex]=d;try{return await d.run()}finally{delete this.transactions[e.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(e){if(Yn(this.transport)||Ia(e,this.server)){return this.selectServerEndpoint()}return it(e,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){this.serverEndpointSelection??=this.resolveServerEndpoint().then(e=>{this.pinnedServerEndpoint=e;return e},e=>{this.serverEndpointSelection=void 0;throw e});return this.serverEndpointSelection}async resolveServerEndpoint(){const e=this.transport;if(!Yn(e)){return it(this.server,e.addressFamily??0)}if(e.remoteAddress){return e.remoteAddress}if(e instanceof cr||e instanceof dr){throw new Error(`${e.type} transport has no remote address`)}return it(this.server)}async requestWithRetry(e,t,s){let i,n;try{[i,n]=await this.request(e,t,void 0,{signal:s})}catch(o){if(o instanceof Gs==false){$(\"requestWithRetry error\",o);throw o}const[c]=o.response.getAttributeValue(\"ERROR-CODE\");const d=o.response.getAttributeValue(\"NONCE\");const h=o.response.getAttributeValue(\"REALM\");if((c===401&&h||c===438&&this.realm)&&d){$(\"retry with nonce\",c);this.nonce=d;if(c===401){this.realm=h}this.integrityKey=Op(this.username,this.realm,this.password);e.transactionId=nu();[i,n]=await this.request(e,this.server,void 0,{signal:s})}else{throw o}}return[i,n]}async sendData(e,t){let s;try{s=await this.getChannel(t)}catch(i){$(\"channelBind error; falling back to Send Indication\",i)}if(!s){await this.getPermission(t);const i=new Q(Y.SEND,B.INDICATION).setAttribute(\"DATA\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);await this.sendStun(i,await this.serverDestination());return}await this.send(ou(s.number,e),await this.serverDestination())}async getPermission(e){const t=Dp(e);if(this.permissionByAddr[t]){return}const s=this.creatingPermissionByAddr.get(t);if(s){return s}const i=this.permissionQueue.then(async()=>{if(this.permissionByAddr[t]){return}await this.createPermission(e);this.permissionByAddr[t]=true});this.permissionQueue=i.then(()=>void 0,()=>void 0);this.creatingPermissionByAddr.set(t,i);try{await i}catch(n){$(\"createPermission error\",n);throw n}finally{if(this.creatingPermissionByAddr.get(t)===i){this.creatingPermissionByAddr.delete(t)}}}async getChannel(e){const t=hu(e);const s=this.channelBindingByAddr.get(t);if(s){return s}const i=this.channelByAddr[t];const n=at(Date.now()/1e3);if(i&&i.refreshAt>n){return i}const o=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=o.then(()=>void 0,()=>void 0);this.channelBindingByAddr.set(t,o);try{return await o}catch(c){$(\"channelBind error\",c);throw c}finally{if(this.channelBindingByAddr.get(t)===o){this.channelBindingByAddr.delete(t)}}}async ensureChannel(e){const t=hu(e);const s=at(Date.now()/1e3);let i=this.channelByAddr[t];if(i&&i.refreshAt>s){return i}const n=!i;if(!i){i={number:this.channelNumber++,address:e,refreshAt:0};this.channelByAddr[t]=i;this.addrByChannel[i.number]=e}try{await this.channelBind(i.number,e);i.refreshAt=at(Date.now()/1e3)+this.channelRefreshTime;$(n?\"channelBind\":\"channelBind refresh\",i);return i}catch(o){if(n){delete this.channelByAddr[t];delete this.addrByChannel[i.number]}throw o}}async channelBind(e,t){const s=new Q(Y.CHANNEL_BIND,B.REQUEST);s.setAttribute(\"CHANNEL-NUMBER\",e).setAttribute(\"XOR-PEER-ADDRESS\",t);const[i]=await this.requestWithRetry(s,this.server);if(i.messageMethod!==Y.CHANNEL_BIND){throw new Error(\"should be CHANNEL_BIND\")}}async sendStun(e,t){await this.send(e.bytes,t)}async refreshAllocation(){if(!this.expiresAt||this.transport.closed){return false}const e=new Q(Y.REFRESH,B.REQUEST);e.setAttribute(\"LIFETIME\",this.lifetime);try{const[t]=await this.requestWithRetry(e,this.server);this.expiresAt=Date.now()+t.getAttributeValue(\"LIFETIME\")*1e3;return true}catch(t){$(\"refresh failed\",t);this.expiresAt=0;return false}}async close(){this.refreshHandle?.resolve?.();if(this.expiresAt>Date.now()&&!this.transport.closed){this.expiresAt=0;const e=new Q(Y.REFRESH,B.REQUEST);e.setAttribute(\"LIFETIME\",0);await this.requestWithRetry(e,this.server,AbortSignal.timeout(_p)).catch(t=>{$(\"delete allocation\",t)})}await this.transport.close()}};function Np(r,e){const t=(0,uu.isIP)(r[0]);if(t===4||t===6){if(e&&e!==t){$(\"udpFamily ignored for IP literal TURN server\",{address:r,udpFamily:e,literalFamily:t})}return t===6?\"udp6\":\"udp4\"}return(e??4)===6?\"udp6\":\"udp4\"}a(Np,\"selectTurnUdpSocketType\");async function Mp({address:r,username:e,password:t},{lifetime:s,portRange:i,interfaceAddresses:n,ssl:o,tlsOptions:c,transport:d,connectTimeoutMs:h,udpFamily:l}={}){s??=Bp;d??=o?\"tls\":\"udp\";const u=d===\"udp\"?await yt.init(Np(r,l),{portRange:i,interfaceAddresses:n}):d===\"tcp\"?await cr.init(r,{connectTimeoutMs:h}):await dr.init(r,c,{connectTimeoutMs:h});const g=new La(r,e,t,s,u);try{await g.connectionMade()}catch(S){try{await g.close()}catch(p){$(\"failed to close TURN client after allocation failure\",p)}throw S}return g}a(Mp,\"createTurnClient\");async function fu(r,e={}){const t=await Mp(r,e);const s=new Ba(t);return s}a(fu,\"createStunOverTurnClient\");function Op(r,e,t){return iu(r,e,t)}a(Op,\"makeIntegrityKey\");var oi=require(\"node:crypto\");var Da=require(\"node:net\");var te=class r{static{a(this,\"Candidate\")}constructor(e,t,s,i,n,o,c,d,h,l,u,g){this.foundation=e;this.component=t;this.transport=s;this.priority=i;this.host=n;this.port=o;this.type=c;this.relatedAddress=d;this.relatedPort=h;this.tcptype=l;this.generation=u;this.ufrag=g;this.id=(0,oi.randomUUID)().toString()}refreshId(){this.id=(0,oi.randomUUID)().toString()}static fromSdp(e){const t=e.split(\" \");if(t.length<8){throw new Error(\"SDP does not have enough properties\")}const s={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let u=8,g=t.length-1;u<g;u+=2){if(t[u]===\"raddr\"){s[\"related_address\"]=t[u+1]}else if(t[u]===\"rport\"){s[\"related_port\"]=Number(t[u+1])}else if(t[u]===\"tcptype\"){s[\"tcptype\"]=t[u+1]}else if(t[u]===\"generation\"){s[\"generation\"]=Number(t[u+1])}else if(t[u]===\"ufrag\"){s[\"ufrag\"]=t[u+1]}}const{foundation:i,component:n,transport:o,priority:c,host:d,port:h,type:l}=s;return new r(i,n,o,c,d,h,l,s[\"related_address\"],s[\"related_port\"],s[\"tcptype\"],s[\"generation\"],s[\"ufrag\"])}canPairWith(e){const t=(0,Da.isIPv4)(this.host);const s=(0,Da.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&Fp(this,e)&&t===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)e+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=void 0)e+=` rport ${this.relatedPort}`;if(this.tcptype)e+=` tcptype ${this.tcptype}`;if(this.generation!=void 0)e+=` generation ${this.generation}`;if(this.ufrag!=void 0)e+=` ufrag ${this.ufrag}`;return e}};var Up={host:126,prflx:110,srflx:100,relay:0};var Hp={host:105,prflx:90,srflx:80,relay:0};var zp={active:6,passive:4,so:2};var qp={active:4,passive:2,so:6};function Qn(r){return r?.toLowerCase()??\"udp\"}a(Qn,\"normalizeTransport\");function Na(r){switch(r){case\"active\":case\"passive\":case\"so\":return r;default:return void 0}}a(Na,\"normalizeTcpType\");function Fp(r,e){if(Qn(r.transport)!==\"tcp\"){return true}const t=Na(r.tcptype);const s=Na(e.tcptype);if(!t||!s){return false}return t===\"active\"&&s===\"passive\"||t===\"passive\"&&s===\"active\"||t===\"so\"&&s===\"so\"}a(Fp,\"canPairTcpCandidates\");function Kp({candidateType:r,transport:e=\"udp\",tcptype:t,otherPreference:s=8191}){if(Qn(e)!==\"tcp\"){return s}const i=Na(t)??\"active\";const n=r===\"srflx\"||r===\"prflx\"?qp[i]:zp[i];return(1<<13)*n+s}a(Kp,\"candidateLocalPreference\");function Gp(r,e=\"udp\"){const t=Qn(e)===\"tcp\"?Hp:Up;return t[r]??0}a(Gp,\"candidateTypePreference\");function jt(r,e,t,s){const i=s===void 0?`${r}|${e}|${t}`:`${r}|${e}|${t}|${s}`;return(0,oi.createHash)(\"md5\").update(i,\"ascii\").digest(\"hex\").slice(7)}a(jt,\"candidateFoundation\");function lt(r,e=65535){const t=1;const s=typeof e===\"number\"?\"udp\":Qn(e.transport);const i=typeof e===\"number\"?e:e.localPreference??Kp({candidateType:r,transport:s,tcptype:e.tcptype,otherPreference:e.otherPreference});const n=Gp(r,s);return(1<<24)*n+(1<<8)*i+(256-t)}a(lt,\"candidatePriority\");function pu(r){switch(r){case\"passive\":return\"active\";case\"active\":return\"passive\";default:return\"so\"}}a(pu,\"remoteTcpTypeForIncoming\");var Bu=require(\"node:crypto\");var Ua=require(\"node:net\");var Lu=bi(require(\"node:timers/promises\"),1);var yu=require(\"node:dgram\");var Tu=require(\"node:events\");var mu=\"224.0.0.251\";var gu=5353;var ai={A:1,AAAA:28};function jp(r){const e=r.replace(/\\.$/,\"\").split(\".\").map(t=>{const s=Buffer.from(t,\"utf8\");return Buffer.concat([Buffer.from([s.length]),s])});return Buffer.concat([...e,Buffer.from([0])])}a(jp,\"encodeName\");function Su(r,e){const t=[];let s=e;let i=-1;for(let n=0;n<64;n++){const o=r[s];if(o===void 0)throw new Error(\"truncated name\");if(o===0){s++;break}if((o&192)===192){if(i<0)i=s+2;s=(o&63)<<8|r[s+1];continue}t.push(r.toString(\"utf8\",s+1,s+1+o));s+=1+o}return[t.join(\".\"),i<0?s:i]}a(Su,\"decodeName\");function Wp(r,e){if(r===ai.A&&e.length===4)return Array.from(e).join(\".\");if(r===ai.AAAA&&e.length===16){const t=[];for(let s=0;s<16;s+=2)t.push(e.readUInt16BE(s).toString(16));return t.join(\":\")}return e}a(Wp,\"formatAddress\");function $p(r){try{if(r.length<12||!(r[2]&128))return void 0;const e=r.readUInt16BE(4);const t=r.readUInt16BE(6)+r.readUInt16BE(8)+r.readUInt16BE(10);let s=12;for(let n=0;n<e;n++)s=Su(r,s)[1]+4;const i=[];for(let n=0;n<t;n++){const[o,c]=Su(r,s);const d=r.readUInt16BE(c);const h=r.readUInt32BE(c+4);const l=r.readUInt16BE(c+8);const u=r.subarray(c+10,c+10+l);s=c+10+l;const g=d===ai.A?\"A\":d===ai.AAAA?\"AAAA\":void 0;i.push({name:o,type:g??d,ttl:h,data:Wp(d,u)})}return i}catch{return void 0}}a($p,\"parseMdnsResponse\");function Vp(r,e){const t=Buffer.alloc(12);t.writeUInt16BE(1,4);const s=Buffer.alloc(4);s.writeUInt16BE(ai[e],0);s.writeUInt16BE(1,2);return Buffer.concat([t,jp(r),s])}a(Vp,\"encodeMdnsQuery\");var Xn=class extends Tu.EventEmitter{static{a(this,\"MulticastDns\")}#e;#t;constructor(){super();this.#e=(0,yu.createSocket)({type:\"udp4\",reuseAddr:true});this.#e.on(\"error\",e=>void this.emit(\"error\",e));this.#e.on(\"message\",(e,t)=>{const s=$p(e);if(s?.length)this.emit(\"response\",s,t)});this.#t=new Promise(e=>{this.#e.bind(gu,()=>{try{this.#e.addMembership(mu);this.#e.setMulticastTTL(255);this.#e.setMulticastLoopback(true)}catch(t){this.emit(\"error\",t)}e()})})}async query(e,t=\"A\"){await this.#t;await new Promise((s,i)=>{this.#e.send(Vp(e,t),gu,mu,n=>n?i(n):s())})}destroy(){try{this.#e.close()}catch{}}};var Jn=class{static{a(this,\"MdnsLookup\")}constructor(){this.cache=new Map;this.mdnsInstance=new Xn;this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,s)=>{const i=a(()=>{this.mdnsInstance.removeListener(\"response\",o);clearTimeout(n)},\"cleanup\");const n=setTimeout(()=>{i();s(new Error(\"No mDNS response\"))},1e4);const o=a(c=>{const d=c.find(h=>h.type===\"A\"&&h.name.toLowerCase()===e.toLowerCase());if(!d){return}i();t(d.data)},\"l\");this.mdnsInstance.on(\"response\",o);this.mdnsInstance.query(e,\"A\").catch(c=>{i();s(c)})})}close(){this.mdnsInstance.destroy()}};var wu=require(\"node:crypto\");var Yp=b(\"webrtc/ice/iceBase:log\");var ci=class{static{a(this,\"CandidatePair\")}get state(){return this._state}toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}constructor(e,t,s){this.protocol=e;this.remoteCandidate=t;this.iceControlling=s;this.id=(0,wu.randomUUID)().toString();this.nominated=false;this.remoteNominated=false;this._state=L.FROZEN;this.packetsSent=0;this.packetsReceived=0;this.bytesSent=0;this.bytesReceived=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.requestsReceived=0;this.requestsSent=0;this.responsesReceived=0;this.responsesSent=0;this.retransmissionsReceived=0;this.retransmissionsSent=0;this.consentRequestsSent=0;this.requestTransactionIds=new Set}updateState(e){this._state=e}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 Ma(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){const t=this.requestTransactionIds.has(e);if(!t){this.requestTransactionIds.add(e);return false}this.retransmissionsReceived++;return true}};var di=1;var Ws=2;var bu=5;var Cu=30;var Qp=1e3;var Xp=500;function Eu(r){if(r===void 0||!Number.isFinite(r)||r<=0){return Qp}return Math.max(Xp,Math.round(r*1e3*2+200))}a(Eu,\"consentResponseTimeoutMs\");var L;(function(r){r[r[\"FROZEN\"]=0]=\"FROZEN\";r[r[\"WAITING\"]=1]=\"WAITING\";r[r[\"IN_PROGRESS\"]=2]=\"IN_PROGRESS\";r[r[\"SUCCEEDED\"]=3]=\"SUCCEEDED\";r[r[\"FAILED\"]=4]=\"FAILED\"})(L||(L={}));var Ru={iceLite:false,useTcp:false,useIpv4:true,useIpv6:true};function Oa(r){if(![\"host\",\"relay\",\"srflx\"].includes(r.type))throw new Error(`Unexpected candidate type \"${r.type}\"`);return r}a(Oa,\"validateRemoteCandidate\");function xu(r,e){return r.sort((t,s)=>Ma(t.localCandidate,t.remoteCandidate,e)-Ma(s.localCandidate,s.remoteCandidate,e)).reverse()}a(xu,\"sortCandidatePairs\");function Ma(r,e,t){const s=t&&r.priority||e.priority;const i=t&&e.priority||r.priority;return(1<<32)*Math.min(s,i)+2*Math.max(s,i)+(s>i?1:0)}a(Ma,\"candidatePairPriority\");async function ku(r,e){const t=new Q(Y.BINDING,B.REQUEST);try{const[s]=await r.request(t,e);const i=r.localCandidate;if(!i){throw new Error(\"not exist\")}const n=new te(jt(\"srflx\",i.transport,i.host,e[0]),i.component,i.transport,lt(\"srflx\",{transport:i.transport,tcptype:i.tcptype}),s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[0],s.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[1],\"srflx\",i.host,i.port,i.tcptype);return n}catch(s){Yp(\"error serverReflexiveCandidate\",s)}}a(ku,\"serverReflexiveCandidate\");function Zn(r){if(r&&Number.isNaN(r[1])){return[r[0],443]}return r}a(Zn,\"validateAddress\");var Pu=bi(require(\"node:os\"),1);function vu(r,e,t={},s){const i=[\"ipsec\",\"tun\",\"utun\",\"tap\"];const n=[\"vmnet\",\"veth\"];const{useLinkLocalAddress:o}=t;const c=Object.keys(r).map(d=>{for(const l of[...i,...n]){if(d.startsWith(l)){return{nic:d,addresses:[]}}}const h=(r[d]??[]).filter(l=>St(l.family)===e&&!l.internal&&(o?true:!s(l)));return{nic:d,addresses:h.map(l=>l.address)}}).filter(d=>!!d);c.sort((d,h)=>d.nic.localeCompare(h.nic));return Object.values(c).flatMap(d=>d.addresses)}a(vu,\"selectAddressesFromInterfaces\");var Jp=b(\"webrtc/ice/utils\");function Zp(r){return St(r.family)===4&&r.address?.startsWith(\"169.254.\")||St(r.family)===6&&r.address?.startsWith(\"fe80::\")}a(Zp,\"isLinkLocalAddress\");function Iu(r,{useLinkLocalAddress:e}={}){const t=Pu.networkInterfaces();Jp(t);return vu(t,r,{useLinkLocalAddress:e},Zp)}a(Iu,\"nodeIpAddress\");function Au(r,e,t={}){const s=[];if(r){s.push(...Iu(4,t))}if(e){s.push(...Iu(6,t))}return s}a(Au,\"getHostAddresses\");var I=b(\"webrtc/ice/ice:log\");var em=1e3;var tm=3e4;var sm={udp:65535,tcp:49151,tls:32767};function rm(r){const e=[];if(r.turnServer&&r.turnUsername&&r.turnPassword){e.push({address:r.turnServer,username:r.turnUsername,password:r.turnPassword,transport:r.turnTransport})}e.push(...r.turnServers??[]);const t=new Map;for(const s of e){const i=Zn(s.address);if(!i||!s.username||!s.password)continue;const n=i[0].toLowerCase();let o=t.get(n);if(!o){o={key:n,attempts:[]};t.set(n,o)}const c=s.transport===void 0||s.transport===\"udp\"?[\"udp\",\"tcp\"]:[s.transport];for(const d of c){const h=o.attempts.some(l=>l.transport===d&&l.address[1]===i[1]&&l.username===s.username&&l.password===s.password);if(!h)o.attempts.push({address:i,transport:d,username:s.username,password:s.password})}}return[...t.values()]}a(rm,\"relayServersOf\");function im(r){const e=[];for(const t of[r.stunServer,...r.stunServers??[]]){const s=Zn(t);if(s&&!e.some(([i,n])=>i===s[0]&&n===s[1]))e.push(s)}return e}a(im,\"stunServersOf\");var eo=class{static{a(this,\"Connection\")}constructor(e,t){this._iceControlling=e;this.localUsername=js(4);this.localPassword=js(22);this.remoteIsLite=false;this.remotePassword=\"\";this.remoteUsername=\"\";this.checkList=[];this.localCandidates=[];this.stunServers=[];this.relayServers=[];this.relays=new Map;this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.generation=-1;this.userHistory={};this.tieBreaker=(0,Bu.randomBytes)(8).readBigUInt64BE(0);this.state=\"new\";this._remoteCandidates=[];this.nominating=false;this.checkListDone=false;this.checkListState=new ii;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;this.protocols=[];this.consentFresh=false;this.consentSessionId=0;this.resolvingRemoteCandidates=0;this.noPairDeadline=0;this.onData=new w;this.stateChanged=new w;this.onIceCandidate=new w;this.queryConsent=()=>{if(this.iceLite){return}this.stopConsentLifecycle();const s=this.consentSessionId;this.consentFresh=true;const i=ni(async(n,o,c)=>{let d=false;const h=new AbortController;const l=a(()=>{if(this.consentExpiryTimer===void 0){return}clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0},\"clearConsentExpiry\");const u=a(()=>{if(d||s!==this.consentSessionId){return}l();this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0;if(d||s!==this.consentSessionId){return}if(this.state===\"closed\"||this.state===\"failed\"){return}I(\"Consent to send expired\");this.consentFresh=false;this.consentSessionId++;this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;if(this.queryConsentHandle===i){this.queryConsentHandle=void 0}d=true;h.abort();this.setState(\"failed\")},Cu*1e3)},\"refreshConsentExpiry\");c.once(()=>{d=true;if(s===this.consentSessionId){l();this.consentRequestAbort?.abort();this.consentRequestAbort=void 0}h.abort();if(this.queryConsentHandle===i){this.queryConsentHandle=void 0}});u();const g=a(()=>bu*(.8+.4*Math.random())*1e3,\"randomizedConsentInterval\");let S=Date.now()+g();const p=a(()=>this.state===\"closed\"||this.state===\"failed\",\"isTerminalState\");try{while(!p()&&!d&&s===this.consentSessionId){await this.abortableDelay(Math.max(0,S-Date.now()),h.signal);if(d||p()||s!==this.consentSessionId){break}S=Date.now()+g();const f=this.nominated;if(!f){break}const y=f.id;const m=this.generation;const T=this.remotePassword;const{localUsername:C,remoteUsername:E,iceControlling:P}=this;const de=this.buildRequest({nominate:this.shouldNominateConsentRequest(f),localUsername:C,remoteUsername:E,iceControlling:P,localCandidate:f.localCandidate});this.consentRequestAbort?.abort();const q=new AbortController;this.consentRequestAbort=q;f.consentRequestsSent++;f.requestsSent++;const pt=Eu(f.rtt);const mt=performance.now();f.protocol.request(de,f.remoteAddr,Buffer.from(T,\"utf8\"),{retransmissions:0,responseTimeout:pt,signal:q.signal,onRequestSent:a(He=>{if(He>0){f.retransmissionsSent++}},\"onRequestSent\")}).then(()=>{if(s!==this.consentSessionId||d){return}const He=this.state;if(He===\"closed\"||He===\"failed\"){return}if(this.nominated?.id!==y){return}if(this.generation!==m){return}if(this.remotePassword!==T){return}const Sc=(performance.now()-mt)/1e3;f.rtt=Sc;f.totalRoundTripTime+=Sc;f.roundTripTimeMeasurements++;f.responsesReceived++;this.consentFresh=true;u();if(He===\"disconnected\"){this.setState(\"connected\")}}).catch(He=>{if(s===this.consentSessionId&&this.nominated?.id===y){I(\"no stun response\",He)}})}}catch(f){}finally{if(s===this.consentSessionId){l()}}});this.queryConsentHandle=i};this.send=async s=>{if(!this.canSendApplicationData()){return}const i=this.nominated;await i.protocol.sendData(s,i.remoteAddr);i.packetsSent++;i.bytesSent+=s.length};this.checkStart=s=>ni(async i=>{I(\"check start\",s.toJSON());s.updateState(L.IN_PROGRESS);const n={};const{remotePassword:o,remoteUsername:c,generation:d}=this;const h=s.localCandidate.ufrag??this.localUsername;const l=false;const u=this.buildRequest({nominate:l,localUsername:h,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});const g=performance.now();try{s.requestsSent++;const[S,p]=await s.protocol.request(u,s.remoteAddr,Buffer.from(o,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++;const f=performance.now();const y=(f-g)/1e3;s.rtt=y;s.totalRoundTripTime+=y;s.roundTripTimeMeasurements++;I(\"response received\",u.toJSON(),S.toJSON(),p,{localUsername:h,remoteUsername:c,remotePassword:o,generation:d,rtt:y});n.response=S;n.addr=p}catch(S){const p=S;I(\"failure case\",u.toJSON(),p.response?JSON.stringify(p.response.toJSON(),null,2):S,{localUsername:h,remoteUsername:c,remotePassword:o,generation:d},s.remoteAddr);if(p.response?.getAttributeValue(\"ERROR-CODE\")[0]===487){if(u.attributesKeys.includes(\"ICE-CONTROLLED\")){this.switchRole(true)}else if(u.attributesKeys.includes(\"ICE-CONTROLLING\")){this.switchRole(false)}await this.checkStart(s).awaitable;i();return}if(p.response?.getAttributeValue(\"ERROR-CODE\")[0]===401){I(\"retry 401\",s.toJSON());await this.checkStart(s).awaitable;i();return}else{I(\"checkStart CandidatePairState.FAILED\",s.toJSON());s.updateState(L.FAILED);this.checkComplete(s);i();return}}if(n.addr[0]!==s.remoteAddr[0]||n.addr[1]!==s.remoteAddr[1]){s.updateState(L.FAILED);this.checkComplete(s);i();return}if(l||s.remoteNominated){s.nominated=true}else if(this.usesTcpRegularNomination(s)){}else if(this.iceControlling&&!this.nominating&&!this.nominated){this.nominating=true;const S=this.buildRequest({nominate:true,localUsername:h,remoteUsername:c,iceControlling:this.iceControlling,localCandidate:s.localCandidate});try{s.requestsSent++;await s.protocol.request(S,s.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(s));s.responsesReceived++}catch(p){this.nominating=false;s.updateState(L.FAILED);this.checkComplete(s);return}s.nominated=true}s.updateState(L.SUCCEEDED);this.checkComplete(s);i()});this.pairRemoteCandidate=s=>{for(const i of this.protocols){this.tryPair(i,s)}};this.options={...Ru,...t};if(this.iceLite){this._iceControlling=false}this.applyStunTurnServersFromOptions();this.restart().catch(s=>I(\"restart failed\",s));I(\"new Connection\",this.options)}setIceServers(e){this.options={...this.options,stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:e.turnTransport,stunServers:e.stunServers,turnServers:e.turnServers};if(e.forceTurn!==void 0){this.options.forceTurn=e.forceTurn}if(e.useTcp!==void 0){this.options.useTcp=e.useTcp}if(e.turnTlsOptions!==void 0){this.options.turnTlsOptions=e.turnTlsOptions}if(e.turnUdpFamily!==void 0){this.options.turnUdpFamily=e.turnUdpFamily}this.applyStunTurnServersFromOptions();I(\"Connection ice servers updated\",this.options)}applyStunTurnServersFromOptions(){this.stunServers=im(this.options);this.relayServers=rm(this.options);this.stunServer=this.stunServers[0];this.turnServer=Zn(this.options.turnServer)??this.relayServers[0]?.attempts[0]?.address}get iceControlling(){return this._iceControlling}set iceControlling(e){if(this.iceLite){e=false}if(this.nominated){return}this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++;this.localUsername=js(4);this.localPassword=js(22);if(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=false;this.localCandidatesEnd=false;this.state=\"new\";this.lookup?.close?.();this.lookup=void 0;this.nominated=void 0;this.nominating=false;this.checkList=[];this.checkListDone=false;this.checkListState=new ii;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;for(const e of this.protocols){e.disconnect?.();if(e.localCandidate){e.localCandidate.refreshId();e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername}}this.stopConsentLifecycle()}resetNominatedPair(){I(\"resetNominatedPair\");for(const e of this.protocols)e.disconnect?.();this.nominated=void 0;this.nominating=false;this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:s}){I(\"setRemoteParams\",{iceLite:e,usernameFragment:t,password:s});this.remoteIsLite=e;this.remoteUsername=t;this.remotePassword=s}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=true;const e=[...this.relays.values()];for(const n of this.protocols){if(n.localCandidate&&!e.includes(n)){n.localCandidate.generation=this.generation;n.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(n.localCandidate)}}let t=Au(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress});const{interfaceAddresses:s}=this.options;if(s){const n=t.filter(o=>Object.values(s).includes(o));if(n.length){t=n}}if(this.options.additionalHostAddresses){t=Array.from(new Set([...this.options.additionalHostAddresses,...t]))}const i=this.getCandidatePromises(t,this.options.stunGatherTimeout);await Promise.allSettled(i);this.localCandidatesEnd=true}this.setState(\"completed\")}appendLocalCandidate(e){this.localCandidates.push(e);this.onIceCandidate.execute(e)}isRedundant(e){const t=a(s=>s.type===\"host\"?`${s.host}|${s.port}`:`${s.relatedAddress}|${s.relatedPort}`,\"baseOf\");return this.localCandidates.some(s=>s.transport===e.transport&&s.host===e.host&&s.port===e.port&&s.type!==\"relay\"&&t(s)===t(e))}gatherRelayCandidates(e){for(const[t,s]of this.relays){if(!e.some(i=>i.key===t))this.dropRelay(t,s)}return e.map(async t=>{const s=this.relays.get(t.key);if(s){if(await s.turn.refreshAllocation()){if(this.relays.get(t.key)!==s)return;s.localCandidate.generation=this.generation;s.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(s.localCandidate);return s.localCandidate}this.dropRelay(t.key,s)}const{protocol:i,attempt:n}=await this.allocateRelay(t);if(this.state===\"closed\"||this.relays.has(t.key)){await i.close();return}this.ensureProtocol(i);this.protocols.push(i);this.relays.set(t.key,i);const o=i.turn.relayedAddress;const c=i.turn.mappedAddress;I(\"turn candidateAddress\",o);i.localCandidate=new te(jt(\"relay\",\"udp\",o[0],`${t.key}|${n.transport}`),1,\"udp\",lt(\"relay\",sm[n.transport]),o[0],o[1],\"relay\",c[0],c[1],void 0,this.generation,this.localUsername);this.appendLocalCandidate(i.localCandidate);return i.localCandidate}).map(t=>t.catch(s=>{I(\"query TURN server\",s)}))}allocateRelay(e){return new Promise((t,s)=>{let i=0;let n=0;let o=false;let c;const d=a(()=>{clearTimeout(c);if(o||i>=e.attempts.length)return;const h=e.attempts[i++];n++;c=setTimeout(d,em);fu({address:h.address,username:h.username,password:h.password},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:h.transport,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3,udpFamily:this.options.turnUdpFamily}).then(l=>{n--;if(o){l.close().catch(u=>I(\"close TURN relay\",u));return}o=true;clearTimeout(c);t({protocol:l,attempt:h})},l=>{n--;I(\"TURN allocation failed\",h.transport,h.address,l);if(o)return;if(i<e.attempts.length){d()}else if(!n){o=true;s(l)}})},\"start\");d()})}dropRelay(e,t){this.relays.delete(e);this.protocols=this.protocols.filter(s=>s!==t);t.close().catch(s=>I(\"close TURN relay\",s))}ensureProtocol(e){e.onRequestReceived.subscribe((t,s)=>{if(t.messageMethod!==Y.BINDING){this.respondError(t,s,e,[400,\"Bad Request\"]);return}const i=t.getAttributeValue(\"USERNAME\");const{remoteUsername:n}=_u(i);const o=this.userHistory[n]??this.localPassword;const{iceControlling:c}=this;if(c&&t.attributesKeys.includes(\"ICE-CONTROLLING\")){if(this.tieBreaker>=t.getAttributeValue(\"ICE-CONTROLLING\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(false)}}else if(!c&&t.attributesKeys.includes(\"ICE-CONTROLLED\")){if(this.iceLite||this.tieBreaker<t.getAttributeValue(\"ICE-CONTROLLED\")){this.respondError(t,s,e,[487,\"Role Conflict\"]);return}else{this.switchRole(true);return}}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,s,e)){return}const d=new Q(Y.BINDING,B.RESPONSE,t.transactionId);d.setAttribute(\"XOR-MAPPED-ADDRESS\",s).addMessageIntegrity(Buffer.from(o,\"utf8\")).addFingerprint();e.sendStun(d,s).catch(h=>{I(\"sendStun error\",h)});if(this.checkList.length===0&&!this.earlyChecksDone){this.earlyChecks.push([t,s,e])}else{this.checkIncoming(t,s,e)}});e.onDataReceived.subscribe(t=>{try{const s=this.nominated;if(s&&s.protocol===e){s.packetsReceived++;s.bytesReceived+=t.length}this.onData.execute(t)}catch(s){I(\"dataReceived\",s)}});e.onConnectionClosed?.subscribe(t=>{this.handleConnectionClosed(e,t)})}handleConnectionClosed(e,t){const s=this.nominated;if(!s||s.protocol!==e||s.remoteAddr[0]!==t[0]||s.remoteAddr[1]!==t[1]){return}if(this.state===\"closed\"||this.state===\"failed\"){return}I(\"selected tcp connection closed\",s.toJSON());this.stopConsentLifecycle();this.setState(\"failed\")}getCandidatePromises(e,t=5){const s=[];const{stunServers:i,relayServers:n}=this;const o=this.iceLite;const c=!o&&this.options.forceTurn&&n.length>0;const d=this.protocols.filter(l=>l instanceof Gt&&!!l.localCandidate);e=e.filter(l=>{if(this.protocols.find(u=>u.localIp===l)){return false}return true});const h=c?[]:e.map(async l=>{const u=new Gt;this.ensureProtocol(u);try{await u.connectionMade((0,Ua.isIPv4)(l),this.options.portRange,this.options.interfaceAddresses);u.localIp=l;this.protocols.push(u);I(\"protocol\",u.localIp);const g=[l,u.getExtraInfo()[1]];u.localCandidate=new te(jt(\"host\",\"udp\",g[0]),1,\"udp\",lt(\"host\",{transport:\"udp\"}),g[0],g[1],\"host\",void 0,void 0,void 0,this.generation,this.localUsername);this.pairLocalProtocol(u);this.appendLocalCandidate(u.localCandidate);return u}catch(g){I(\"error protocol STUN\",g)}});if(!c){s.push(...h.map(l=>l.then(u=>u?.localCandidate)))}if(!c&&this.options.useTcp){const l=e.map(async u=>{if(this.options.tcpPassive!==false){const g=new Wn;this.ensureProtocol(g);await g.connectionMade(u,this.options.portRange);g.localIp=u;g.localCandidate=new te(jt(\"host\",\"tcp\",u),1,\"tcp\",lt(\"host\",{transport:\"tcp\",tcptype:\"passive\"}),u,g.listeningPort,\"host\",void 0,void 0,\"passive\",this.generation,this.localUsername);this.protocols.push(g);this.appendLocalCandidate(g.localCandidate)}if(!o){const g=new jn;this.ensureProtocol(g);await g.connectionMade(u);g.localIp=u;g.localCandidate=new te(jt(\"host\",\"tcp\",u),1,\"tcp\",lt(\"host\",{transport:\"tcp\",tcptype:\"active\"}),u,9,\"host\",void 0,void 0,\"active\",this.generation,this.localUsername);this.protocols.push(g);this.pairLocalProtocol(g);this.appendLocalCandidate(g.localCandidate)}});s.push(...l)}if(!o&&!c&&i.length){const l=[...d.map(g=>Promise.resolve(g)),...h];const u=l.flatMap(g=>i.map(async S=>{const p=await g;if(!p)return;const f=this.generation;const y=(async()=>{const C=p.localCandidate?.host;if(!C||!(0,Ua.isIPv4)(C))return;const E=await ku(p,S).catch(P=>{I(\"error\",P)});if(!E||f!==this.generation||this.isRedundant(E))return;E.generation=this.generation;E.ufrag=this.localUsername;this.appendLocalCandidate(E);return E})();let m;const T=new Promise((C,E)=>{m=setTimeout(()=>E(new Error(\"STUN query timeout\")),t*1e3)});return Promise.race([y,T]).finally(()=>clearTimeout(m)).catch(C=>{I(\"query STUN server\",C)})}));s.push(...u)}if(!o){s.push(...this.gatherRelayCandidates(n))}return s}async connect(){I(\"start connect ice\");if(!this.localCandidatesEnd){if(!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(const t of this.remoteCandidates){this.pairRemoteCandidate(t)}this.sortCheckList();if(!this.iceLite){this.unfreezeInitial()}I(\"earlyChecks\",this.localPassword,this.earlyChecks.length);for(const t of this.earlyChecks){this.checkIncoming(...t)}this.earlyChecks=[];this.earlyChecksDone=true;if(this.iceLite){if(!this.nominated){let t=Ws;while(!this.checkListDone&&this.state!==\"closed\"){t=await this.checkListState.get();I(\"checkListState\",t);if(t===di){break}}if(t!==di&&!this.nominated){throw new Error(\"ICE negotiation failed\")}}this.setState(\"connected\");return}this.noPairDeadline=Date.now()+tm;for(;;){if(this.state===\"closed\")break;if(!this.schedulingChecks())break;await Lu.setTimeout(20)}let e=Ws;while(this.checkList.length>0&&e===Ws&&this.state!==\"closed\"){e=await this.checkListState.get();I(\"checkListState\",e)}for(const t of this.checkList){t.handle?.resolve?.()}if(e!==di){throw new Error(\"ICE negotiation failed\")}this.queryConsent();this.setState(\"connected\")}unfreezeInitial(){const[e]=this.checkList;if(!e)return;if(e.state===L.FROZEN){e.updateState(L.WAITING)}const t=new Set(e.localCandidate.foundation);for(const s of this.checkList){if(s.component===e.component&&!t.has(s.localCandidate.foundation)&&s.state===L.FROZEN){s.updateState(L.WAITING);t.add(s.localCandidate.foundation)}}}schedulingChecks(){if(this.nominating&&!this.nominated)return true;{const e=this.checkList.filter(t=>{if(this.options.forceTurn&&t.protocol.type===Gt.type)return false;return true}).find(t=>t.state===L.WAITING);if(e){e.handle=this.checkStart(e);return true}}{const e=this.checkList.find(t=>t.state===L.FROZEN);if(e){e.handle=this.checkStart(e);return true}}if(!this.remoteCandidatesEnd||this.resolvingRemoteCandidates>0||!this.checkList.length&&Date.now()<this.noPairDeadline){return!this.checkListDone}return false}stopConsentLifecycle(){this.consentSessionId++;this.consentFresh=false;if(this.consentExpiryTimer!==void 0){clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0}this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;const e=this.queryConsentHandle;this.queryConsentHandle=void 0;e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){if(!this.nominated){return false}if(this.state===\"closed\"||this.state===\"failed\"){return false}if(this.iceLite){return true}return this.consentFresh}abortableDelay(e,t){return new Promise((s,i)=>{if(t.aborted){i(new DOMException(\"The operation was aborted\",\"AbortError\"));return}const n=setTimeout(()=>{t.removeEventListener(\"abort\",o);s()},e);const o=a(()=>{clearTimeout(n);i(new DOMException(\"The operation was aborted\",\"AbortError\"))},\"onAbort\");t.addEventListener(\"abort\",o,{once:true})})}async close(){this.setState(\"closed\");this.stopConsentLifecycle();if(this.checkList&&!this.checkListDone){this.checkListState.put(new Promise(t=>{t(Ws)}))}this.nominated=void 0;const e=this.protocols;this.protocols=[];this.relays.clear();await Promise.all(e.map(async t=>{await t.close?.()}));this.localCandidates=[];this.lookup?.close?.();this.lookup=void 0}setState(e){this.state=e;this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=true;return}if(e.host.includes(\".local\")){void this.resolveRemoteCandidate(e);return}this.addResolvedRemoteCandidate(e)}async resolveRemoteCandidate(e){const t=this.generation;this.resolvingRemoteCandidates++;try{if(!this.lookup){this.lookup=new Jn}e.host=await this.lookup.lookup(e.host)}catch{return}finally{this.resolvingRemoteCandidates--}if(t!==this.generation||this.state===\"closed\")return;this.addResolvedRemoteCandidate(e)}addResolvedRemoteCandidate(e){try{Oa(e)}catch(t){return}if(this._remoteCandidates.some(t=>t.host===e.host&&t.port===e.port&&t.component===e.component&&t.type===e.type&&t.transport.toLowerCase()===e.transport.toLowerCase())){return}I(\"addRemoteCandidate\",e);this._remoteCandidates.push(e);this.pairRemoteCandidate(e);this.sortCheckList()}getDefaultCandidate(){const e=this.localCandidates.sort((s,i)=>s.priority-i.priority);const[t]=e;return t}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw new Error(\"Cannot set remote candidates after end-of-candidates.\");this._remoteCandidates=[];for(const t of e){try{Oa(t)}catch(s){continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=true}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){xu(this.checkList,this.iceControlling)}findPair(e,t){const s=this.checkList.find(i=>i.protocol===e&&i.remoteCandidate===t);return s}applyIceControlling(e){this._iceControlling=e;for(const t of this.checkList){t.iceControlling=e}}switchRole(e){I(\"switch role\",e);if(this.iceLite){e=false}this.applyIceControlling(e);this.sortCheckList()}checkComplete(e){e.handle=void 0;if(e.state===L.SUCCEEDED){if(e.nominated&&(e.remoteCandidate.ufrag==void 0||e.remoteCandidate.ufrag===this.remoteUsername)&&this.nominated==void 0){I(\"nominated\",e.toJSON());this.nominated=e;this.nominating=false;this.pruneTcpConnections(e);e.protocol.connectTo?.(e.remoteAddr);if(!this.iceLite&&(this.state===\"connected\"||this.state===\"completed\")){this.queryConsent()}for(const t of this.checkList){if(t.component===e.component&&[L.WAITING,L.FROZEN].includes(t.state)){t.updateState(L.FAILED)}}}if(this.nominated){if(!this.checkListDone){I(\"ICE completed\");this.checkListState.put(new Promise(t=>t(di)));this.checkListDone=true}return}I(\"not completed\",e.toJSON());for(const t of this.checkList){if(t.localCandidate.foundation===e.localCandidate.foundation&&t.state===L.FROZEN){t.updateState(L.WAITING)}}}this.nominateTcpPairIfReady();if(this.nominating){return}{const t=[L.SUCCEEDED,L.FAILED];if(this.checkList.find(({state:s})=>!t.includes(s))){return}}if(!this.iceControlling){const t=L.SUCCEEDED;if(this.checkList.find(({state:s})=>s===t)){return}}if(!this.checkListDone){I(\"ICE failed\");this.checkListState.put(new Promise(t=>{t(Ws)}))}}isTcpPair(e){return e.localCandidate.transport.toLowerCase()===\"tcp\"}usesTcpRegularNomination(e){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(e)}checkRequestOptions(e){const t=a(s=>{if(s>0){e.retransmissionsSent++}},\"onRequestSent\");if(this.isTcpPair(e)){return{retransmissions:0,responseTimeout:qh,onRequestSent:t}}return{retransmissions:4,onRequestSent:t}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating){return}for(const e of this.checkList){if(!this.isTcpPair(e)){continue}if(e.state===L.SUCCEEDED){this.nominateTcpPair(e);return}if(e.state!==L.FAILED){return}}}nominateTcpPair(e){this.nominating=true;const{generation:t}=this;const s=this.buildRequest({nominate:true,localUsername:e.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:e.localCandidate});e.requestsSent++;e.protocol.request(s,e.remoteAddr,Buffer.from(this.remotePassword,\"utf8\"),this.checkRequestOptions(e)).then(()=>{if(this.isStaleNomination(e,t)){return}e.responsesReceived++;e.nominated=true;this.nominating=false;this.checkComplete(e)},i=>{if(this.isStaleNomination(e,t)){return}I(\"tcp nomination failed\",e.toJSON(),i);this.nominating=false;e.updateState(L.FAILED);this.checkComplete(e)})}isStaleNomination(e,t){return this.state===\"closed\"||this.generation!==t||!this.checkList.includes(e)}addPair(e){this.checkList.push(e);this.sortCheckList()}checkIncoming(e,t,s){const i=e.getAttributeValue(\"USERNAME\");const{remoteUsername:n}=_u(i);let o;const[c,d]=t;for(const l of this.remoteCandidates){if(l.host===c&&l.port===d){o=l;break}}if(!o){o=new te(js(10),1,s.localCandidate?.transport??\"udp\",e.getAttributeValue(\"PRIORITY\"),c,d,\"prflx\",void 0,void 0,s.localCandidate?.transport===\"tcp\"?pu(s.localCandidate.tcptype):void 0,void 0,void 0);this._remoteCandidates.push(o)}let h=this.findPair(s,o);if(!h){h=new ci(s,o,this.iceControlling);h.updateState(L.WAITING);this.addPair(h)}h.noteIncomingRequest(e.transactionIdHex);h.requestsReceived++;h.responsesSent++;h.localCandidate.ufrag=n;I(\"Triggered Checks\",e.toJSON(),h.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation});if(this.iceLite){if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){h.remoteNominated=true;h.nominated=true;h.updateState(L.SUCCEEDED);this.checkComplete(h)}return}if([L.WAITING,L.FAILED].includes(h.state)){h.handle=this.checkStart(h)}if(e.attributesKeys.includes(\"USE-CANDIDATE\")&&!this.iceControlling){h.remoteNominated=true;if(h.state===L.SUCCEEDED){h.nominated=true;this.checkComplete(h)}}}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&!(e.localCandidate.transport.toLowerCase()===\"tcp\"&&e.localCandidate.tcptype===\"passive\"&&t.type!==\"prflx\")&&!this.findPair(e,t)){const s=new ci(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(s)){return}s.updateState(L.WAITING);this.addPair(s)}}pairLocalProtocol(e){for(const t of this.remoteCandidates){this.tryPair(e,t)}}buildRequest({nominate:e,remoteUsername:t,localUsername:s,iceControlling:i,localCandidate:n}){const o=nm({remoteUsername:t,localUsername:s});const c=new Q(Y.BINDING,B.REQUEST);c.setAttribute(\"USERNAME\",o).setAttribute(\"PRIORITY\",lt(\"prflx\",{transport:n?.transport,tcptype:n?.tcptype}));if(i){c.setAttribute(\"ICE-CONTROLLING\",this.tieBreaker);if(e){c.setAttribute(\"USE-CANDIDATE\",null)}}else{c.setAttribute(\"ICE-CONTROLLED\",this.tieBreaker)}return c}pruneTcpConnections(e){for(const t of this.protocols){if(t.localCandidate?.transport.toLowerCase()!==\"tcp\"){continue}if(\"pruneForSelection\"in t&&typeof t.pruneForSelection===\"function\"){void t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}}}respondError(e,t,s,i){const n=new Q(e.messageMethod,B.ERROR,e.transactionId);n.setAttribute(\"ERROR-CODE\",i).addMessageIntegrity(Buffer.from(this.localPassword,\"utf8\")).addFingerprint();s.sendStun(n,t).catch(o=>{I(\"sendStun error\",o)})}};var nm=a(({remoteUsername:r,localUsername:e})=>{return`${r}:${e}`},\"encodeTxUsername\");var _u=a(r=>{const[e,t]=r.split(\":\");return{remoteUsername:e,localUsername:t}},\"decodeTxUsername\");var Zs=require(\"node:crypto\");var to=class extends Map{static{a(this,\"RTCStatsReport\")}constructor(e){super();if(e){for(const t of e){this.set(t.id,t)}}}};function D(r,...e){const t=e.filter(s=>s!==void 0);return`${r}_${t.join(\"_\")}`}a(D,\"generateStatsId\");function $s(r,e,t){return D(\"codec\",r,e,t)}a($s,\"generateCodecStatsId\");function J(){return performance.timeOrigin+performance.now()}a(J,\"getStatsTimestamp\");function om(r){const e=[];for(const[t,s]of Object.entries(r)){if(t===\"id\"){continue}if(t.endsWith(\"Id\")){if(typeof s===\"string\"){e.push(s)}continue}if(t.endsWith(\"Ids\")&&Array.isArray(s)){for(const i of s){if(typeof i===\"string\"){e.push(i)}}}}return e}a(om,\"getReferencedStatsIds\");function Wt(r,e){const t=new Map;for(const n of r){t.set(n.id,n)}if(!e){return new to([...t.values()])}const s=new Set;const i=[...new Set(Array.from(e))];while(i.length>0){const n=i.shift();if(!n||s.has(n)){continue}const o=t.get(n);if(!o){continue}s.add(n);i.push(...om(o))}return new to([...s].map(n=>t.get(n)).filter(n=>!!n))}a(Wt,\"buildStatsReport\");var Gu=require(\"node:crypto\");var Mu=require(\"node:crypto\");var Fa=require(\"node:perf_hooks\");var Du=require(\"node:crypto\");var so=class{static{a(this,\"RTCRtpTransceiver\")}set codecs(e){this._codecs=e}get codecs(){return this._codecs}get codecPreferences(){return this._codecPreferences}setCodecPreferences(e){if(!Array.isArray(e)){throw Re(\"codecs must be an array\")}const t=e.length===0?void 0:e.map(_d);if(am(this._codecPreferences,t))return;this._codecPreferences=t;this.codecPreferencesNeedResolution=true;this._codecs=[];this.onCodecPreferencesChanged.execute()}constructor(e,t,s,i,n){this.kind=e;this.receiver=s;this.sender=i;this._direction=n;this.id=(0,Du.randomUUID)().toString();this.onTrack=new w;this.mid=null;this.usedForSender=false;this._codecs=[];this.headerExtensions=[];this.onCodecPreferencesChanged=new w;this.codecPreferencesNeedResolution=false;this.options={};this.stopping=false;this.stopped=false;this.rejected=false;this.pendingRejection=false;this.firedReceiving=false;this.addedByAddTrack=false;this.onStopRequested=new w;this.onRelease=new w;this.onDirectionChanged=new w;if(t){this.setDtlsTransport(t)}}get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){const t=e!==this._direction;this.setDirection(e);if(t)this.onDirectionChanged.execute()}setDirection(e){this._direction=e;if(this._currentDirection&&this._currentDirection!==\"stopped\"&&zt.includes(this._currentDirection)){this.usedForSender=true}}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e;if(e&&e!==\"stopped\"&&zt.includes(e)&&this.sender.track){this.usedForSender=true}}setDtlsTransport(e){this.receiver.setDtlsTransport(e);this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){const t=this.receiver.addTrack(e);if(t){this.onTrack.execute(e,this)}}get associated(){return this.mid!=null&&this.mLineIndex!=void 0}stop(){if(this.stopping){return}this.stopping=true;this.releaseMedia();if(!this.associated){this.markStopped()}this.onStopRequested.execute()}commitStopped({rejected:e}){if(e&&!this.stopping){this.rejected=true}this.pendingRejection=false;this.stopping=true;this.releaseMedia();this.markStopped()}markStopped(){this.stopped=true;this.setCurrentDirection(\"stopped\")}releaseMedia(){this.sender.stop({keepTrack:true});this.receiver.stop();this.receiver.endTracks();this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped){return}this.stopping=true;this.stopped=true;this.setCurrentDirection(\"stopped\");this.receiver.stop();this.sender.stop();this.onRelease.execute()}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){const e=J();return this.collectCodecStats(e)}collectCodecStats(e){const t=[];if(!this.dtlsTransport){return t}const s=D(\"transport\",this.dtlsTransport.id);for(const i of this.codecs){const n={type:\"codec\",id:$s(s,i.payloadType,this.id),timestamp:e,payloadType:i.payloadType,transportId:s,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,sdpFmtpLine:i.parameters};t.push(n)}return t}};function am(r,e){if(r===e)return true;if(r==void 0||e==void 0||r.length!==e.length){return false}return ro(r)===ro(e)}a(am,\"sameCodecPreferences\");function ro(r){if(Array.isArray(r)){return`[${r.map(ro).join(\",\")}]`}if(r!=void 0&&typeof r===\"object\"){const e=Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[s])=>t.localeCompare(s));return`{${e.map(([t,s])=>`${JSON.stringify(t)}:${ro(s)}`).join(\",\")}}`}return JSON.stringify(r)??\"undefined\"}a(ro,\"stableCodecValue\");var cm=\"inactive\";var Ha=\"sendonly\";var za=\"recvonly\";var qa=\"sendrecv\";var io=[cm,Ha,za,qa];var dm=b(\"webrtc/peer/utils\");function Ka(r,e){const t=a(n=>n.toUpperCase(),\"upper\");const s=a(n=>n.match(/(.{2})/g).join(\":\"),\"colon\");const i=(0,Mu.createHash)(e).update(r).digest(\"hex\");return s(t(i))}a(Ka,\"fingerprint\");var hm={sha1:\"sha1\",\"sha-1\":\"sha1\",sha224:\"sha224\",\"sha-224\":\"sha224\",sha256:\"sha256\",\"sha-256\":\"sha256\",sha384:\"sha384\",\"sha-384\":\"sha384\",sha512:\"sha512\",\"sha-512\":\"sha512\"};function Ga(r){return hm[r.trim().toLowerCase()]}a(Ga,\"normalizeFingerprintAlgorithm\");function no(r){return r.replace(/[^0-9a-f]/gi,\"\").toLowerCase()}a(no,\"normalizeFingerprintValue\");function Ou(r){const e=r[0];return e>19&&e<64}a(Ou,\"isDtls\");var oo=a((r,e)=>io[io.indexOf(r)&io.indexOf(e)],\"andDirection\");function Uu(r){if(r===\"sendonly\")return\"recvonly\";if(r===\"recvonly\")return\"sendonly\";return r}a(Uu,\"reverseDirection\");var Vs=Date.now;var um=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n;var Hu=a(()=>{return um+process.hrtime.bigint()/1000n},\"microTime\");var Ys=a(()=>Date.now()/1e3,\"timestampSeconds\");var ja=Date.UTC(1900,0,1);var zu=a((r=Fa.performance.timeOrigin+Fa.performance.now())=>{const e=r-ja;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);return BigInt(t)<<32n|BigInt(s)},\"ntpTime\");var Wa=a(r=>{const e=r-ja;const t=Math.floor(e/1e3);const s=Math.floor((e-t*1e3)/1e3*2**32);const i=Buffer.allocUnsafe(3);i.writeUIntBE((t&63)<<18|s>>>14,0,3);return i},\"absSendTimeOf\");var qu=a(r=>{const e=Number(r>>32n);const t=Number(r&0xffffffffn);return e*1e3+t/2**32*1e3+ja},\"ntpTimeToEpochMs\");var ao=a(r=>{return Number(r>>16n&0xffffffffn)},\"compactNtp\");function Fu(r){const e={stunServers:[],turnServers:[]};for(const t of r){const s=Array.isArray(t.urls)?t.urls:[t.urls];for(const i of s){const n=lm(i);if(!n){continue}if(n.kind===\"stun\"){e.stunServer??=n.address;e.stunServers.push(n.address)}if(n.kind===\"turn\"){if(!e.turnServer){e.turnServer=n.address;e.turnTransport=n.transport;e.turnUsername=t.username;e.turnPassword=t.credential}if(t.username&&t.credential){e.turnServers.push({address:n.address,username:t.username,password:t.credential,transport:n.transport})}}}}dm(\"iceOptions\",e);return e}a(Fu,\"parseIceServers\");function $a({configuredTurnTransport:r,forceTurnTCP:e,parsedTurnTransport:t}){if(t){return t}if(r){return r}if(e){return\"tcp\"}return void 0}a($a,\"resolveTurnTransport\");function lm(r){const e=/^(stun|stuns|turn|turns):(.+)$/i.exec(r.trim());if(!e){return}const[,t,s]=e;const i=t.toLowerCase();const[n]=s.split(\"?\",1);const[,o=\"\"]=s.split(\"?\");const c=mm(n,pm(i));if(!c){return}if(i===\"stun\"||i===\"stuns\"){return{kind:\"stun\",address:c}}const d=new URLSearchParams(o);const h=d.get(\"transport\");const l=fm({scheme:i,transportParam:h});if(l===\"invalid\"){return}return{kind:\"turn\",address:c,transport:l}}a(lm,\"parseIceServerUrl\");function fm({scheme:r,transportParam:e}){if(e==null){return r===\"turns\"?\"tls\":void 0}if(e===\"udp\"){return r===\"turns\"?\"invalid\":\"udp\"}if(e===\"tcp\"){return r===\"turns\"?\"tls\":\"tcp\"}return\"invalid\"}a(fm,\"resolveParsedTurnTransport\");function pm(r){if(r===\"stuns\"||r===\"turns\"){return 5349}return 3478}a(pm,\"defaultPort\");function mm(r,e){const t=r.startsWith(\"//\")?r.slice(2):r;if(!t){return}if(t.startsWith(\"[\")){const n=t.indexOf(\"]\");if(n===-1){return}const o=t.slice(1,n);const c=Nu(t.slice(n+1),e);return[o,c]}const s=t.indexOf(\":\");const i=t.lastIndexOf(\":\");if(s!==-1&&s===i){return[t.slice(0,s),Nu(t.slice(s+1),e)]}return[t,e]}a(mm,\"parseAddress\");function Nu(r,e){const t=r.startsWith(\":\")?r.slice(1):r;const s=Number.parseInt(t,10);return Number.isFinite(s)?s:e}a(Nu,\"parsePort\");var Xv=Xe.createSelfSignedCertificateWithKey;var Ku=a((r,e)=>{if(!r||typeof r!==\"object\"){if(e!==null&&typeof e===\"object\"){return e}else{return r}}if(!e||typeof e!==\"object\"){if(e==void 0){return r}return e}for(const t in e){if(Object.prototype.hasOwnProperty.call(e,t)){const s=e[t];if(s!=void 0){r[t]=s}}}return r},\"deepMerge\");var gm=b(\"webrtc/peer/media/receiver/receiverTwcc\");var Sm=100;var ym=500;var Tm=1<<15;function wm(r){const e=[];let t=0;while(t<r.length){let s=1;while(t+s<r.length&&r[t+s]===r[t]&&s<8191)s++;if(s>=7){e.push(new rs({packetStatus:r[t],runLength:s}));t+=s;continue}const i=r.slice(t,t+14);const n=i.includes(z.TypeTCCPacketReceivedLargeDelta)?r.slice(t,t+7):i;const o=n===i?14:7;e.push(new Sr({type:dt.TypeTCCStatusVectorChunk,symbolSize:o===14?0:1,symbolList:[...n,...Array(o-n.length).fill(z.TypeTCCPacketNotReceived)]}));t+=o}return e}a(wm,\"packetChunksOf\");var co=class{static{a(this,\"ReceiverTWCC\")}constructor(e){this.dtlsTransport=e;this.arrivals=new Map;this.fbPktCount=0;this.rtcpSsrc=(0,Gu.randomBytes)(4).readUInt32BE();this.mediaSourceSsrc=0}handleTWCC(e,t,s=Number(Hu())){const i=this.unwrap(e);if(this.nextSequenceNumber!==void 0&&i<this.nextSequenceNumber)return;if(!this.arrivals.has(i))this.arrivals.set(i,s);if(this.arrivals.size>Tm){let n=i;for(const o of this.arrivals.keys())n=Math.min(n,o);this.arrivals.delete(n);this.nextSequenceNumber=n+1}this.mediaSourceSsrc=t;if(!this.timer){this.timer=setInterval(()=>this.sendTWCC(),Sm);this.timer.unref()}}stop(){clearInterval(this.timer);this.timer=void 0;this.arrivals.clear()}sendTWCC(){if(this.arrivals.size===0)return;let e=this.nextSequenceNumber??Infinity;if(e===Infinity){for(const s of this.arrivals.keys())e=Math.min(e,s)}const t=this.highestSequenceNumber;while(e<=t){const{feedback:s,next:i}=this.buildFeedback(e,t);this.dtlsTransport.sendRtcp([new Z({feedback:s})]).catch(n=>gm(n));e=i}this.arrivals.clear();this.nextSequenceNumber=t+1}unwrap(e){if(this.highestSequenceNumber===void 0){this.highestSequenceNumber=e;return e}let t=e-this.highestSequenceNumber&65535;if(t>=32768)t-=65536;const s=this.highestSequenceNumber+t;if(s>this.highestSequenceNumber)this.highestSequenceNumber=s;return s}buildFeedback(e,t){let s=e;while(!this.arrivals.has(s))s++;const i=Math.floor(this.arrivals.get(s)/64e3);let n=i*64e3;const o=[];const c=[];let d=e;for(;d<=t&&o.length<ym;d++){const l=this.arrivals.get(d);if(l===void 0){o.push(z.TypeTCCPacketNotReceived);continue}const u=Math.round((l-n)/250);if(u<-32768||u>32767)break;const g=u>=0&&u<=255?z.TypeTCCPacketReceivedSmallDelta:z.TypeTCCPacketReceivedLargeDelta;o.push(g);c.push(new bt({type:g,delta:u*250}));n+=u*250}const h=new je({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:e&65535,packetStatusCount:o.length,referenceTime:i&16777215,fbPktCount:this.fbPktCount,packetChunks:wm(o),recvDeltas:c});this.fbPktCount=Rc(this.fbPktCount,1);return{feedback:h,next:d}}};var ho=class{static{a(this,\"CumulativeResult\")}constructor(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}addPacket(e,t,s){if(this.numPackets===0){this.firstPacketSentAtMs=t;this.firstPacketReceivedAtMs=s;this.lastPacketSentAtMs=t;this.lastPacketReceivedAtMs=s}else{if(t<this.firstPacketSentAtMs)this.firstPacketSentAtMs=t;if(s<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=s;if(t>this.lastPacketSentAtMs)this.lastPacketSentAtMs=t;if(s>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=s}this.numPackets++;this.totalSize+=e}reset(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}get receiveBitrate(){const e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;const t=this.totalSize/e*8*1e3;return ss(t)}get sendBitrate(){const e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;const t=this.totalSize/e*8*1e3;return ss(t)}};var Qs=20;var bm=10;var Cm=8192;var uo=class{static{a(this,\"SenderBandwidthEstimator\")}get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e;this.onCongestionScore.execute(e)}get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e;this.onAvailableBitrate.execute(e)}constructor(){this.congestion=false;this.onAvailableBitrate=new w;this.onCongestion=new w;this.onCongestionScore=new w;this.congestionCounter=0;this.cumulativeResult=new ho;this.sentInfos=new Map;this._congestionScore=1;this._availableBitrate=0}receiveTWCC(e){const t=Vs();const s=this.cumulativeResult.numPackets?t-this.cumulativeResult.firstPacketSentAtMs:0;if(s>1e3){this.cumulativeResult.reset();if(this.congestionCounter<Qs){this.congestionCounter++}else if(this.congestionScore<bm){this.congestionScore++}if(this.congestionCounter>=Qs&&!this.congestion){this.congestion=true;this.onCongestion.execute(this.congestion)}}for(const i of e.packetResults){if(!i.received)continue;const n=i.sequenceNumber;const o=this.sentInfos.get(n);if(!o)continue;if(!i.receivedAtMs)continue;this.cumulativeResult.addPacket(o.size,o.sendingAtMs,i.receivedAtMs)}if(s>=100&&this.cumulativeResult.numPackets>=20){this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate);this.cumulativeResult.reset();if(this.congestionCounter>-Qs){const i=ss(Qs/2)+1;const n=ss(Qs/4)+1;const o=i-(i-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-o}if(this.congestionCounter<=-Qs){if(this.congestionScore>1){this.congestionScore--;this.onCongestion.execute(false)}this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion){this.congestion=false;this.onCongestion.execute(this.congestion)}}}rtpPacketSent(e){this.sentInfos.delete(e.wideSeq-Cm&65535);this.sentInfos.set(e.wideSeq,e)}};var Se=b(\"webrtc/peer/transport/dtls\");var Em=a(()=>void 0,\"ignoreSendFailure\");function Rm(r){if(!r){return}if(r.major===254&&r.minor===253){return\"DTLS 1.2\"}if(r.major===254&&r.minor===255){return\"DTLS 1.0\"}}a(Rm,\"formatDtlsVersion\");function xm(r){switch(r){case 1:return\"AES_CM_128_HMAC_SHA1_80\";case 7:return\"AEAD_AES_128_GCM\";default:return}}a(xm,\"formatSrtpCipher\");var hi=class r{static{a(this,\"RTCDtlsTransport\")}#e;#t;constructor(e,t,s,i=[]){this.config=e;this.iceTransport=t;this.localCertificate=s;this.srtpProfiles=i;this.id=(0,Zs.randomUUID)().toString();this.state=\"new\";this.role=\"auto\";this.srtpStarted=false;this.transportSequenceNumber=0;this.receiverTWCC=new co(this);this.senderBWE=new uo;this.bytesSent=0;this.bytesReceived=0;this.packetsSent=0;this.packetsReceived=0;this.dataReceiver=()=>{};this.onStateChange=new w;this.onRtcp=new w;this.onRtp=new w;this.events=new he;this.addEventListener=(n,o,c)=>{this.events.addEventListener(n,o,c)};this.removeEventListener=(n,o)=>{this.events.removeEventListener(n,o)};this.dispatchEvent=n=>this.events.dispatchEvent(n);this.sendData=async n=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()){return}if(!this.dtls){throw new Error(\"dtls not established\")}await this.dtls.send(n)};this.localCertificate??=r.localCertificate;this.#e=Pm(t.connection)}get localParameters(){return new Js(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate){return this.localCertificate}if(this.localCertificatePromise){return this.localCertificatePromise}this.localCertificatePromise=(async()=>{const{certPem:e,keyPem:t,signatureHash:s}=await Xe.createSelfSignedCertificateWithKey({signature:ce.ecdsa_3,hash:cn.sha256_4},Ve.secp256r1_23);this.localCertificate=new ui(t,e,s);return this.localCertificate})();return this.localCertificatePromise}setRemoteParams(e){const t=km([...this.remoteParameters?.fingerprints??[],...e.fingerprints]);const s=e.role===\"auto\"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new Js(t,s)}async start(){if(this.#t){return await this.#t}if(this.state!==\"new\"){throw new Error(\"state must be new\")}this.#t=this.#s();await this.#t}async#s(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}if(this.role===\"auto\"){if(this.iceTransport.role===\"controlling\"){this.role=\"server\"}else{this.role=\"client\"}}this.setState(\"connecting\");await new Promise((e,t)=>{if(this.role===\"server\"){this.dtls=new Qr({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true,certificateRequest:true})}else{this.dtls=new Ms({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:this.#e,srtpProfiles:this.srtpProfiles,extendedMasterSecret:true})}this.dtls.onData.subscribe(s=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}this.dataReceiver(s)});this.dtls.onClose.subscribe(()=>{if(this.state!==\"failed\"){this.setState(\"closed\")}});this.dtls.onConnect.once(e);this.dtls.onError.once(s=>{this.setState(\"failed\");Se(\"dtls failed\",s);t(s)});if(this.dtls instanceof Ms){this.dtls.connect().catch(s=>{this.setState(\"failed\");Se(\"dtls connect failed\",s);t(s)})}});try{this.verifyRemoteCertificateFingerprint()}catch(e){this.setState(\"failed\");this.dtls?.close();throw e}if(this.srtpProfiles.length>0){this.startSrtp()}this.setState(\"connected\");Se(\"dtls connected\")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0){throw new Error(\"remote fingerprint not exist\")}const e=this.dtls?.remoteCertificate;if(!e){throw new Error(\"remote certificate not available\")}const t=this.remoteParameters.fingerprints.flatMap(({algorithm:c,value:d})=>{const h=Ga(c);if(!h){return[]}const l=no(d);if(!l){throw new Error(\"remote fingerprint value is empty\")}return[{normalizedAlgorithm:h,normalizedValue:l}]});if(t.length===0){throw new Error(\"no supported remote fingerprint algorithms\")}const s=Im(t);const i=t.filter(({normalizedAlgorithm:c})=>c===s);const n=i.reduce((c,{normalizedAlgorithm:d})=>{if(!c.has(d)){c.set(d,no(Ka(e,d)))}return c},new Map);const o=i.some(({normalizedAlgorithm:c,normalizedValue:d})=>n.get(c)===d);if(!o){throw new Error(\"remote certificate fingerprint mismatch\")}}updateSrtpSession(){if(!this.dtls)throw new Error;const e=this.dtls.srtp.srtpProfile;if(!e){throw new Error(\"need srtpProfile\")}Se(\"selected SRTP Profile\",e);const{localKey:t,localSalt:s,remoteKey:i,remoteSalt:n}=this.dtls.extractSessionKeys(qc(e),Fc(e));const o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:i,remoteMasterSalt:n},profile:e};this.srtp=new Yi(o);this.srtcp=new $i(o)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=true;this.updateSrtpSession();this.iceTransport.connection.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()){return}if(!jc(e))return;this.bytesReceived+=e.length;this.packetsReceived++;if($c(e)){let t;try{t=this.srtcp.decrypt(e)}catch(i){if(i instanceof le){Se(\"dropping invalid SRTCP packet\",i);return}throw i}let s;try{s=Oi.deSerialize(t)}catch(i){Se(\"dropping malformed SRTCP packet\",i);return}for(const i of s){try{if(i instanceof Z&&i.feedback instanceof je){this.senderBWE.receiveTWCC(i.feedback);continue}this.onRtcp.execute(i)}catch(n){Se(\"RTCP error\",n)}}}else{let t;try{t=this.srtp.decrypt(e)}catch(i){if(i instanceof le){Se(\"dropping invalid SRTP packet\",i);return}throw i}let s;try{s=W.deSerialize(t)}catch(i){Se(\"dropping malformed SRTP packet\",i);return}try{this.onRtp.execute(s)}catch(i){Se(\"RTP error\",i)}}})}async sendRtp(e,t){try{const s=this.srtp.encrypt(e,t);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(Em);return s.length}catch(s){Se(\"failed to send\",s);return 0}}async sendRtcp(e){if(!this.srtcp){return}const t=Buffer.concat(e.map(i=>i.serialize()));const s=this.srtcp.encrypt(t);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,t=true){if(e!=this.state){this.state=e;if(e===\"closed\"||e===\"failed\")this.receiverTWCC.stop();this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}async stop(){this.setState(\"closed\",false);this.dtls?.close();await this.iceTransport.stop()}async getStats(e=J()){const t=[];const s=D(\"transport\",this.id);const i={type:\"transport\",id:s,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===\"unknown\"?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?D(\"candidate-pair\",this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?D(\"certificate\",this.id,\"local\"):void 0,remoteCertificateId:this.dtls?.remoteCertificate?D(\"certificate\",this.id,\"remote\"):void 0,dtlsRole:this.role===\"auto\"?void 0:this.role,tlsVersion:Rm(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:xm(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};t.push(i);if(this.localCertificate){const o=this.localCertificate.getFingerprints();if(o.length>0){const c={type:\"certificate\",id:D(\"certificate\",this.id,\"local\"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(\"base64\")};t.push(c)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){const o={type:\"certificate\",id:D(\"certificate\",this.id,\"remote\"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(\"base64\")};t.push(o)}const n=await this.iceTransport.getStats(e,s);t.push(...n);return t}};var ui=class{static{a(this,\"RTCCertificate\")}constructor(e,t,s){this.certPem=t;this.signatureHash=s;this.publicKey=new Zs.X509Certificate(t).publicKey.export({type:\"spki\",format:\"pem\"});this.privateKey=(0,Zs.createPrivateKey)(e).export({type:\"pkcs8\",format:\"pem\"})}getFingerprints(){return[new Xs(\"sha-256\",Ka(fn(this.certPem),\"sha256\"))]}};var Xs=class{static{a(this,\"RTCDtlsFingerprint\")}constructor(e,t){this.algorithm=e;this.value=t}};var Js=class{static{a(this,\"RTCDtlsParameters\")}constructor(e=[],t){this.fingerprints=e;this.role=t}};var km=a(r=>{const e=new Set;return r.filter(({algorithm:t,value:s})=>{const i=`${Ga(t)??t.trim().toLowerCase()}:${no(s)}`;if(e.has(i)){return false}e.add(i);return true})},\"deduplicateFingerprints\");var vm=[\"sha512\",\"sha384\",\"sha256\",\"sha224\",\"sha1\"];var Im=a(r=>{return vm.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm},\"selectPreferredFingerprintAlgorithm\");var Va=class{static{a(this,\"IceTransport\")}#e;#t;constructor(e){this.ice=e;this.closed=false;this.#e=[];this.type=\"ice\";this.send=t=>{return this.ice.send(t)};e.onData.subscribe(t=>{if(!Ou(t))return;if(this.#t)this.#t(t);else if(this.#e&&this.#e.length<16)this.#e.push(t)})}get onData(){return this.#t??(()=>void 0)}set onData(e){const t=this.#e;if(!t){this.#t=e;return}queueMicrotask(()=>{this.#e=void 0;this.#t=e;t.forEach(s=>e(s))})}get address(){return{}}async close(){this.closed=true;K(()=>this.ice.close(),e=>Se(\"close failed\",e))}};var Pm=a(r=>new Va(r),\"createIceTransport\");var ju=require(\"node:crypto\");var lo=b(\"webrtc/peer/transport/ice\");function Am(r){switch(r){case 0:return\"frozen\";case 1:return\"waiting\";case 2:return\"in-progress\";case 3:return\"succeeded\";case 4:return\"failed\";default:return\"failed\"}}a(Am,\"mapCandidatePairState\");var fo=class{static{a(this,\"RTCIceTransport\")}constructor(e){this.iceGather=e;this.id=(0,ju.randomUUID)().toString();this.state=\"new\";this.component=\"rtp\";this.iceRestarts=0;this.renominating=false;this.events=new he;this.onStateChange=new w;this.onIceCandidate=new w;this.onNegotiationNeeded=new w;this.addEventListener=(t,s,i)=>{this.events.addEventListener(t,s,i)};this.removeEventListener=(t,s)=>{this.events.removeEventListener(t,s)};this.dispatchEvent=t=>this.events.dispatchEvent(t);this.addRemoteCandidate=async t=>{if(!this.connection.remoteCandidatesEnd){await this.connection.addRemoteCandidate(t?_m(t):void 0)}};this.connection=this.iceGather.connection;this.connection.stateChanged.subscribe(t=>{this.setState(t)});this.iceGather.onIceCandidate=t=>{this.onIceCandidate.execute(t)};this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.();this.events.emit(\"gatheringstatechange\")})}get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return\"unknown\"}if(this.connection.iceControlling)return\"controlling\";else return\"controlled\"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==\"prflx\").map(e=>nt(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>nt(e).toJSON())}getSelectedCandidatePair(){const e=this.connection.candidatePairs.find(t=>t.nominated)??this.connection.candidatePairs.find(t=>t.state===3);if(!e){return null}return{local:nt(e.localCandidate).toJSON(),remote:nt(e.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword){return null}return new er({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=true){if(e!==this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(\"statechange\")}}}gather(){return this.iceGather.gather()}setIceServers(e){this.iceGather.setIceServers(e)}setRemoteParams(e,t=false){if(t){this.renominating=true}if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)){if(this.renominating){lo(\"renomination\",e);this.connection.resetNominatedPair();this.checking=void 0;this.renominating=false}else{lo(\"restart\",e);this.restart()}}this.connection.setRemoteParams(e)}restart(){this.iceRestarts++;this.connection.restart().catch(e=>lo(\"restart failed\",e));this.setState(\"new\");this.iceGather.setGatheringState(\"new\");this.checking=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.checking??=this.check();await this.checking}async check(){this.setState(\"checking\");try{await this.connection.connect()}catch(e){if(this.state!==\"closed\")this.setState(\"failed\");throw e}}async stop(){if(this.state!==\"closed\"){this.setState(\"closed\",false);await this.connection.close()}this.onStateChange.complete();this.onIceCandidate.complete();this.onNegotiationNeeded.complete()}async getStats(e=J(),t=D(\"transport\",this.id)){const s=[];for(const n of this.connection.localCandidates){const o={type:\"local-candidate\",id:D(\"local-candidate\",n.id),timestamp:e,transportId:t,address:n.host,port:n.port,protocol:n.transport,candidateType:n.type,priority:n.priority,foundation:n.foundation,relatedAddress:n.relatedAddress,relatedPort:n.relatedPort,usernameFragment:n.ufrag,tcpType:n.tcptype};s.push(o)}for(const n of this.connection.remoteCandidates){const o={type:\"remote-candidate\",id:D(\"remote-candidate\",n.id),timestamp:e,transportId:t,address:n.host,port:n.port,protocol:n.transport,candidateType:n.type,priority:n.priority,foundation:n.foundation,relatedAddress:n.relatedAddress,relatedPort:n.relatedPort,usernameFragment:n.ufrag,tcpType:n.tcptype};s.push(o)}const i=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(n=>n.nominated),...this.connection.candidatePairs.filter(n=>!n.nominated)]:[];for(const n of i){const o={type:\"candidate-pair\",id:D(\"candidate-pair\",n.id),timestamp:e,transportId:t,localCandidateId:D(\"local-candidate\",n.localCandidate.id),remoteCandidateId:D(\"remote-candidate\",n.remoteCandidate.id),state:Am(n.state),nominated:n.nominated,packetsSent:n.packetsSent,packetsReceived:n.packetsReceived,bytesSent:n.bytesSent,bytesReceived:n.bytesReceived,currentRoundTripTime:n.rtt,totalRoundTripTime:n.totalRoundTripTime,roundTripTimeMeasurements:n.roundTripTimeMeasurements,requestsReceived:n.requestsReceived,requestsSent:n.requestsSent,responsesReceived:n.responsesReceived,responsesSent:n.responsesSent,retransmissionsReceived:n.retransmissionsReceived,retransmissionsSent:n.retransmissionsSent,consentRequestsSent:n.consentRequestsSent};s.push(o)}return s}};var po=class{static{a(this,\"RTCIceGatherer\")}constructor(e={}){this.options=e;this.onIceCandidate=()=>{};this.gatheringState=\"new\";this.onGatheringStateChange=new w;this.connection=new eo(false,this.options);this.connection.onIceCandidate.subscribe(t=>{this.onIceCandidate(nt(t))})}async gather(){if(this.gatheringState===\"new\"){this.setState(\"gathering\");await this.connection.gatherCandidates();this.onIceCandidate(void 0);this.setState(\"complete\")}}setIceServers(e){this.connection.setIceServers(e)}setGatheringState(e){this.setState(e)}get localCandidates(){return this.connection.localCandidates.map(nt)}get localParameters(){const e=new er({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword});return e}setState(e){if(e!==this.gatheringState){this.gatheringState=e;this.onGatheringStateChange.execute(e)}}};function nt(r){const e=new li(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);e.relatedAddress=r.relatedAddress;e.relatedPort=r.relatedPort;e.tcpType=r.tcptype;return e}a(nt,\"candidateFromIce\");function _m(r){return new te(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}a(_m,\"candidateToIce\");var Ya=class{static{a(this,\"RTCIceCandidate\")}constructor(e){Object.assign(this,e)}static fromSdp(e){const t=te.fromSdp(e);const s=nt(t);return s.toJSON()}static isThis(e){if(typeof e?.candidate===\"string\")return true}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};var li=class{static{a(this,\"IceCandidate\")}constructor(e,t,s,i,n,o,c,d,h){this.component=e;this.foundation=t;this.ip=s;this.port=i;this.priority=n;this.protocol=o;this.type=c;this.generation=d;this.ufrag=h}toJSON(){return new Ya({candidate:Qa(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate){throw new Error(\"candidate is required\")}const t=e.candidate.startsWith(\"candidate:\")?e.candidate.slice(\"candidate:\".length):e.candidate;const s=Xa(t);s.sdpMLineIndex=e.sdpMLineIndex??void 0;s.sdpMid=e.sdpMid??void 0;return s}catch(t){lo(\"candidate not parsed\",t)}}};var er=class{static{a(this,\"RTCIceParameters\")}constructor(e={}){this.iceLite=false;Object.assign(this,e)}};var Wu=require(\"node:crypto\");var oe=b(\"webrtc/peer/transport/sctp\");var tr=65536;var mo=class r{static{a(this,\"RTCSctpTransport\")}constructor(e=5e3,t=tr,s={}){this.port=e;this.maxMessageSize=t;this.sctpOptions=s;this.onDataChannel=new w;this.id=(0,Wu.randomUUID)().toString();this.bundled=false;this.dataChannels={};this.remoteMaxMessageSize=tr;this.dataChannelQueue=[];this.eventDisposer=[];this.datachannelReceive=async(i,n,o)=>{if(n===Us&&o.length>0){oe(\"DCEP\",i,n,o);switch(o[0]){case la:{if(o.length<12){oe(\"DATA_CHANNEL_OPEN data.length not enough\");return}if(!Object.keys(this.dataChannels).includes(i.toString())){const h=o.readUInt8(1);const l=o.readUInt32BE(4);const u=o.readUInt16BE(8);const g=o.readUInt16BE(10);let S=12;const p=o.slice(S,S+u).toString(\"utf8\");S+=u;const f=o.slice(S,S+g).toString(\"utf8\");oe(\"DATA_CHANNEL_OPEN\",{channelType:h,reliability:l,streamId:i,label:p,protocol:f});const y=(h&3)===1?l:void 0;const m=(h&3)===2?l:void 0;const T=new Zt({label:p,ordered:(h&128)===0,maxPacketLifeTime:m,maxRetransmits:y,protocol:f,id:i});const C=new Jt(this,T,false);C.isCreatedByRemote=true;this.dataChannels[i]=C;this.onDataChannel.execute(C);C.setReadyState(\"open\")}else{oe(\"datachannel already opened\",\"retransmit ack\")}const c=this.dataChannels[i];const d=Buffer.allocUnsafe(1);d.writeUInt8(ua,0);this.dataChannelQueue.push([c,Us,d]);await this.dataChannelFlush()}break;case ua:{oe(\"DATA_CHANNEL_ACK\",i,n);const c=this.dataChannels[i];if(!c){throw new Error(\"channel not found\")}c.setReadyState(\"open\")}break}}else{const c=this.dataChannels[i];if(c){const d=(()=>{switch(n){case fa:return o.toString(\"utf8\");case On:return\"\";case pa:return o;case Un:return Buffer.from([]);default:throw new Error}})();c.messagesReceived++;c.bytesReceived+=o.length;c.onMessage.execute(d);c.emit(\"message\",{data:d});if(c.onmessage){K(()=>c.onmessage({data:d}),h=>oe(\"onmessage failed\",h))}}}};this.datachannelSend=(i,n)=>{const o=pr(n);this.assertSendableMessageSize(o);i.addBufferedAmount(o);if(o===0){this.dataChannelQueue.push([i,typeof n===\"string\"?On:Un,Buffer.from([0])])}else{const c=Buffer.isBuffer(n)?n:Buffer.from(n);this.dataChannelQueue.push(typeof n===\"string\"?[i,fa,c]:[i,pa,c])}if(this.sctp.associationState!==A.ESTABLISHED){oe(\"sctp not established\",this.sctp.associationState)}this.dataChannelFlush().catch(c=>oe(\"flush failed\",c));return o}}get transport(){return this.dtlsTransport}setDtlsTransport(e){if(this.dtlsTransport&&this.dtlsTransport.id===e.id){return}this.eventDisposer.forEach(t=>t());this.dtlsTransport=e;this.sctp=new Br(new Ja(this.dtlsTransport),this.port,this.sctpOptions);this.eventDisposer=[...[this.sctp.onReceive.subscribe(ye(this.datachannelReceive,t=>oe(\"receive failed\",t))),this.sctp.onReconfigStreams.subscribe(t=>{t.forEach(s=>{const i=this.dataChannels[s];if(!i)return;i.setReadyState(\"closing\");i.setReadyState(\"closed\");delete this.dataChannels[s]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{if(t.negotiated&&t.readyState!==\"open\"){t.setReadyState(\"open\")}});this.dataChannelFlush().catch(t=>oe(\"flush failed\",t))}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState(\"closed\")});this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"closed\"){this.sctp.setState(A.CLOSED)}})].map(t=>t.unSubscribe),()=>this.sctp.onSackReceived=async()=>{},()=>this.sctp.onSent=void 0];this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()};this.sctp.onSent=(t,s,i)=>{if(s===Us||s===On||s===Un){return}this.dataChannels[t]?.addBufferedAmount(-i)}}holdReceived(e){this.sctp.holdReceived(e)}releaseReceived(e){this.sctp.releaseReceived(e)}get isServer(){return this.dtlsTransport.iceTransport.role!==\"controlling\"}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}dataChannelAddNegotiated(e){if(e.id==void 0){throw new Error}if(this.dataChannels[e.id]){throw new Error}this.dataChannels[e.id]=e;if(this.sctp.associationState===A.ESTABLISHED){e.setReadyState(\"open\")}}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=Lh;const s=0;let i=0;if(e.maxRetransmits!==null){t=1;i=e.maxRetransmits}else if(e.maxPacketLifeTime!==null){t=2;i=e.maxPacketLifeTime}if(!e.ordered){t|=128}const n=Buffer.allocUnsafe(12);n.writeUInt8(la,0);n.writeUInt8(t,1);n.writeUInt16BE(s,2);n.writeUInt32BE(i,4);const o=Buffer.from(e.label,\"utf8\");const c=Buffer.from(e.protocol,\"utf8\");n.writeUInt16BE(o.length,8);n.writeUInt16BE(c.length,10);const d=Buffer.concat([n,o,c]);this.dataChannelQueue.push([e,Us,d]);this.dataChannelFlush().catch(h=>oe(\"flush failed\",h))}async dataChannelFlush(){if(this.sctp.associationState!=A.ESTABLISHED)return;while(this.dataChannelQueue.length>0){const[e,t,s]=this.dataChannelQueue.shift();let i=e.id;if(i===void 0){i=this.dataChannelId;while(Object.keys(this.dataChannels).includes(i.toString())){i+=2}this.dataChannels[i]=e;e.setId(i)}if(t===Us){this.sctp.send(i,t,s,{ordered:true}).catch(n=>oe(\"send dcep failed\",n.message))}else{const n=e.maxPacketLifeTime!==null?Date.now()+e.maxPacketLifeTime/1e3:void 0;this.sctp.send(i,t,s,{expiry:n,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}).catch(o=>oe(\"send data failed\",o.message))}}this.dataChannelQueue=[]}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize){throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}}getCapabilities(){return r.getCapabilities(this.maxMessageSize)}static getCapabilities(e=tr){return new fi(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??tr}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=this.dtlsTransport.role===\"server\"?1:0;this.sctp.isServer=this.isServer;await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{};await this.sctp.stop()}dataChannelClose(e){if(![\"closing\",\"closed\"].includes(e.readyState)){e.setReadyState(\"closing\");if(this.sctp.associationState===A.ESTABLISHED){if(!this.sctp.reconfigQueue.includes(e.id)){this.sctp.reconfigQueue.push(e.id)}if(this.sctp.reconfigQueue.length===1){this.sctp.transmitReconfigRequest().catch(t=>oe(\"reconfig failed\",t))}}else{this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id);this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id);if(e.id!==void 0){delete this.dataChannels[e.id]}e.setReadyState(\"closed\")}}}};var fi=class{static{a(this,\"RTCSctpCapabilities\")}constructor(e){this.maxMessageSize=e}};var Ja=class{static{a(this,\"BridgeDtls\")}constructor(e){this.dtls=e;this.send=t=>{return this.dtls.sendData(t)}}set onData(e){this.dtls.dataReceiver=e}close(){}};var ot=class r{static{a(this,\"SessionDescription\")}constructor(){this.version=0;this.name=\"-\";this.time=\"0 0\";this.group=[];this.extMapAllowMixed=true;this.msidSemantic=[];this.media=[];this.dtlsFingerprints=[]}static parse(e){const[t,s]=Bm(e);const i=new r;t.forEach(c=>{if(c.startsWith(\"v=\")){i.version=Number.parseInt(c.slice(2),10)}else if(c.startsWith(\"o=\")){i.origin=c.slice(2)}else if(c.startsWith(\"s=\")){i.name=c.slice(2)}else if(c.startsWith(\"c=\")){i.host=Za(c.slice(2))}else if(c.startsWith(\"t=\")){i.time=c.slice(2)}else if(c.startsWith(\"a=\")){const[d,h]=ec(c);switch(d){case\"fingerprint\":{const[l,u]=h?.split(\" \")||[];i.dtlsFingerprints.push(new Xs(l,u))}break;case\"ice-lite\":i.iceLite=true;break;case\"ice-options\":i.iceOptions=h;break;case\"ice-pwd\":i.icePassword=h;break;case\"ice-ufrag\":i.iceUsernameFragment=h;break;case\"group\":tc(i.group,h);break;case\"msid-semantic\":tc(i.msidSemantic,h);break;case\"setup\":i.dtlsRole=Sa[h];break;case\"extmap-allow-mixed\":i.extMapAllowMixed=true;break}}});const n=i.group.find(c=>c.semantic===\"BUNDLE\");s.forEach(c=>{const d=c[0];const h=d.match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!h){throw new Error(\"m line not found\")}const l=h[1];const u=h[4].split(\" \");const g=[\"audio\",\"video\"].includes(l)?u.map(f=>Number(f)):void 0;const S=new $t(l,Number.parseInt(h[2]),h[3],g||u);S.dtlsParams=new Js([...i.dtlsFingerprints],i.dtlsRole);S.iceParams=new er({iceLite:i.iceLite,usernameFragment:i.iceUsernameFragment,password:i.icePassword});S.iceOptions=i.iceOptions;i.media.push(S);c.slice(1).forEach(f=>{if(f.startsWith(\"c=\")){S.host=Za(f.slice(2))}else if(f.startsWith(\"a=\")){const[y,m]=ec(f);switch(y){case\"candidate\":if(!m)throw new Error;S.iceCandidates.push(Xa(m));break;case\"end-of-candidates\":S.iceCandidatesComplete=true;break;case\"extmap\":{let[T,C]=m.split(\" \");if(T.includes(\"/\")){[T]=T.split(\"/\")}S.rtp.headerExtensions.push(new Te({id:Number.parseInt(T),uri:C}))}break;case\"fingerprint\":{if(!m)throw new Error;const[T,C]=m.split(\" \");S.dtlsParams?.fingerprints.push(new Xs(T,C))}break;case\"ice-options\":S.iceOptions=m;break;case\"ice-pwd\":S.iceParams.password=m;break;case\"ice-ufrag\":S.iceParams.usernameFragment=m;break;case\"ice-lite\":S.iceParams.iceLite=true;break;case\"max-message-size\":S.sctpCapabilities=new fi(Number.parseInt(m,10));break;case\"mid\":S.rtp.muxId=m;break;case\"msid\":S.msids.push(m);break;case\"rtcp\":{const[T,C]=_e(m,\" \");S.rtcpPort=Number.parseInt(T);S.rtcpHost=Za(C)}break;case\"rtcp-mux\":S.rtcpMux=true;break;case\"bundle-only\":S.bundleOnly=true;break;case\"setup\":S.dtlsParams.role=Sa[m];break;case\"recvonly\":case\"sendonly\":case\"sendrecv\":case\"inactive\":S.direction=y;break;case\"rtpmap\":{const[T,C]=_e(m,\" \");const[E,P,de]=C.split(\"/\");let q;if(S.kind===\"audio\"){q=de?Number.parseInt(de):1}const pt=new re({mimeType:S.kind+\"/\"+E,channels:q,clockRate:Number.parseInt(P),payloadType:Number.parseInt(T)});S.rtp.codecs.push(pt)}break;case\"sctpmap\":{if(!m)throw new Error;const[T,C]=_e(m,\" \");S.sctpMap[Number.parseInt(T)]=C;S.sctpPort=Number.parseInt(T)}break;case\"sctp-port\":if(!m)throw new Error;S.sctpPort=Number.parseInt(m);break;case\"ssrc\":{const[T,C]=_e(m,\" \");const E=Number.parseInt(T);const[P,de]=_e(C,\":\");let q=S.ssrc.find(pt=>pt.ssrc===E);if(!q){q=new sr({ssrc:E});S.ssrc.push(q)}if(ya.includes(P)){q[P]=de}}break;case\"ssrc-group\":tc(S.ssrcGroup,m);break;case\"rid\":{const[T,C]=_e(m,\" \");S.simulcastParameters.push(new es({rid:T,direction:C}))}break}}});if(!S.iceParams.usernameFragment||!S.iceParams.password){if(S.rtp.muxId&&n&&n.items.includes(S.rtp.muxId)){for(let f=0;f<n.items.length;f++){if(!n.items.includes(f.toString()))continue;const y=i.media[f];if(y.iceParams?.usernameFragment&&y.iceParams.password){S.iceParams={...y.iceParams};break}}}}if(!S.dtlsParams.role){S.dtlsParams=void 0}const p=a(f=>S.rtp.codecs.find(y=>y.payloadType===f),\"findCodec\");c.slice(1).forEach(f=>{if(f.startsWith(\"a=\")){const[y,m]=ec(f);if(y===\"fmtp\"){const[T,C]=_e(m,\" \");const E=p(Number(T));E.parameters=C}else if(y===\"rtcp-fb\"){const[T,C,E]=m.split(\" \");S.rtp.codecs.forEach(P=>{if([\"*\",P.payloadType.toString()].includes(T)){P.rtcpFeedback.push(new Li({type:C,parameter:E}))}})}}})});const o=n?i.media.find(c=>c.rtp.muxId===n.items[0]):void 0;if(n&&o?.port){for(const c of i.media){if(c.port===0&&c.bundleOnly&&c.rtp.muxId&&n.items.includes(c.rtp.muxId))c.port=o.port}}return i}webrtcTrackId(e){if(e.msid?.includes(\" \")){const t=e.msid.split(\" \");for(const s of this.msidSemantic){if(s.semantic===\"WMS\"&&(s.items.includes(t[0])||s.items.includes(\"*\"))){return t[1]}}}return}get string(){const e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host){e.push(`c=${sc(this.host)}`)}e.push(`t=${this.time}`);this.group.forEach(i=>e.push(`a=group:${i.str}`));if(this.extMapAllowMixed){e.push(`a=extmap-allow-mixed`)}this.msidSemantic.forEach(i=>e.push(`a=msid-semantic:${i.str}`));const t=this.media.map(i=>i.toString()).join(\"\");const s=e.join(\"\\r\\n\")+\"\\r\\n\"+t;return s}toJSON(){const e=this.string;if(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type){this.cachedJson=new rc(e,this.type)}return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}};var $t=class{static{a(this,\"MediaDescription\")}constructor(e,t,s,i){this.kind=e;this.port=t;this.profile=s;this.fmt=i;this.msids=[];this.rtcpMux=false;this.bundleOnly=false;this.ssrc=[];this.ssrcGroup=[];this.rtp={codecs:[],headerExtensions:[]};this.sctpMap={};this.iceCandidates=[];this.iceCandidatesComplete=false;this.simulcastParameters=[]}get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){const e=[];e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(t=>t.toString()).join(\" \")}`);if(this.host){e.push(`c=${sc(this.host)}`)}this.iceCandidates.forEach(t=>{e.push(`a=candidate:${Qa(t)}`)});if(this.iceCandidatesComplete){e.push(\"a=end-of-candidates\")}if(this.iceParams?.usernameFragment){e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`)}if(this.iceParams?.password){e.push(`a=ice-pwd:${this.iceParams.password}`)}if(this.iceParams?.iceLite){e.push(`a=ice-lite`)}if(this.iceOptions){e.push(`a=ice-options:${this.iceOptions}`)}if(this.dtlsParams){this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)});e.push(`a=setup:${Mn[this.dtlsParams.role]}`)}if(this.direction){e.push(`a=${this.direction}`)}if(this.rtp.muxId){e.push(`a=mid:${this.rtp.muxId}`)}this.msids.forEach(t=>e.push(`a=msid:${t}`));if(this.rtcpPort&&this.rtcpHost){e.push(`a=rtcp:${this.rtcpPort} ${sc(this.rtcpHost)}`);if(this.rtcpMux){e.push(\"a=rtcp-mux\")}}this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)});this.ssrc.forEach(t=>{ya.forEach(s=>{const i=t[s];if(i!==void 0){e.push(`a=ssrc:${t.ssrc} ${s}:${i}`)}})});this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`);t.rtcpFeedback.forEach(s=>{let i=s.type;if(s.parameter)i+=` ${s.parameter}`;e.push(`a=rtcp-fb:${t.payloadType} ${i}`)});if(t.parameters){e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}});Object.keys(this.sctpMap).forEach(t=>{const s=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${s}`)});if(this.sctpPort){e.push(`a=sctp-port:${this.sctpPort}`)}if(this.sctpCapabilities){e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`)}this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`));if(this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{e.push(`a=rid:${n.rid} ${n.direction}`)});let t=`a=simulcast:`;const s=this.simulcastParameters.filter(n=>n.direction===\"recv\");if(s.length){t+=`recv ${s.map(n=>n.rid).join(\";\")} `}const i=this.simulcastParameters.filter(n=>n.direction===\"send\");if(i.length){t+=`send ${i.map(n=>n.rid).join(\";\")}`}e.push(t)}return e.join(\"\\r\\n\")+\"\\r\\n\"}};var ft=class{static{a(this,\"GroupDescription\")}constructor(e,t){this.semantic=e;this.items=t}get str(){return`${this.semantic} ${this.items.join(\" \")}`}};function Za(r){const e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error(\"exception\");return e[2]}a(Za,\"ipAddressFromSdp\");function sc(r){const e=(0,Vu.isIPv4)(r)?4:6;return`IN IP${e} ${r}`}a(sc,\"ipAddressToSdp\");function Qa(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;if(r.relatedAddress!=void 0){e+=` raddr ${r.relatedAddress}`}if(r.relatedPort!=void 0){e+=` rport ${r.relatedPort}`}if(r.tcpType!=void 0){e+=` tcptype ${r.tcpType}`}if(r.generation!=void 0){e+=` generation ${r.generation}`}if(r.ufrag!=void 0){e+=` ufrag ${r.ufrag}`}return e}a(Qa,\"candidateToSdp\");function Bm(r){const e=[];const t=[];let s=r.split(\"\\r\\n\");if(s.length===1){s=r.split(\"\\n\")}s.forEach(i=>{if(i.startsWith(\"m=\")){t.push([i])}else if(t.length>0){t[t.length-1].push(i)}else{e.push(i)}});return[e,t]}a(Bm,\"groupLines\");function ec(r){if(r.includes(\":\")){const e=_e(r.slice(2),\":\");return[e[0],e[1]]}else{return[r.slice(2),void 0]}}a(ec,\"parseAttr\");function tc(r,e,t=s=>s.toString()){const s=e.split(\" \");if(s.length>0){r.push(new ft(s[0],s.slice(1).map(t)))}}a(tc,\"parseGroup\");function Xa(r){const e=te.fromSdp(r);const t=nt(e);return t}a(Xa,\"candidateFromSdp\");var rc=class{static{a(this,\"RTCSessionDescription\")}constructor(e,t){Object.defineProperties(this,{sdp:{configurable:true,enumerable:true,value:e,writable:false},type:{configurable:true,enumerable:true,value:t,writable:false}})}static isThis(e){if(typeof e?.sdp===\"string\")return true}toSdp(){return{sdp:this.sdp,type:this.type}}};function ic(r,e){const t=\"-\";const s=(0,$u.randomBytes)(8).readBigUInt64BE(0).toString().slice(0,8);const i=0;e.origin=`${t} ${s} ${i} IN IP4 0.0.0.0`;e.msidSemantic.push(new ft(\"WMS\",[\"*\"]));e.type=r}a(ic,\"addSDPHeader\");function Ie(r){const e={};r.split(\";\").forEach(t=>{if(t.length===0)return;if(t.includes(\"=\")){const[s,i]=_e(t,\"=\");if(Dh.includes(s)){e[s]=Number(i)}else{e[s]=i}}else if(t.includes(\":\")){const[s,i]=t.split(\":\");e[s]=Number.isNaN(Number(i))?i:Number(i)}else{e[t]=void 0}});return e}a(Ie,\"codecParametersFromString\");var sr=class{static{a(this,\"SsrcDescription\")}constructor(e){Object.assign(this,e)}};function mi(r){return r.name.toLowerCase()}a(mi,\"codecName\");function go(r,e){return r==void 0||e==void 0||r===e}a(go,\"optionalEqual\");function Yu(r){const e=Ie(r.parameters??\"\");return{packetizationMode:e[\"packetization-mode\"],profileLevelId:e[\"profile-level-id\"]?.toString().toLowerCase()}}a(Yu,\"h264Parameters\");function rr(r,e){if(r.mimeType.toLowerCase()!==e.mimeType.toLowerCase()){return false}if(r.clockRate!==e.clockRate)return false;if(!go(r.channels,e.channels))return false;if(mi(r)!==\"h264\")return true;const t=Yu(r);const s=Yu(e);if(!go(t.packetizationMode,s.packetizationMode)){return false}return go(t.profileLevelId,s.profileLevelId)}a(rr,\"isCodecCompatible\");function Vt(r){return[\"rtx\",\"red\"].includes(mi(r))}a(Vt,\"isAuxiliary\");function So(r,e,t){if(r!==\"audio\"||e==void 0||mi(e)!==\"red\"){return e}const[s]=nc(e);return t.find(i=>!Vt(i)&&i.payloadType===s)??t.find(i=>!Vt(i))??e}a(So,\"deliveredTrackCodec\");function Qu(r,e){return r.some(t=>!Vt(t)&&e.some(s=>s.mimeType.toLowerCase()===t.mimeType.toLowerCase()))}a(Qu,\"hasCommonPrimaryMimeType\");function nc(r){const e=r.parameters??\"\";if(mi(r)===\"rtx\"){const t=Number(Ie(e).apt);return Number.isNaN(t)?[]:[t]}if(mi(r)===\"red\"){return e.split(\"/\").map(Number).filter(t=>!Number.isNaN(t))}return[]}a(nc,\"referencedPayloadTypes\");function Xu(r,e){const t=new Set(e.map(i=>i.payloadType));const s=r.filter(i=>{if(!Vt(i))return false;const n=nc(i);return n.length>0&&n.every(o=>t.has(o))});return r.filter(i=>e.includes(i)||s.includes(i))}a(Xu,\"withAuxiliaryCodecs\");function Ju(r,e){const t=r.filter(s=>!Vt(s)&&e.some(i=>rr(i,s)));return Xu(r,t)}a(Ju,\"intersectCodecs\");function Lm(r,e){return r.mimeType.toLowerCase()===e.mimeType.toLowerCase()&&go(r.clockRate,e.clockRate)}a(Lm,\"matchesPreference\");function Zu(r,e){if(e==void 0)return r;const t=e.flatMap(c=>{const d=r.find(h=>Lm(h,c));return d?[d]:[]});const s=[...new Set(t)];const i=new Set(s.filter(Vt).flatMap(nc));const n=r.filter(c=>!Vt(c)&&(s.includes(c)||i.has(c.payloadType)));const o=Xu(r,n);return[...s.filter(c=>o.includes(c)),...o.filter(c=>!s.includes(c))]}a(Zu,\"applyCodecPreferences\");function oc(r,e,t){return Zu(e==void 0?r:Ju(r,e),t)}a(oc,\"resolveCodecs\");function pi(r){return r?.map(e=>e.mimeType).join(\", \")||\"(none)\"}a(pi,\"list\");function Yt(r){const{kind:e,configured:t,source:s,preferences:i}=r;const n=s==void 0?t:Ju(t,s);if(s!=void 0&&n.length===0){throw _(\"NotSupportedError\",`Track codec ${pi(s)} is not supported by this RTCPeerConnection. Configured ${e} codecs: ${pi(t)}`)}const o=Zu(n,i);if(o.length===0){throw _(\"NotSupportedError\",`No codec remains after applying codec preferences. Source codecs: ${pi(s)} Configured codecs: ${pi(t)} Preferred codecs: ${pi(i)}`)}return o}a(Yt,\"assertCodecsSupported\");function ac(){return new Te({uri:M.sdesMid})}a(ac,\"useSdesMid\");function cc(){return new Te({uri:M.transportWideCC})}a(cc,\"useTransportWideCC\");function dc(){return new Te({uri:M.absSendTime})}a(dc,\"useAbsSendTime\");function el(){return new Te({uri:M.audioLevelIndication})}a(el,\"useAudioLevelIndication\");var sl=require(\"node:crypto\");var wo=require(\"node:timers/promises\");var Dm=b(\"webrtc/peer/media/receiver/nack\");var tl=30*5;var yo=class{static{a(this,\"NackHandler\")}constructor(e){this.receiver=e;this.newEstSeqNum=0;this._lost={};this.onPacketLost=new w;this.retryCount=10;this.closed=false;this.sendNack=()=>new Promise((t,s)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){const i=new Ge({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers});const n=new Z({feedback:i});this.receiver.dtlsTransport.sendRtcp([n]).then(t).catch(s);this.updateRetryCount();this.onPacketLost.execute(i)}})}get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t;if(this.nackLoop||this.closed){return}this.nackLoop=setInterval(ye(async()=>{await this.sendNack();if(!Object.keys(this._lost).length){clearInterval(this.nackLoop);this.nackLoop=void 0}},s=>Dm(\"failed to send nack\",s)),5)}removeLost(e){delete this._lost[e]}addPacket(e){const{sequenceNumber:t,ssrc:s}=e.header;this.mediaSourceSsrc=s;if(this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===j(this.newEstSeqNum,1)){this.newEstSeqNum=t}else if(t>j(this.newEstSeqNum,1)){for(let i=j(this.newEstSeqNum,1);i<t;i=j(i,1)){this.setLost(i,1)}this.newEstSeqNum=t;this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>tl){this._lost=Object.entries(this._lost).slice(-tl).reduce((e,[t,s])=>{e[t]=s;return e},{})}}close(){this.closed=true;clearInterval(this.nackLoop);this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{const t=this._lost[e]++;if(t>this.retryCount){this.removeLost(e);return e}})}};var To=class{static{a(this,\"StreamStatistics\")}constructor(e){this.cycles=0;this.packets_received=0;this.bytesReceived=0;this.headerBytesReceived=0;this.jitter_q4=0;this.expected_prior=0;this.received_prior=0;this.clockRate=e}add(e,t=Date.now()/1e3){const s=this.max_seq==void 0||Ei(e.header.sequenceNumber,this.max_seq);this.packets_received++;this.bytesReceived+=e.payload.length;this.headerBytesReceived+=e.header.serializeSize;this.lastPacketReceivedTimestamp=J();if(this.base_seq==void 0){this.base_seq=e.header.sequenceNumber}if(s){const i=at(t*this.clockRate);if(this.max_seq!=void 0&&e.header.sequenceNumber<this.max_seq){this.cycles+=1<<16}this.max_seq=e.header.sequenceNumber;if(e.header.timestamp!==this.last_timestamp&&this.packets_received>1){const n=Math.abs(i-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=i;this.last_timestamp=e.header.timestamp}}get fraction_lost(){const e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;const t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;const s=e-t;if(e==0||s<=0){return 0}else{return Math.floor((s<<8)/e)}}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){const e=this.packets_expected-this.packets_received;return e<0?0:e}};var ir=b(\"webrtc/peer/media/rtpReceiver\");var nr=class{static{a(this,\"RTCRtpReceiver\")}get codecArray(){this.sortedCodecs??=Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType);return this.sortedCodecs}constructor(e,t,s){this.config=e;this.kind=t;this.rtcpSsrc=s;this.codecs={};this.ssrcByRtx={};this.nack=new yo(this);this.audioRedHandler=new zi;this.type=\"receiver\";this.uuid=(0,sl.randomUUID)().toString();this.tracks=[];this.trackBySSRC={};this.trackByRID={};this.lastSRtimestamp={};this.receiveLastSRTimestamp={};this.onPacketLost=this.nack.onPacketLost;this.onRtcp=new w;this.stopped=false;this.remoteStreamIds=[];this.rtcpRunning=false;this.rtcpCancel=new AbortController;this.remoteStreams={};this.senderReportsReceivedBySsrc={};this.remoteTimestampsBySsrc={};this.remotePacketCountBySsrc={};this.remoteOctetCountBySsrc={};this.nackCountBySsrc={};this.pliCountBySsrc={};this.handleRtpBySsrc=(i,n)=>{const o=this.trackBySSRC[i.header.ssrc];this.handleRTP(i,n,o)};this.handleRtpByRid=(i,n,o)=>{const c=this.trackByRID[n];if(!this.trackBySSRC[i.header.ssrc]){this.trackBySSRC[i.header.ssrc]=c}this.handleRTP(i,o,c)};this.defaultTrack=new Be({kind:t,remote:true});this.onPacketLost.subscribe(i=>{this.nackCountBySsrc[i.mediaSourceSsrc]=(this.nackCountBySsrc[i.mediaSourceSsrc]??0)+1})}get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===\"nack\")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===rn().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===Bt().type)}prepareReceive(e){e.codecs.forEach(t=>{this.codecs[t.payloadType]=t});this.sortedCodecs=void 0;e.encodings.forEach(t=>{if(t.rtx){this.ssrcByRtx[t.rtx.ssrc]=t.ssrc}})}resyncCodecs(e){for(const s of Object.keys(this.codecs)){delete this.codecs[Number(s)]}this.sortedCodecs=void 0;for(const s of Object.keys(this.ssrcByRtx)){delete this.ssrcByRtx[Number(s)]}this.prepareReceive(e);const t=So(this.kind,e.codecs[0],e.codecs);if(t){for(const s of this.tracks){s.codec=t}}}addTrack(e){const t=this.tracks.find(s=>{if(s.rid){return s.rid===e.rid}if(s.ssrc){return s.ssrc===e.ssrc}});if(t){return false}this.tracks.push(e);if(e.ssrc){this.trackBySSRC[e.ssrc]=e}if(e.rid){this.trackByRID[e.rid]=e}return true}stop(){this.stopped=true;this.rtcpRunning=false;this.rtcpCancel.abort();this.nack.close()}endTracks(){for(const e of[...this.tracks,this.defaultTrack]){e.stop()}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,wo.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=Object.entries(this.remoteStreams).map(([s,i])=>{let n=0,o=0;if(this.lastSRtimestamp[s]){n=this.lastSRtimestamp[s];const c=Ys()-this.receiveLastSRTimestamp[s];if(c>0&&c<65536){o=at(c*65536)}}return new wt({ssrc:Number(s),fractionLost:i.fraction_lost,packetsLost:i.packets_lost,highestSequence:i.max_seq,jitter:i.jitter,lsr:n,dlsr:o})});const t=new be({ssrc:this.rtcpSsrc,reports:e});try{if(this.config.debug.receiverReportDelay){await(0,wo.setTimeout)(this.config.debug.receiverReportDelay)}await this.dtlsTransport.sendRtcp([t])}catch(s){ir(\"sendRtcp failed\",s);await(0,wo.setTimeout)(500+Math.random()*1e3)}}}catch(e){ir(\"rtcp loop ended\",e)}}getInboundRtpStatsId(e){return D(\"inbound-rtp\",e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return D(\"remote-outbound-rtp\",e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e?true:t===e).filter(t=>t.ssrc).map(t=>this.getInboundRtpStatsId(t))}collectStats(e){const t=[];const s=this.dtlsTransport?D(\"transport\",this.dtlsTransport.id):void 0;const i=this.codecArray[0];const n=new Set;for(const o of this.tracks){if(!o.ssrc)continue;const c=this.remoteStreams[o.ssrc];const d=this.remoteTimestampsBySsrc[o.ssrc]!==void 0;const h=this.lastSRtimestamp[o.ssrc]!==void 0||d?this.getRemoteOutboundRtpStatsId(o):void 0;const l=i&&s?$s(s,i.payloadType,o.id??o.uuid):void 0;if(i&&s&&l&&!n.has(l)){n.add(l);const g={type:\"codec\",id:l,timestamp:e,payloadType:i.payloadType,transportId:s,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,sdpFmtpLine:i.parameters};t.push(g)}const u={type:\"inbound-rtp\",id:this.getInboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:l,mid:this.sdesMid,trackIdentifier:o.id??o.uuid,packetsReceived:c?.packets_received??0,bytesReceived:c?.bytesReceived??0,headerBytesReceived:c?.headerBytesReceived??0,packetsLost:c?.packets_lost??0,jitter:c?.clockRate?c.jitter/c.clockRate:void 0,lastPacketReceivedTimestamp:c?.lastPacketReceivedTimestamp,remoteId:h,nackCount:this.nackCountBySsrc[o.ssrc]||void 0,pliCount:this.pliCountBySsrc[o.ssrc]||void 0};t.push(u);if(h){const g={type:\"remote-outbound-rtp\",id:this.getRemoteOutboundRtpStatsId(o),timestamp:e,ssrc:o.ssrc,kind:this.kind,transportId:s,codecId:u.codecId,localId:u.id,remoteTimestamp:this.remoteTimestampsBySsrc[o.ssrc],reportsSent:this.senderReportsReceivedBySsrc[o.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[o.ssrc],bytesSent:this.remoteOctetCountBySsrc[o.ssrc]};t.push(g)}}return t}async getStats(){const e=J();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return Wt(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){ir(\"pli not supported\",{mediaSsrc:e});return}if(this.stopped){return}ir(\"sendRtcpPLI\",{mediaSsrc:e});const t=new we({feedback:new Fe({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1;await this.dtlsTransport.sendRtcp([t])}catch(s){ir(s)}}handleRtcpPacket(e){switch(e.type){case ue.type:{const t=e;this.lastSRtimestamp[t.ssrc]=ao(t.senderInfo.ntpTimestamp);this.receiveLastSRTimestamp[t.ssrc]=Ys();this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1;this.remoteTimestampsBySsrc[t.ssrc]=qu(t.senderInfo.ntpTimestamp);this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount;this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;const s=this.trackBySSRC[e.ssrc];if(s){s.onReceiveRtcp.execute(e)}}break}this.onRtcp.execute(e)}handleRTP(e,t,s){if(this.stopped){return}const i=this.codecs[e.header.payloadType];if(!i){return}this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new To(i.clockRate);this.remoteStreams[e.header.ssrc].add(e);if(this.twccEnabled){const o=t[M.transportWideCC];if(o!==void 0){this.dtlsTransport.receiverTWCC.handleTWCC(o,e.header.ssrc)}}if(i.name.toLowerCase()===\"rtx\"){const o=this.ssrcByRtx[e.header.ssrc];const c=Ie(i.parameters??\"\");const d=this.codecs[c[\"apt\"]];if(e.payload.length<2)return;e=rd(e,d.payloadType,o);s=this.trackBySSRC[o]}let n;if(i.name.toLowerCase()===\"red\"){n=is.deSerialize(e.payload);if(!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())){return}}if(s?.kind===\"video\"&&this.nackEnabled){this.nack.addPacket(e)}if(s){if(n){if(s.kind===\"audio\"){const o=this.audioRedHandler.push(n,e);for(const c of o){s.onReceiveRtp.execute(c.clone(),t)}}}else{s.onReceiveRtp.execute(e.clone(),t)}}this.runRtcp().catch(o=>ir(\"rtcp failed\",o))}};var gi=b(\"webrtc/peer/media/router\");var bo=class{static{a(this,\"RtpRouter\")}constructor(){this.ssrcTable={};this.ridTable={};this.extIdUriMap={};this.routeRtp=e=>{const t=Vc(e.header.extensions,this.extIdUriMap);let s=this.ssrcTable[e.header.ssrc];const i=t[M.sdesRTPStreamID];if(typeof i===\"string\"){s=this.ridTable[i];if(s){s.latestRid=i;s.handleRtpByRid(e,i,t)}}else if(s){s.handleRtpBySsrc(e,t)}else{s=Object.values(this.ridTable).filter(c=>c instanceof nr).find(c=>c.trackBySSRC[e.header.ssrc]);if(s){gi(\"simulcast register receiver by ssrc\",e.header.ssrc);this.registerRtpReceiver(s,e.header.ssrc);s.handleRtpBySsrc(e,t)}else{}}if(!s){gi(\"ssrcReceiver not found\");return}const n=t[M.sdesMid];if(typeof n===\"string\"){s.sdesMid=n}const o=t[M.repairedRtpStreamId];if(typeof o===\"string\"){s.latestRepairedRid=o}};this.routeRtcp=e=>{const t=[];switch(e.type){case ue.type:{e=e;t.push(this.ssrcTable[e.ssrc])}break;case be.type:{e=e;e.reports.forEach(s=>{t.push(this.ssrcTable[s.ssrc])})}break;case We.type:break;case Z.type:{const s=e;if(s.feedback){t.push(this.ssrcTable[s.feedback.mediaSourceSsrc])}}break;case we.type:{const s=e;switch(s.feedback.count){case Ke.count:{const i=s.feedback;t.push(this.ssrcTable[i.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[s.feedback.mediaSsrc]||this.ssrcTable[s.feedback.senderSsrc])}}break}t.filter(s=>s).forEach(s=>s.handleRtcpPacket(e))}}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){gi(\"registerRtpReceiver\",t);this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){gi(\"registerRtpReceiverBySsrc\",t);t.encodings.filter(s=>s.ssrc!=void 0).forEach((s,i)=>{this.registerRtpReceiver(e.receiver,s.ssrc);e.addTrack(new Be({ssrc:s.ssrc,kind:e.kind,id:e.sender.trackId,remote:true,codec:So(e.kind,t.codecs[i],t.codecs)}));if(s.rtx){this.registerRtpReceiver(e.receiver,s.rtx.ssrc)}});t.headerExtensions.forEach(s=>{this.extIdUriMap[s.id]=s.uri})}registerRtpReceiverByRid(e,t,s){const[i]=s.codecs;gi(\"registerRtpReceiverByRid\",t);e.addTrack(new Be({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:true,codec:i}));this.ridTable[t.rid]=e.receiver}unregisterTransceiver(e){const t=[e.sender,e.receiver];for(const[s,i]of Object.entries(this.ssrcTable)){if(t.includes(i)){delete this.ssrcTable[Number(s)]}}for(const[s,i]of Object.entries(this.ridTable)){if(t.includes(i)){delete this.ridTable[s]}}}};var Si=require(\"node:crypto\");var uc=require(\"node:timers/promises\");var Co=class{static{a(this,\"SDPManager\")}constructor({cname:e,midSuffix:t,bundlePolicy:s,mLineReuse:i}){this.seenMid=new Set;this.cname=e;this.midSuffix=t??false;this.bundlePolicy=s;this.mLineReuse=i??\"compatible\"}get localDescription(){if(!this._localDescription){return void 0}return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription){return void 0}return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(e=>e.direction===\"inactive\")}createMediaDescriptionForTransceiver(e,t){const s=new $t(e.kind,9,\"UDP/TLS/RTP/SAVPF\",e.codecs.map(i=>i.payloadType));s.direction=t;s.msids=e.msids;s.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0};s.rtcpHost=\"0.0.0.0\";s.rtcpPort=9;s.rtcpMux=true;s.ssrc=[new sr({ssrc:e.sender.ssrc,cname:this.cname})];if(e.options.simulcast){s.simulcastParameters=e.options.simulcast.map(i=>new es(i))}if(s.rtp.codecs.find(i=>i.name.toLowerCase()===\"rtx\")){s.ssrc.push(new sr({ssrc:e.sender.rtxSsrc,cname:this.cname}));s.ssrcGroup=[new ft(\"FID\",[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]}this.addTransportDescription(s,e.dtlsTransport);return s}createRejectedMediaDescription(e,t){const s=e.fmt[0]??e.codecs[0]?.payloadType??0;const i=new $t(e.kind,0,e.profile,[s]);i.host=ma;i.direction=\"inactive\";i.rtp={codecs:e.codecs.filter(n=>n.payloadType?.toString()===s.toString()),headerExtensions:[],muxId:e.mid};i.rtcpMux=true;if(t){i.iceParams=t.iceTransport.localParameters;i.dtlsParams=t.localParameters}return i}createMediaDescriptionForSctp(e){const t=new $t(\"application\",ga,\"UDP/DTLS/SCTP\",[\"webrtc-datachannel\"]);t.sctpPort=e.port;t.rtp.muxId=e.mid;t.sctpCapabilities=e.getCapabilities();this.addTransportDescription(t,e.dtlsTransport);return t}addTransportDescription(e,t){const s=t.iceTransport;e.iceCandidates=s.localCandidates;e.iceCandidatesComplete=s.gatheringState===\"complete\";e.iceParams=s.localParameters;e.iceOptions=\"trickle\";e.host=ma;e.port=ga;if(e.direction===\"inactive\"){if(this.mLineReuse===\"aggressive\"){e.port=0}e.msids=[]}if(!e.dtlsParams){e.dtlsParams=t.localParameters;if(!e.dtlsParams.fingerprints){e.dtlsParams.fingerprints=t.localParameters.fingerprints}}}allocateMid(e=\"\"){let t;for(let s=0;;){t=(s++).toString()+e;if(!this.seenMid.has(t))break}this.seenMid.add(t);return t}parseSdp({sdp:e,isLocal:t,signalingState:s,type:i}){const n=ot.parse(e);this.validateDescription({description:n,isLocal:t,signalingState:s,type:i});n.type=i;return n}validateDescription({isLocal:e,signalingState:t,type:s}){if(e){if(s===\"offer\"){if(![\"stable\",\"have-local-offer\"].includes(t))throw _(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}else{if(s===\"offer\"){if(![\"stable\",\"have-remote-offer\",\"have-local-offer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle offer in signaling state\")}}else if([\"answer\",\"pranswer\"].includes(s)){if(![\"have-local-offer\",\"have-remote-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot handle answer in signaling state\")}}}}buildOfferSdp(e,t){const s=new ot;ic(\"offer\",s);const i=this.findLiveDtlsTransport(e,t);const n=this.currentLocalDescription?.media??[];const o=new Set;n.forEach((c,d)=>{const h=c.rtp.muxId;if(!h){return}if(c.kind===\"application\"){if(!t){throw new Error(\"sctpTransport not found\")}t.mLineIndex=d;s.media.push(this.createMediaDescriptionForSctp(t))}else{const l=e.find(u=>u.mid===h);if(!l){o.add(d);s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:h},i));return}l.mLineIndex=d;if(l.stopping||l.stopped){s.media.push(this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:h},this.liveTransportOr(l.dtlsTransport,i)));return}s.media.push(this.createMediaDescriptionForTransceiver(l,l.direction))}});for(const c of e.filter(d=>!d.stopping&&!d.stopped&&!s.media.find(h=>h.rtp.muxId===d.mid))){if(c.mid==void 0){c.mid=this.allocateMid(this.midSuffix?\"av\":\"\")}const d=this.createMediaDescriptionForTransceiver(c,c.direction);const h=c.mLineIndex;if(h!=void 0&&o.has(h)&&s.media[h]?.kind===c.kind){o.delete(h);s.media[h]=d}else{c.mLineIndex=s.media.length;s.media.push(d)}}if(t&&!s.media.find(c=>c.kind===\"application\")){t.mLineIndex=s.media.length;if(t.mid==void 0){t.mid=this.allocateMid(this.midSuffix?\"dc\":\"\")}s.media.push(this.createMediaDescriptionForSctp(t))}if(this.bundlePolicy!==\"disable\"){const c=s.media.filter(d=>d.port!==0).map(d=>d.rtp.muxId).filter(d=>d);if(c.length){const d=new ft(\"BUNDLE\",rl(c,this.negotiatedBundleTag));s.group.push(d)}}return s}liveTransportOr(e,t){return e&&e.state!==\"closed\"?e:t}findLiveDtlsTransport(e,t){return[...e.filter(s=>!s.stopped&&!s.pendingRejection).map(s=>s.dtlsTransport),t?.dtlsTransport,...e.map(s=>s.dtlsTransport)].find(s=>!!s&&s.state!==\"closed\")}get negotiatedBundleTag(){const e=[this.currentLocalDescription,this.currentRemoteDescription].find(t=>t?.type===\"answer\");return e?.group.find(t=>t.semantic===\"BUNDLE\")?.items[0]}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:s}){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(s)){throw new Error(\"createAnswer failed\")}if(!this._remoteDescription){throw new Error(\"wrong state\")}const i=new ot;ic(\"answer\",i);const n=this._remoteDescription;const o=this.findLiveDtlsTransport(e,t);for(const c of n.media){let d;let h;let l=true;if([\"audio\",\"video\"].includes(c.kind)){const u=e.find(g=>g.mid!=void 0&&g.mid===c.rtp.muxId);if(!u&&c.port!==0){throw new Error(`Transceiver with mid=${c.rtp.muxId} not found`)}if(!u||c.port===0||u.stopped||u.pendingRejection){l=false;d=this.liveTransportOr(u?.dtlsTransport,o);h=this.createRejectedMediaDescription({kind:c.kind,profile:c.profile,fmt:c.fmt,codecs:c.rtp.codecs,mid:c.rtp.muxId},d)}else{h=this.createMediaDescriptionForTransceiver(u,u.stopping?\"inactive\":oo(u.direction,u.offerDirection));d=u.dtlsTransport}}else if(c.kind===\"application\"){if(!t||!t.mid){throw new Error(\"sctpTransport not found\")}h=this.createMediaDescriptionForSctp(t);d=t.dtlsTransport}else{throw new Error(\"invalid kind\")}if(h.dtlsParams&&d){if(d.role===\"auto\"){h.dtlsParams.role=\"client\"}else{h.dtlsParams.role=d.role}}if(l&&c.simulcastParameters&&c.simulcastParameters.length>0){h.simulcastParameters=c.simulcastParameters.map(u=>({...u,direction:u.direction===\"send\"?\"recv\":\"send\"}))}i.media.push(h)}if(this.bundlePolicy!==\"disable\"){i.group.push(...this.buildAnswerBundleGroups(n,i))}return i}buildAnswerBundleGroups(e,t){const s=new Set(t.media.filter(n=>n.port!==0&&n.rtp.muxId).map(n=>n.rtp.muxId));const i=this.negotiatedBundleTag;return e.group.filter(n=>n.semantic===\"BUNDLE\").map(n=>n.items.filter((o,c,d)=>{return s.has(o)&&d.indexOf(o)===c})).filter(n=>n.length>0).map(n=>new ft(\"BUNDLE\",rl(n,i)))}assertRemoteAnswerCodecs(e){if(![\"answer\",\"pranswer\"].includes(e.type)){return}const t=this.pendingLocalDescription;if(!t){return}e.media.forEach((s,i)=>{if(![\"audio\",\"video\"].includes(s.kind)||s.port===0){return}const n=t.media[i];if(!n||n.port===0||n.kind!==s.kind){return}const o=s.rtp.codecs.some(c=>c.name.toLowerCase()!==\"rtx\"&&n.rtp.codecs.some(d=>d.mimeType.toLowerCase()===c.mimeType.toLowerCase()));if(!o){throw _(\"InvalidAccessError\",`No common codec for m-line ${i} (mid=${s.rtp.muxId}) in remote ${e.type}`)}})}assertBundlePreserved(e){if(e.type!==\"offer\"||this.bundlePolicy===\"disable\"){return}const t=[this.currentLocalDescription,this.currentRemoteDescription].find(i=>i?.type===\"answer\")?.group.filter(i=>i.semantic===\"BUNDLE\")??[];const s=e.group.filter(i=>i.semantic===\"BUNDLE\");for(const i of t){let n;for(const o of i.items){const c=e.media.find(h=>h.rtp.muxId===o);if(!c||c.port===0){continue}const d=s.find(h=>h.items.includes(o));if(!d){throw _(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be preserved by the remote offer`)}n??=d;if(d!==n){throw _(\"InvalidAccessError\",`BUNDLE transport of mid=${o} cannot be split into another BUNDLE group by the remote offer`)}}}}setLocalDescription(e){if(e.type===\"offer\"||e.type===\"pranswer\"){this.pendingLocalDescription=e;return}this.currentLocalDescription=e;if(this.pendingRemoteDescription){this.currentRemoteDescription=this.pendingRemoteDescription}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type){throw new Error(\"invalid sessionDescription\")}if(e.type===\"rollback\"){if(![\"have-remote-offer\",\"have-local-pranswer\"].includes(t)){throw _(\"InvalidStateError\",\"Cannot rollback remote description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0;return}if(!e.sdp){throw new Error(\"invalid sessionDescription\")}const s=this.parseSdp({sdp:e.sdp,isLocal:false,signalingState:t,type:e.type});this.assertRemoteAnswerCodecs(s);this.assertBundlePreserved(s);if(s.type===\"offer\"||s.type===\"pranswer\"){this.pendingRemoteDescription=s}else{if(this.pendingLocalDescription){this.currentLocalDescription=this.pendingLocalDescription}this.currentRemoteDescription=s;this.pendingRemoteDescription=void 0;this.pendingLocalDescription=void 0}return s}rollbackLocalDescription(e){if(![\"have-local-offer\",\"have-local-pranswer\"].includes(e)){throw _(\"InvalidStateError\",\"Cannot rollback local description in signaling state\")}this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){const e=this._remoteDescription;if(!e){return void 0}const t=e.group.find(s=>s.semantic===\"BUNDLE\"&&this.bundlePolicy!==\"disable\");return t}setLocal(e,t,s){const i=new Map(t.map(c=>[c?.mLineIndex,c]));const n=t.find(c=>c?.dtlsTransport)?.dtlsTransport??s?.dtlsTransport;e.media.forEach((c,d)=>{if(![\"audio\",\"video\"].includes(c.kind)){return}const h=t.find(g=>g?.mid!=void 0&&g.mid===c.rtp.muxId)??i.get(d);if(c.port===0){const g=h&&!h.stopping&&!h.stopped&&!h.pendingRejection;if(!g){return}}const l=h?.dtlsTransport??n;if(!l){throw new Error(`dtls transport not found for media index ${d}`)}const u=c.port;this.addTransportDescription(c,l);if(u===0){c.port=0}});const o=e.media.find(c=>c.kind===\"application\");if(s&&o){this.addTransportDescription(o,s.dtlsTransport)}this.setLocalDescription(e)}};function rl(r,e){if(!e||!r.includes(e)){return r}return[e,...r.filter(t=>t!==e)]}a(rl,\"orderBundleMids\");var Qt=b(\"webrtc/peer/media/rtpSender\");var il=128;var hc=256;var nl=.85;function Nm(r){if(r===true){return{enabled:true,maxLength:hc}}if(r==void 0||r===false){return{enabled:false,maxLength:hc}}const e=typeof r.maxLength===\"number\"&&Number.isFinite(r.maxLength)&&r.maxLength>=1?Math.floor(r.maxLength):hc;return{enabled:r.enabled??true,maxLength:e}}a(Nm,\"resolvePendingRtpOptions\");function Mm(r,e,t,s,i){return{seqOffset:j(j(r,1),-t),timestampOffset:Ae(Ae(e,i),-s)}}a(Mm,\"freezeRtpContinuityOffsets\");var Eo=class{static{a(this,\"RTCRtpSender\")}constructor(e,t={}){this.trackOrKind=e;this.type=\"sender\";this.ssrc=(0,Si.randomBytes)(4).readUInt32BE(0);this.rtxSsrc=(0,Si.randomBytes)(4).readUInt32BE(0);this.trackId=(0,Si.randomUUID)().toString();this.onReady=new w;this.onRtcp=new w;this.onPictureLossIndication=new w;this.onGenericNack=new w;this.onStreamsChanged=new w;this.rtxSequenceNumber=_o();this._redDistance=2;this.redEncoder=new Hi(this._redDistance);this.headerExtensions=[];this.sendEncodings=[{}];this.rtpTimestamp=0;this.octetCount=0;this.packetCount=0;this.headerBytesSent=0;this.totalRoundTripTime=0;this.roundTripTimeMeasurements=0;this.retransmittedPacketsSent=0;this.retransmittedBytesSent=0;this.nackCount=0;this.pliCount=0;this.firCount=0;this.receiverEstimatedMaxBitrate=0n;this.timestampOffset=0;this.seqOffset=0;this.rtpContinuityPending=false;this.pendingTimestampStep=1;this.rtpCache=[];this.pendingRtp=[];this.drainingPendingRtp=false;this.negotiatedCodecs=[];this.dtlsDisposer=[];this.track=null;this.streamIds=[];this.stopped=false;this.rtcpRunning=false;this.rtcpCancel=new AbortController;const s=Nm(t.pendingRtp);this.pendingRtpEnabled=s.enabled;this.pendingRtpMaxLength=s.maxLength;this.kind=typeof this.trackOrKind===\"string\"?this.trackOrKind:this.trackOrKind.kind;if(typeof e!==\"string\"){this.registerTrack(e)}}get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){if(this.dtlsTransport){this.dtlsDisposer.forEach(t=>t())}this.dtlsTransport=e;this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(t=>{if(t===\"connected\"){this.onReady.execute();void this.drainPendingRtp()}}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e;this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname;this.mid=e.muxId;this.headerExtensions=e.headerExtensions;this.rtpStreamId=e.rtpStreamId??this.rtpStreamId;this.repairedRtpStreamId=e.repairedRtpStreamId;this.negotiatedCodecs=[...e.codecs];this.selectCodec(this.track?Le(this.track):void 0);if(this.track){this.track.codec=this.codec}void this.drainPendingRtp()}selectCodec(e){const t=this.negotiatedCodecs;const s=a(o=>{if(o?.name.toLowerCase()!==\"red\")return o;const c=Number((o.parameters??\"\").split(\"/\")[0]);return t.find(d=>![\"red\",\"rtx\"].includes(d.name.toLowerCase())&&d.payloadType===c)},\"primaryOf\");const i=a(o=>{const c=s(o);return!!c&&(!e||e.some(d=>rr(d,c)))},\"compatible\");const n=t.find(o=>o.name.toLowerCase()!==\"rtx\")??t[0];this.codec=t.find(o=>o.name.toLowerCase()!==\"rtx\"&&i(o))??n;this.sendPrimaryCodec=s(this.codec);this.rtxPayloadType=void 0;this.redRedundantPayloadType=void 0;t.forEach(o=>{const c=Ie(o.parameters??\"\");if(o.name.toLowerCase()===\"rtx\"&&this.sendPrimaryCodec?.payloadType===c[\"apt\"]){this.rtxPayloadType=o.payloadType}});if(this.codec?.name.toLowerCase()===\"red\"&&this.sendPrimaryCodec!=void 0){this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType}}canSendRtp(){return!this.stopped&&this.dtlsTransport?.state===\"connected\"&&!!this.codec}settlePendingRtp(e,t){if(t==void 0){e.resolve();return}e.reject(t)}discardPendingRtp(){const e=this.pendingRtp.splice(0);for(const t of e){this.settlePendingRtp(t)}}enqueuePendingRtp(e,t,s){const i=Buffer.isBuffer(e)?W.deSerialize(e):e.clone();this.pendingRtp.push({packet:i,resolve:t,reject:s});while(this.pendingRtp.length>this.pendingRtpMaxLength){const n=this.pendingRtp.shift();if(n){this.settlePendingRtp(n)}}}async drainPendingRtp(){if(this.drainingPendingRtp){return}this.drainingPendingRtp=true;try{while(this.pendingRtp.length>0&&this.canSendRtp()){const e=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(e);continue}try{await this.dispatchRtp(e.packet);this.settlePendingRtp(e)}catch(t){this.settlePendingRtp(e,t)}}}finally{this.drainingPendingRtp=false}if(this.pendingRtp.length>0&&this.canSendRtp()){await this.drainPendingRtp()}}registerTrack(e){if(e.stopped)throw new Error(\"track is ended\");Et(e);if(this.disposeTrack){this.disposeTrack()}e.id=this.trackId;const{unSubscribe:t}=e.onReceiveRtp.subscribe(ye((i,n)=>e.remote?this.sendRtp(this.relayedRtp(i,n),true):this.sendRtp(i),i=>Qt(\"send rtp failed\",i)));const{unSubscribe:s}=e.onSourceChanged.subscribe(i=>{this.replaceRTP(i)});this.track=e;this.disposeTrack=()=>{t();s()};if(this.codec){e.codec=this.codec}}relayedRtp(e,t={}){const s=e.clone();s.header.extensions=this.headerExtensions.flatMap(i=>{switch(i.uri){case M.audioLevelIndication:{const n=t[i.uri];return n?[{id:i.id,payload:Buffer.from([(n.v?128:0)|n.level&127])}]:[]}case M.videoOrientation:{const n=t[i.uri];return n?[{id:i.id,payload:Buffer.from([n.c<<3|n.f<<2|n.r1<<1|n.r0])}]:[]}default:return[]}});return s}setStreams(e=[]){const t=[...new Set(e.map(i=>i.id))];const s=t.join(\"\\n\")!==(this.streamIds??[]).join(\"\\n\");this.streamIds=t;if(s)this.onStreamsChanged.execute()}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(s=>({...s})):[{}];const t=this.sendEncodings.find(s=>typeof s.rid===\"string\")?.rid;if(typeof t===\"string\"){this.rtpStreamId=t}}async replaceTrack(e){if(e===null){this.detachTrack();return}if(e.stopped)throw new Error(\"track is ended\");Et(e);const t=Le(e);if(this.sendPrimaryCodec!=void 0&&t!=void 0&&!this.negotiatedCodecs.some(s=>![\"red\",\"rtx\"].includes(s.name.toLowerCase())&&t.some(i=>rr(i,s)))){throw _(\"InvalidModificationError\",`Track codec ${t.map(s=>s.mimeType).join(\", \")} is incompatible with negotiated codecs ${this.negotiatedCodecs.map(s=>s.mimeType).join(\", \")}`)}if(this.negotiatedCodecs.length)this.selectCodec(t);if(this.sequenceNumber!=void 0){this.scheduleRtpContinuity()}this.registerTrack(e);Qt(\"replaceTrack\",\"ssrc\",e.ssrc,\"rid\",e.rid)}detachTrack(){this.rtpContinuityPending=false;this.discardPendingRtp();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}this.track=null}stop({keepTrack:e=false}={}){this.stopped=true;this.rtpContinuityPending=false;this.discardPendingRtp();this.rtcpRunning=false;this.rtcpCancel.abort();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}if(!e){this.track=null}}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await(0,uc.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=this.sentAtEpochMs===void 0?0n:zu(this.sentAtEpochMs);const t=[new ue({ssrc:this.ssrc,senderInfo:new wr({ntpTimestamp:e,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=ao(e);this.lastSentSRTimestamp=Ys();if(this.cname){t.push(new We({chunks:[new yr({source:this.ssrc,items:[new Tr({type:1,text:this.cname})]})]}))}try{await this.dtlsTransport.sendRtcp(t)}catch(s){Qt(\"sendRtcp failed\",s);await(0,uc.setTimeout)(500+Math.random()*1e3)}}}catch(e){Qt(\"rtcp loop ended\",e)}}async sendRtp(e,t=false){if(this.stopped){return}if(!this.pendingRtpEnabled){if(!this.canSendRtp()){return}await this.dispatchRtp(e,t);return}await new Promise((s,i)=>{this.enqueuePendingRtp(e,s,i);void this.drainPendingRtp()})}replaceRTP(e,t=false,s=1){this.scheduleRtpContinuity(s);Qt(\"replaceRTP\",this.sequenceNumber,e.sequenceNumber,t,s)}scheduleRtpContinuity(e=1){this.rtpContinuityPending=true;this.pendingTimestampStep=e;this.rtpCache=[]}async dispatchRtp(e,t=false){if(!this.canSendRtp()){return}const s=this.codec;if(!s){return}e=Buffer.isBuffer(e)?W.deSerialize(e):t?e:e.clone();const{header:i,payload:n}=e;const o=i.sequenceNumber;const c=i.timestamp;if(this.rtpContinuityPending){if(this.sequenceNumber!=void 0&&this.timestamp!=void 0){const p=Mm(this.sequenceNumber,this.timestamp,o,c,this.pendingTimestampStep);this.seqOffset=p.seqOffset;this.timestampOffset=p.timestampOffset}this.rtpContinuityPending=false;this.pendingTimestampStep=1}i.ssrc=this.ssrc;i.payloadType=s.payloadType;i.timestamp=Ae(i.timestamp,this.timestampOffset);i.sequenceNumber=j(i.sequenceNumber,this.seqOffset);this.timestamp=i.timestamp;this.sequenceNumber=i.sequenceNumber;const d=performance.timeOrigin+performance.now();let h;const l=[];for(const p of this.headerExtensions){let f;switch(p.uri){case M.sdesMid:if(this.mid)f=Yc(this.mid);break;case M.sdesRTPStreamID:if(this.rtpStreamId)f=Qc(this.rtpStreamId);break;case M.repairedRtpStreamId:if(this.repairedRtpStreamId)f=Xc(this.repairedRtpStreamId);break;case M.transportWideCC:h=this.nextTransportSequenceNumber();f=Ko(h);break;case M.absSendTime:f=Wa(d);break}if(f)l.push({id:p.id,payload:f})}for(const p of i.extensions){let f;for(const y of l){if(y.id===p.id){f=y;break}}if(f){f.payload=p.payload}else{l.push(p)}}for(let p=1;p<l.length;p++){if(l[p-1].id>l[p].id){l.sort((f,y)=>f.id-y.id);break}}i.extensions=l;this.sentAtEpochMs=d;this.rtpTimestamp=i.timestamp;this.octetCount+=n.length;this.headerBytesSent+=i.serializeSize;this.packetCount=Ae(this.packetCount,1);this.rtpCache[i.sequenceNumber%il]=e;let u=n;if(this.redRedundantPayloadType){this.redEncoder.push({block:u,timestamp:i.timestamp,blockPT:this.redRedundantPayloadType});const p=this.redEncoder.build();u=p.serialize()}const g=Vs();const S=await this.dtlsTransport.sendRtp(u,i);if(!this.rtcpRunning&&!this.stopped)this.runRtcp().catch(p=>Qt(\"rtcp failed\",p));if(h!==void 0){this.packetSent(h,S,g)}}nextTransportSequenceNumber(){this.dtlsTransport.transportSequenceNumber=j(this.dtlsTransport.transportSequenceNumber,1);return this.dtlsTransport.transportSequenceNumber}packetSent(e,t,s){const i={wideSeq:e,size:t,sendingAtMs:s,sentAtMs:Vs()};this.dtlsTransport.senderBWE.rtpPacketSent(i)}async resendRtp(e){let t;const s=e.header.extensions.map(c=>{const d=this.headerExtensions.find(h=>h.id===c.id)?.uri;switch(d){case M.transportWideCC:t=this.nextTransportSequenceNumber();return{id:c.id,payload:Ko(t)};case M.absSendTime:return{id:c.id,payload:Wa(performance.timeOrigin+performance.now())};default:return c}});let i=new W(new ee({...e.header,extensions:s}),e.payload);if(this.rtxPayloadType!=void 0){i=id(i,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc);this.rtxSequenceNumber=j(this.rtxSequenceNumber,1)}this.retransmittedPacketsSent++;this.retransmittedBytesSent+=i.payload.length;this.headerBytesSent+=i.header.serializeSize;const n=Vs();const o=await this.dtlsTransport.sendRtp(i.payload,i.header);if(t!==void 0){this.packetSent(t,o,n)}}handleRtcpPacket(e){switch(e.type){case ue.type:case be.type:{const t=e;t.reports.filter(s=>s.ssrc===this.ssrc).forEach(s=>{this.remotePacketsLost=s.packetsLost;this.remoteFractionLost=s.fractionLost/256;if(this.lastSRtimestamp===s.lsr&&s.dlsr){if(this.lastSentSRTimestamp){const i=Ys()-this.lastSentSRTimestamp-s.dlsr/65536;this.totalRoundTripTime+=i;this.roundTripTimeMeasurements++;if(this.rtt===void 0){this.rtt=i}else{this.rtt=nl*this.rtt+(1-nl)*i}}}})}break;case Z.type:{const t=e;switch(t.feedback.count){case Ge.count:{const s=t.feedback;this.nackCount++;s.lost.forEach(ye(async i=>{const n=this.rtpCache[i%il];if(n&&n.header.sequenceNumber===i){await this.resendRtp(n)}},i=>Qt(\"retransmission failed\",i)));this.onGenericNack.execute(s)}break}}break;case we.type:{const t=e;switch(t.feedback.count){case Ke.count:{const s=t.feedback;this.receiverEstimatedMaxBitrate=s.bitrate}break;case Fe.count:{this.pliCount++;this.onPictureLossIndication.execute()}break}}break}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){if(e.encodings){this.setSendEncodings(e.encodings)}}get outboundRtpStatsId(){return D(\"outbound-rtp\",this.trackId)}get mediaSourceStatsId(){return D(\"media-source\",this.trackId)}get remoteInboundRtpStatsId(){return D(\"remote-inbound-rtp\",this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){const t=[];const s=this.dtlsTransport?D(\"transport\",this.dtlsTransport.id):void 0;const i=this.codec&&s?$s(s,this.codec.payloadType,this.trackId):void 0;const n={type:\"outbound-rtp\",id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:i,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};t.push(n);if(this.track){const o={type:\"media-source\",id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(o)}if(this.codec&&s){const o={type:\"codec\",id:i,timestamp:e,payloadType:this.codec.payloadType,transportId:s,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(o)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){const o={type:\"remote-inbound-rtp\",id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:s,codecId:n.codecId,localId:n.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(o)}return t}async getStats(){const e=J();const t=this.collectStats(e);if(this.dtlsTransport){t.push(...await this.dtlsTransport.getStats(e))}return Wt(t,this.getStatsRootIds())}};var ol=b(\"webrtc/peer/transceiverManager\");function Om(r){if(!r||r.length<2){return void 0}const e=r.map(t=>t.rid).filter(t=>typeof t===\"string\"&&t.length>0);if(e.length<2){return void 0}return e.map(t=>({rid:t,direction:\"send\"}))}a(Om,\"simulcastFromSendEncodings\");var Ro=class{static{a(this,\"TransceiverManager\")}constructor(e,t,s){this.cname=e;this.config=t;this.router=s;this.transceivers=[];this.watched=new WeakSet;this.stableState=new Map;this.onTransceiverAdded=new w;this.onRemoteTransceiverAdded=new w;this.onTrack=new w;this.onNegotiationNeeded=new w}getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.watchTransceiver(e);this.transceivers.push(e)}replaceTransceiver(e,t){this.watchTransceiver(e);this.transceivers[t]=e}unwatchTransceiver(e){this.watched.delete(e);e.onRelease.allUnsubscribe();e.onStopRequested.allUnsubscribe();e.onDirectionChanged.allUnsubscribe();e.sender.onStreamsChanged.allUnsubscribe()}watchTransceiver(e){if(this.watched.has(e)){return}this.watched.add(e);e.onRelease.subscribe(()=>{this.router.unregisterTransceiver(e)});e.onStopRequested.subscribe(()=>{if(!e.stopped){this.onNegotiationNeeded.execute()}});e.onDirectionChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()});e.sender.onStreamsChanged.subscribe(()=>{if(!e.stopping&&!e.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(e){return this.transceivers.find(t=>t.stopped&&t.kind===e&&t.mLineIndex!=void 0&&!this.transceivers.some(s=>s!==t&&s.mLineIndex===t.mLineIndex))}takeOverMLine(e,t){const s=this.transceivers.indexOf(e);t.mLineIndex=e.mLineIndex;e.mid=null;e.mLineIndex=void 0;this.unwatchTransceiver(e);this.replaceTransceiver(t,s)}associateMLine(e,t){const s=this.transceivers.find(i=>i!==e&&i.stopped&&i.mLineIndex===t);if(!s){return}this.transceivers.splice(this.transceivers.indexOf(e),1);this.takeOverMLine(s,e)}releaseUnassociatedReservations(e,t){for(const s of this.transceivers){if(!e.has(s)&&s.mid==null&&s.mLineIndex!=void 0&&s.mLineIndex<t){s.mLineIndex=void 0}}}addTransceiver(e,t,s={},{remoteMLineIndex:i}={}){const n=typeof e===\"string\"?e:e.kind;const o=s.direction||\"sendrecv\";if(typeof e!==\"string\"){Et(e);Yt({kind:n,configured:this.filterCodecsByDirection(n,o),source:Le(e),preferences:void 0})}const c=new Eo(e,{pendingRtp:this.config.pendingRtp});const d=new nr(this.config,n,c.ssrc);const h=new so(n,t,d,c,o);h.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()});h.options={...s,simulcast:s.simulcast??Om(s.sendEncodings)};h.sender.setStreams(s.streams??[]);h.sender.setSendEncodings((s.sendEncodings??[]).map(u=>({...u})));this.router.registerRtpSender(h.sender);const l=i==void 0?this.findReusableTransceiver(n):this.transceivers.find(u=>u.stopped&&u.mLineIndex===i);if(l){this.takeOverMLine(l,h)}else{this.pushTransceiver(h)}if(i!=void 0){this.remoteOfferSnapshot?.remoteCreated.add(h)}this.onTransceiverAdded.execute(h);return h}reusableForTrack(e,t){return e.sender.track==void 0&&e.kind===t&&!e.usedForSender&&!e.stopping&&!e.stopped&&!e.rejected&&!e.pendingRejection}addTrack(e,t=[],s){if(this.getSenders().find(c=>c.track?.uuid===e.uuid)){throw _(\"InvalidAccessError\",\"Track already added\")}const i=a(c=>this.reusableForTrack(c,e.kind)&&(s===void 0||c===s),\"reusableForTrack\");const n=s===null?void 0:this.transceivers.find(c=>i(c)&&zt.includes(c.direction));if(n){this.validateTrackForTransceiver(e,n);const c=n.sender;c.setStreams(t);c.registerTrack(e);n.options={...n.options,streams:t};n.codecs=[];return n}const o=s===null?void 0:this.transceivers.find(c=>i(c)&&!zt.includes(c.direction));if(o){const c=o.direction===\"recvonly\"?\"sendrecv\":o.direction===\"inactive\"?\"sendonly\":o.direction;this.validateTrackForTransceiver(e,o,c);const d=o.sender;d.setStreams(t);d.registerTrack(e);o.options={...o.options,streams:t};switch(o.direction){case\"recvonly\":o.setDirection(\"sendrecv\");break;case\"inactive\":o.setDirection(\"sendonly\");break}o.codecs=[];return o}else{const c=this.addTransceiver(e,void 0,{direction:\"sendrecv\",streams:t});c.addedByAddTrack=true;return c}}removeTrack(e){if(!this.getSenders().find(({ssrc:s})=>e.ssrc===s)){throw _(\"InvalidAccessError\",\"Sender does not exist\")}const t=this.transceivers.find(({sender:{ssrc:s}})=>e.ssrc===s);if(!t)throw new Error(\"No matching transceiver found\");if(t.stopping||t.stopped){return false}if(e.track==void 0){return false}e.detachTrack();if(t.direction===\"sendrecv\"){t.setDirection(\"recvonly\")}else if(t.direction===\"sendonly\"){t.setDirection(\"inactive\")}return true}assignTransceiverCodecs(e){const t=this.filterCodecsByDirection(e.kind,e.direction);e.codecs=Yt({kind:e.kind,configured:t,source:Le(e.sender.track),preferences:e.codecPreferences});e.codecPreferencesNeedResolution=false}filterCodecsByDirection(e,t){return this.config.codecs[e].filter(s=>{switch(s.direction){case\"recvonly\":{if(Nh.includes(t))return true;return false}case\"sendonly\":{if(zt.includes(t))return true;return false}case\"sendrecv\":{if([qa,za,Ha].includes(t))return true;return false}case\"all\":{return true}default:return false}})}validateTrackForTransceiver(e,t,s=t.direction){Et(e);Yt({kind:e.kind,configured:this.filterCodecsByDirection(e.kind,s),source:Le(e),preferences:t.codecPreferences})}getLocalRtpParams(e){if(e.mid==void 0)throw new Error(\"mid not assigned\");const t={codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:true}};return t}getRemoteRtpParams(e,t){const s={muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((i,n)=>{if(n.name.toLowerCase()===\"rtx\"){const o=Ie(n.parameters??\"\");const c=i[o[\"apt\"]];if(c&&e.ssrc.length===2){c.rtx=new Di({ssrc:e.ssrc[1].ssrc})}return i}i[n.payloadType]=new Ni({ssrc:e.ssrc[0]?.ssrc,payloadType:n.payloadType});return i},{}))};return s}resyncAnswerCodecs(e,t){this.refreshAnswerCodecs(e,t);const s=this.getLocalRtpParams(e);e.sender.prepareSend(s);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const i=this.getRemoteRtpParams(t,e);for(const n of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,n,i)}e.receiver.resyncCodecs(i);this.router.registerRtpReceiverBySsrc(e,i)}}resolveRemoteCodecSet(e,t,s,i){const n=a(l=>l.name.toLowerCase(),\"codecName\");const o=a(l=>(l.parameters??\"\").split(\"/\").map(Number).filter(u=>!Number.isNaN(u)),\"redPayloadTypes\");const c=new Map;const d=new Set;for(const l of e){if([\"red\",\"rtx\"].includes(n(l)))continue;const u=t.rtp.codecs.find(g=>!d.has(g)&&g.mimeType.toLowerCase()===l.mimeType.toLowerCase()&&(i==void 0||i.some(S=>rr(S,g))));if(u){c.set(l,u);d.add(u)}}const h=e.flatMap(l=>{if(n(l)===\"red\"){const f=o(l).flatMap(m=>{const T=e.find(E=>E.payloadType===m);const C=T?c.get(T):void 0;return C?[C.payloadType]:[]});const y=t.rtp.codecs.find(m=>{if(n(m)!==\"red\"||d.has(m))return false;const T=o(m);return T.length===f.length&&T.every((C,E)=>C===f[E])});if(!y)return[];d.add(y);return[y]}if(n(l)!==\"rtx\"){const f=c.get(l);return f?[f]:[]}const u=Ie(l.parameters??\"\").apt;const g=e.find(f=>f.payloadType===u);if(!g)return[];const S=c.get(g);if(!S)return[];const p=t.rtp.codecs.find(f=>{if(n(f)!==\"rtx\"||d.has(f)){return false}return Ie(f.parameters??\"\").apt===S.payloadType});if(!p)return[];d.add(p);return[p]});if(s===\"remote\"){const l=new Map(t.rtp.codecs.map((u,g)=>[u,g]));h.sort((u,g)=>l.get(u)-l.get(g))}if(h.length===0){throw _(\"NotSupportedError\",\"No compatible codec remains after remote negotiation.\")}return h}refreshAnswerCodecs(e,t){const s=this.config.codecs[t.kind]||[];const i=Le(e.sender.track);Yt({kind:t.kind,configured:s,source:i,preferences:e.codecPreferences});const n=oc(s,i,e.codecPreferences);e.codecs=this.resolveRemoteCodecSet(n,t,\"local\",i);e.codecPreferencesNeedResolution=false;ol(\"negotiated codecs\",e.codecs)}planRemoteRtpCodecs(e,t){const s=new Map;const i=e.type===\"offer\";for(const[n,o]of e.media.entries()){if(![\"audio\",\"video\"].includes(o.kind))continue;const c=t(o,n);if(o.port===0||c?.stopped||c?.stopping){s.set(n,[]);continue}const d=Le(c?.sender.track);const h=this.config.codecs[o.kind]||[];const l=i?h:c?.pendingLocalOfferCodecs||[];if(!Qu(l,o.rtp.codecs)){s.set(n,[]);continue}if(i){Yt({kind:o.kind,configured:h,source:d,preferences:c?.codecPreferences})}const u=this.resolveRemoteCodecSet(i?oc(h,d,c?.codecPreferences):l,o,i?\"local\":\"remote\",d);if(d!=void 0){Yt({kind:o.kind,configured:u,source:d,preferences:void 0})}s.set(n,u)}return s}setRemoteRTP(e,t,s,i,n){if(!e.mid){e.mid=t.rtp.muxId??null}e.mLineIndex=i;if(s===\"answer\")e.pendingLocalOfferCodecs=void 0;if(e.stopped){return false}if(e.stopping){if(s===\"answer\"&&t.port===0){e.commitStopped({rejected:false})}return false}ol(\"negotiated codecs\",n);if(t.port===0||n.length===0){if(s===\"answer\"){e.commitStopped({rejected:true})}else{e.pendingRejection=true}return false}e.pendingRejection=false;e.codecs=n;e.headerExtensions=t.rtp.headerExtensions.filter(h=>(this.config.headerExtensions[t.kind]||[]).find(l=>l.uri===h.uri));const o=t.direction??\"inactive\";const c=Uu(o);if([\"answer\",\"pranswer\"].includes(s)){e.setCurrentDirection(c)}else{e.offerDirection=c}const d=this.getLocalRtpParams(e);e.sender.prepareSend(d);if([\"recvonly\",\"sendrecv\"].includes(e.direction)){const h=this.getRemoteRtpParams(t,e);for(const l of t.simulcastParameters){this.router.registerRtpReceiverByRid(e,l,h)}e.receiver.resyncCodecs(h);this.router.registerRtpReceiverBySsrc(e,h)}if([\"sendonly\",\"sendrecv\"].includes(o)){const h=[...new Set(t.msids.map(u=>u.split(\" \")[0]))];const l=t.msids[0]?.split(\" \")[1];e.receiver.remoteStreamId=h[0];e.receiver.remoteStreamIds=h;e.receiver.remoteTrackId=l;if(!e.firedReceiving){e.firedReceiving=true;this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:h.map(u=>new us({id:u,tracks:[e.receiver.track]}))})}}else{e.firedReceiving=false}return true}markStable(){this.stableState=new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex}]))}rollbackLocalOffer(){for(const e of this.transceivers){const t=this.stableState.get(e);e.mid=t?.mid??null;e.mLineIndex=t?.mLineIndex}}beginRemoteOffer(){if(this.remoteOfferSnapshot){return}this.remoteOfferSnapshot={transceivers:[...this.transceivers],remoteCreated:new Set,states:new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex,pendingRejection:e.pendingRejection,firedReceiving:e.firedReceiving}]))}}commitRemoteOffer(){this.remoteOfferSnapshot=void 0;for(const e of this.transceivers){if(e.pendingRejection){e.commitStopped({rejected:true})}}}rollbackRemoteOffer(){const e=this.remoteOfferSnapshot;this.remoteOfferSnapshot=void 0;if(!e){return}for(const t of this.transceivers){if(e.states.has(t)){continue}if(!e.remoteCreated.has(t)||t.sender.track){t.mid=null;t.mLineIndex=void 0;e.transceivers.push(t);continue}t.forceStop();this.unwatchTransceiver(t)}this.transceivers.splice(0,this.transceivers.length,...e.transceivers);e.transceivers.forEach(t=>this.watchTransceiver(t));for(const[t,s]of e.states){t.mid=s.mid;t.mLineIndex=s.mLineIndex;t.pendingRejection=s.pendingRejection;t.firedReceiving=s.firedReceiving}}settleStoppingTransceivers(e){for(const t of this.transceivers){if(!t.stopping||t.stopped){continue}if(t.mid==void 0||!e.has(t.mid)){t.commitStopped({rejected:false})}}return this.transceivers.some(t=>t.stopping&&!t.stopped)}collectStats(e){const t=[];for(const s of this.transceivers){if(s.sender){t.push(...s.sender.collectStats(e))}if(s.receiver){t.push(...s.receiver.collectStats(e))}const i=s.collectCodecStats(e);if(i){t.push(...i)}}return t}getStatsRootIds(e){if(!e){return[]}const t=[];for(const s of this.transceivers){if(s.sender.track===e){t.push(...s.sender.getStatsRootIds())}if(s.receiver.tracks.includes(e)){t.push(...s.receiver.getStatsRootIds(e))}}return t}close(){for(const e of this.transceivers){e.forceStop();this.unwatchTransceiver(e)}this.onTransceiverAdded.allUnsubscribe();this.onRemoteTransceiverAdded.allUnsubscribe();this.onTrack.allUnsubscribe();this.onNegotiationNeeded.allUnsubscribe()}};var Um=b(\"webrtc/peer/sctpManager\");var xo=class{static{a(this,\"SctpTransportManager\")}constructor(){this.dataChannelsOpened=0;this.dataChannelsClosed=0;this.dataChannels=[];this.onDataChannel=new w}createSctpTransport(e,t){const s=new mo(5e3,e,t);s.mid=void 0;s.onDataChannel.subscribe(i=>{this.dataChannelsOpened++;this.dataChannels.push(i);this.onDataChannel.execute(i)});this.sctpTransport=s;return s}createDataChannel(e,t={}){const s=al(t.maxPacketLifeTime,\"maxPacketLifeTime\");const i=al(t.maxRetransmits,\"maxRetransmits\");const n={protocol:\"\",ordered:true,negotiated:false};const o={...n,...t,maxPacketLifeTime:s,maxRetransmits:i};if(o.maxPacketLifeTime!=null&&o.maxRetransmits!=null){throw Re(\"maxPacketLifeTime and maxRetransmits cannot both be set\")}if(!this.sctpTransport){this.sctpTransport=this.createSctpTransport()}const c=new Zt({id:o.id,label:e,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits,negotiated:o.negotiated,ordered:o.ordered,protocol:o.protocol});const d=new Jt(this.sctpTransport,c);this.dataChannelsOpened++;this.dataChannels.push(d);d.stateChange.subscribe(h=>{if(h===\"closed\"){this.dataChannelsClosed++;const l=this.dataChannels.indexOf(d);if(l!==-1){this.dataChannels.splice(l,1)}}});return d}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort){return}await this.sctpTransport.start(this.sctpRemotePort);await this.sctpTransport.sctp.stateChanged.connected.asPromise();Um(\"sctp connected\")}setRemoteSCTP(e,t){if(!this.sctpTransport){return}this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize);this.sctpRemotePort=e.sctpPort;if(!this.sctpRemotePort){throw new Error(\"sctpRemotePort not exist\")}this.sctpTransport.setRemotePort(this.sctpRemotePort);this.sctpTransport.mLineIndex=t;if(!this.sctpTransport.mid){this.sctpTransport.mid=e.rtp.muxId}}async close(){if(this.sctpTransport){await this.sctpTransport.stop();await new Promise(e=>setImmediate(e))}this.onDataChannel.allUnsubscribe()}async getStats(e=J()){const t=[];for(const s of this.dataChannels){const i={type:\"data-channel\",id:D(\"data-channel\",s.id??s.statsId),timestamp:e,label:s.label,protocol:s.protocol,dataChannelIdentifier:s.id??void 0,state:s.readyState,messagesSent:s.messagesSent||0,bytesSent:s.bytesSent||0,messagesReceived:s.messagesReceived||0,bytesReceived:s.bytesReceived||0};t.push(i)}return t}};function al(r,e){if(r===void 0){return void 0}const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw Re(`${e} must be an unsigned short`)}return t}a(al,\"coerceUnsignedShortOption\");var lc=b(\"webrtc/peer/secureTransportManager\");var ko=class{static{a(this,\"SecureTransportManager\")}constructor({config:e,transceiverManager:t,sctpManager:s}){this.connectionState=\"new\";this.iceConnectionState=\"new\";this.iceGatheringState=\"new\";this.iceGatheringStateChange=new w;this.iceConnectionStateChange=new w;this.onIceCandidate=new w;this.connectionStateChange=new w;this.createdTransports=new Set;this.config=e;this.transceiverManager=t;this.sctpManager=s;if(this.config.dtls){const{keys:i}=this.config.dtls;if(this.config.certificates[0]){this.certificate=this.config.certificates[0]}else if(i){this.setupCertificate(i)}}}get dtlsTransports(){return fc([...this.transceiverManager.getTransceivers().filter(e=>!e.stopped).map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return fc([...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new ui(e.keyPem,e.certPem,e.signatureHash)}resolveIceServerOptions(){const e=Fu(this.config.iceServers);const t=$a({parsedTurnTransport:e.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:t,stunServers:e.stunServers,turnServers:e.turnServers.map(s=>({...s,transport:$a({parsedTurnTransport:s.transport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP})}))}}updateIceServers(){const e={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy===\"relay\",useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(const t of this.iceTransports){if(t.gatheringState===\"new\"){t.setIceServers(e)}}}createTransport({inheritCredentials:e=true}={}){const t=e?this.iceTransports.find(o=>o.state!==\"closed\"):void 0;const s=new po({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy===\"relay\",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});if(t){s.connection.localUsername=t.connection.localUsername;s.connection.localPassword=t.connection.localPassword}s.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()});this.updateIceGatheringState();const i=new fo(s);i.onStateChange.subscribe(()=>{this.updateIceConnectionState()});const n=new hi(this.config,i,this.certificate,Hm);this.createdTransports.add(n);return n}handleNewIceCandidate({candidate:e,sdpMid:t,sdpMLineIndex:s}){e.sdpMid=t;e.sdpMLineIndex=s;if(e.foundation&&!e.foundation.startsWith(\"candidate:\")){e.foundation=\"candidate:\"+e.foundation}this.onIceCandidate.execute(e);return e}async addIceCandidate(e,t){const s=t?.candidate;const i=t?.sdpMid;const n=t?.sdpMLineIndex;const o=t?.usernameFragment;const c=t==null||s==null||s===\"\";const d=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:c,sdpMid:i,sdpMLineIndex:n,usernameFragment:o});if(c){const S=d.map(p=>this.getTransportByMLineIndex(e,p)).filter(p=>!!p).reduce((p,f)=>{if(!p.find(({id:y})=>y===f.id)){p.push(f)}return p},[]);await Promise.all(S.map(p=>p.addRemoteCandidate(void 0)));return{kind:\"end-of-candidates\",mediaIndices:d}}const h=li.fromJSON(t);if(!h){throw _(\"OperationError\",\"Failed to parse ICE candidate\")}const l=d[0];const u=e.media[l];if(!u){throw _(\"OperationError\",\"ICE media section not found\")}h.sdpMid=u.rtp.muxId??void 0;h.sdpMLineIndex=l;const g=this.getTransportByMLineIndex(e,l);if(!g){if(this.isRejectedMedia(u)){return{kind:\"candidate\",candidate:h,mediaIndices:[l]}}throw _(\"OperationError\",\"ICE transport not found for candidate\")}await g.addRemoteCandidate(h);return{kind:\"candidate\",candidate:h,mediaIndices:[l]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:s,sdpMLineIndex:i,usernameFragment:n}){let o;if(typeof s===\"string\"){const c=e.media.findIndex(d=>d.rtp.muxId===s);if(c<0){throw _(\"OperationError\",\"Media section for sdpMid was not found\")}o=[c]}else if(typeof i===\"number\"){if(i<0||i>=e.media.length){throw _(\"OperationError\",\"Media section for sdpMLineIndex was not found\")}o=[i]}else if(t){o=e.media.map((c,d)=>d)}else{throw Re(\"sdpMid or sdpMLineIndex must be provided with a candidate\")}if(typeof n===\"string\"){const c=o.filter(d=>e.media[d]?.iceParams?.usernameFragment===n);if(c.length===0){throw _(\"OperationError\",\"No media section matched the ICE usernameFragment\")}o=c}return o}isRejectedMedia(e){if(e.port===0){return true}if(![\"audio\",\"video\"].includes(e.kind)){return false}const t=this.transceiverManager.getTransceivers().find(s=>s.mid!=void 0&&s.mid===e.rtp.muxId);return!t||t.stopped||t.stopping||t.pendingRejection}getTransportByMid(e){if(!e){return}let t;const s=this.transceiverManager.getTransceivers().find(i=>i.mid===e);if(s){t=s.dtlsTransport?.iceTransport}else if(!t&&this.sctpManager.sctpTransport?.mid===e){t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport}if(t?.state===\"closed\"){return}return t}getTransportByMLineIndex(e,t){const s=e.media[t];if(!s){return}const i=this.getTransportByMid(s.rtp.muxId);return i}restartIce(){for(const e of this.iceTransports){e.restart()}this.updateIceGatheringState()}setLocalRole({type:e,role:t,roleOfTransport:s}){for(const i of this.dtlsTransports){const n=i.iceTransport;if(n.state===\"new\"){if(n.connection.iceLite){n.connection.iceControlling=false}else if(n.connection.remoteIsLite){n.connection.iceControlling=true}else{n.connection.iceControlling=e===\"offer\"}}if(e===\"answer\"){const o=s?.get(i)??t;if(o){i.role=o}}}}updateIceGatheringState(){const e=this.iceTransports;function t(...i){return e.filter(n=>i.includes(n.gatheringState)).length===e.length}a(t,\"allMatch\");let s;if(e.length&&t(\"complete\")){s=\"complete\"}else if(!e.length||t(\"new\",\"complete\")){s=\"new\"}else if(e.map(i=>i.gatheringState).includes(\"gathering\")){s=\"gathering\"}else{s=\"new\"}if(this.iceGatheringState===s){return}this.iceGatheringState=s;this.iceGatheringStateChange.execute(s)}updateIceConnectionState(){const e=this.iceTransports;let t;function s(...n){return e.filter(o=>n.includes(o.state)).length===e.length}a(s,\"allMatch\");function i(...n){return e.some(o=>n.includes(o.state))}a(i,\"anyMatch\");if(this.connectionState===\"closed\"){t=\"closed\"}else if(i(\"failed\")){t=\"failed\"}else if(i(\"disconnected\")){t=\"disconnected\"}else if(s(\"new\",\"closed\")){t=\"new\"}else if(i(\"new\",\"checking\")){t=\"checking\"}else if(s(\"completed\",\"closed\")){t=\"completed\"}else if(s(\"connected\",\"completed\",\"closed\")){t=\"connected\"}else{t=\"new\"}if(this.iceConnectionState===t){return}lc(\"iceConnectionStateChange\",t);this.iceConnectionState=t;this.iceConnectionStateChange.execute(t);if(t===\"failed\"&&this.connectionState!==\"closed\"){this.setConnectionState(\"failed\")}else if(t===\"disconnected\"&&this.connectionState===\"connected\"){this.setConnectionState(\"disconnected\")}}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter(e=>e.state!==\"closed\").map(e=>e.gather())).catch(e=>{lc(\"gatherCandidates failed\",e)})}setConnectionState(e){if(this.connectionState===e||this.connectionState===\"closed\"){return}lc(\"connectionStateChange\",e);this.connectionState=e;this.connectionStateChange.execute(e)}async getStats(e){const t=[];for(const s of this.dtlsTransports){const i=await s.getStats(e);if(i){t.push(...i)}}return t}async ensureCerts(){if(!this.certificate){this.certificate=await hi.SetupCertificate()}for(const e of this.dtlsTransports){e.localCertificate=this.certificate}}async close(){this.setConnectionState(\"closed\");await Promise.allSettled(fc([...this.allDtlsTransports,...this.createdTransports]).map(e=>e.stop()));this.createdTransports.clear();this.iceGatheringStateChange.allUnsubscribe();this.iceConnectionStateChange.allUnsubscribe();this.onIceCandidate.allUnsubscribe();this.connectionStateChange.allUnsubscribe()}};function fc(r){return r.reduce((e,t)=>{if(t&&!e.map(s=>s.id).includes(t.id)){e.push(t)}return e},[])}a(fc,\"uniqueTransports\");var Hm=[Ta.SRTP_AEAD_AES_128_GCM,Ta.SRTP_AES128_CM_HMAC_SHA1_80];var U=b(\"webrtc/peer/peerConnection\");var vo=class extends he{static{a(this,\"RTCPeerConnection\")}get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super();this.id=(0,pc.randomUUID)().toString();this.cname=(0,pc.randomUUID)().toString();this.config=dl();this.signalingState=\"stable\";this.negotiationneeded=false;this.negotiationneededScheduled=false;this.negotiationChangeSeq=0;this.negotiatedChangeSeq=0;this.lastCreatedOfferChangeSeq=0;this.needRestart=false;this.router=new bo;this.isClosed=false;this.shouldNegotiationneeded=false;this.pendingRemoteCandidates=[];this.iceGatheringStateChange=new w;this.iceConnectionStateChange=new w;this.signalingStateChange=new w;this.connectionStateChange=new w;this.onDataChannel=new w;this.onRemoteTransceiverAdded=new w;this.onTransceiverAdded=new w;this.onIceCandidate=new w;this.onNegotiationneeded=new w;this.onTrack=new w;this.eventHandlers={};this.needNegotiation=()=>{this.negotiationChangeSeq++;this.scheduleNegotiationneeded()};this.setConfiguration(e);this.sdpManager=new Co({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse});this.transceiverManager=new Ro(this.cname,this.config,this.router);this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);this.transceiverManager.onTrack.subscribe(({track:t,streams:s,transceiver:i})=>{const n=new mc({track:t,streams:s,transceiver:i,receiver:i.receiver});this.onTrack.execute(t);this.emit(\"track\",n);if(this.ontrack){K(()=>this.ontrack(n),o=>U(\"event handler failed\",o))}});this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation());this.sctpManager=new xo;this.sctpManager.onDataChannel.subscribe(t=>{this.onDataChannel.execute(t);const s={type:\"datachannel\",channel:t};if(this.ondatachannel)K(()=>this.ondatachannel(s),i=>U(\"event handler failed\",i));this.emit(\"datachannel\",s)});this.secureManager=new ko({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager});this.secureManager.iceGatheringStateChange.subscribe(t=>{this.iceGatheringStateChange.execute(t);if(this.onicegatheringstatechange){K(()=>this.onicegatheringstatechange(new globalThis.Event(\"icegatheringstatechange\")),s=>U(\"event handler failed\",s))}this.emit(\"icegatheringstatechange\")});this.secureManager.iceConnectionStateChange.subscribe(t=>{if(t===\"closed\"){this.close().catch(s=>U(\"close failed\",s))}this.iceConnectionStateChange.execute(t);if(this.oniceconnectionstatechange)K(()=>this.oniceconnectionstatechange(),s=>U(\"event handler failed\",s));this.emit(\"iceconnectionstatechange\")});this.secureManager.connectionStateChange.subscribe(t=>{this.connectionStateChange.execute(t);if(this.onconnectionstatechange)K(()=>this.onconnectionstatechange(),s=>U(\"event handler failed\",s));this.emit(\"connectionstatechange\")});this.secureManager.onIceCandidate.subscribe(t=>{const s=t?t.toJSON():void 0;this.onIceCandidate.execute(s);const i={type:\"icecandidate\",candidate:s};if(this.onicecandidate)K(()=>this.onicecandidate(i),n=>U(\"event handler failed\",n));this.emit(\"icecandidate\",i)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){const e=this.sdpManager._remoteDescription;if(!e){return null}const t=[e.iceOptions,...e.media.map(s=>s.iceOptions)].filter(s=>!!s).join(\" \");return t.split(/\\s+/).includes(\"trickle\")}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(e){const t=qm(e);const s=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==\"require\"){throw new Error(\"rtcpMuxPolicy must be require\")}if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0)){throw new Error(\"iceCandidatePoolSize must be a non-negative integer\")}if(s&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy){throw new Error(\"bundlePolicy cannot be changed\")}if(t.mLineReuse!==void 0&&!cl.includes(t.mLineReuse)){throw Re(`mLineReuse must be one of ${cl.join(\", \")}`)}if(s&&t.mLineReuse!==void 0&&t.mLineReuse!==this.config.mLineReuse){throw _(\"InvalidModificationError\",\"mLineReuse cannot be changed\")}if(s&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy){throw new Error(\"rtcpMuxPolicy cannot be changed\")}if(s&&t.certificates!==void 0&&!Km(t.certificates,this.config.certificates)){throw new Error(\"certificates cannot be changed\")}if(s&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize){throw new Error(\"iceCandidatePoolSize cannot be changed after setLocalDescription\")}if((t.iceCandidatePoolSize??0)>0){throw new Error(\"iceCandidatePoolSize > 0 is not supported\")}if(t.sctp!==void 0){const o=t.sctp.mtu??bs;sn(o);if(this.sctpManager?.sctpTransport&&o!==this.config.sctp.mtu){throw new Error(\"sctp.mtu cannot be changed after SCTP transport creation\")}}Ku(this.config,t);this.config.sctp={mtu:this.config.sctp?.mtu??bs};if(this.config.icePortRange){const[o,c]=this.config.icePortRange;if(o===c)throw new Error(\"should not be same value\");if(o>=c)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\")}if(this.sctpManager?.sctpTransport){this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize}zm(this.config);const i=new Map;const n=[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]];n.forEach(o=>{if(!i.has(o.uri))i.set(o.uri,i.size+1);o.id=i.get(o.uri)});if(s&&this.secureManager&&(t.iceServers!==void 0||t.turnUdpFamily!==void 0)){this.secureManager.updateIceServers()}}getConfiguration(){return Gm(this.config)}headerExtensionsFor(e){const t=new Map;for(const i of this.transceiverManager.getTransceivers()){for(const n of i.headerExtensions)t.set(n.uri,n.id)}const s=new Set(t.values());return(this.config.headerExtensions[e]??[]).flatMap(i=>{let n=t.get(i.uri);if(n===void 0){n=s.has(i.id)?Array.from({length:14},(o,c)=>c+1).find(o=>!s.has(o)):i.id;if(n===void 0)return[];s.add(n);t.set(i.uri,n)}return[new Te({uri:i.uri,id:n})]})}async createOffer({iceRestart:e}={}){if(e||this.needRestart){this.needRestart=false;this.secureManager.restartIce()}await this.secureManager.ensureCerts();for(const i of this.transceiverManager.getTransceivers()){if(i.codecs.length===0||i.codecPreferencesNeedResolution){this.transceiverManager.assignTransceiverCodecs(i)}if(i.headerExtensions.length===0){i.headerExtensions=this.headerExtensionsFor(i.kind)}}const t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);const s=t.toJSON();this.lastCreatedOffer=s;this.lastCreatedOfferChangeSeq=this.negotiationChangeSeq;return s}createSctpTransport(){const e=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp);const t=this.findOrCreateTransport();e.setDtlsTransport(t);return e}createDataChannel(e,t={}){if(!this.sctpTransport){this.createSctpTransport();this.needNegotiation()}const s=this.sctpManager.createDataChannel(e,t);if(!s.sctp.dtlsTransport){const i=this.findOrCreateTransport();s.sctp.setDtlsTransport(i)}return s}removeTrack(e){if(this.isClosed){throw _(\"InvalidStateError\",\"peer closed\")}if(this.transceiverManager.removeTrack(e)){this.needNegotiation()}}scheduleNegotiationneeded(){this.invalidateLastCreatedDescriptions();this.shouldNegotiationneeded=true;if(this.negotiationneeded||this.negotiationneededScheduled||this.signalingState!==\"stable\"){return}this.shouldNegotiationneeded=false;this.negotiationneededScheduled=true;setImmediate(()=>{this.negotiationneededScheduled=false;if(this.negotiatedChangeSeq>=this.negotiationChangeSeq){return}if(this.signalingState!==\"stable\"){this.shouldNegotiationneeded=true;return}this.negotiationneeded=true;this.onNegotiationneeded.execute();if(this.onnegotiationneeded){K(()=>this.onnegotiationneeded(new globalThis.Event(\"negotiationneeded\")),e=>U(\"event handler failed\",e))}this.emit(\"negotiationneeded\")})}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0;this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed();await Promise.resolve();if(this.isClosed){await new Promise(()=>void 0)}}findOrCreateTransport(){const e=this.dtlsTransports.find(t=>t.state!==\"closed\");if(this.sdpManager.bundlePolicy===\"max-bundle\"||this.sdpManager.bundlePolicy!==\"disable\"&&this.remoteIsBundled){if(e){return e}}return this.createDtlsTransport()}createDtlsTransport({inheritCredentials:e=true}={}){const t=this.secureManager.createTransport({inheritCredentials:e});t.onRtp.subscribe(i=>{this.router.routeRtp(i)});t.onRtcp.subscribe(i=>{this.router.routeRtcp(i)});const s=t.iceTransport;s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()});s.onIceCandidate.subscribe(i=>{if(!this.localDescription){U(\"localDescription not found when ice candidate was gathered\");return}if(!i){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport);this.onIceCandidate.execute(void 0);if(this.onicecandidate){K(()=>this.onicecandidate({candidate:void 0}),o=>U(\"event handler failed\",o))}this.emit(\"icecandidate\",{candidate:void 0});return}if(!this._localDescription){U(\"localDescription not found when ice candidate was gathered\");return}const n=this.resolveLocalCandidateOwner(s);if(!n){U(\"no accepted m-line owns the ice transport\",s.id);return}this.secureManager.handleNewIceCandidate({candidate:i,sdpMid:n.mid,sdpMLineIndex:n.index})});return t}resolveLocalCandidateOwner(e){const t=this._localDescription;if(!t){return}const s=t.media.map((o,c)=>({media:o,index:c})).filter(({media:o})=>{if(o.port===0){return false}const c=o.rtp.muxId;if(o.kind===\"application\"){return!!this.sctpTransport&&this.sctpTransport.mid===c&&this.sctpTransport.dtlsTransport?.iceTransport.id===e.id}const d=this.transceiverManager.getTransceivers().find(h=>h.mid!=void 0&&h.mid===c);return!!d&&!d.stopped&&d.dtlsTransport?.iceTransport.id===e.id});const i=t.group.filter(o=>o.semantic===\"BUNDLE\").map(o=>o.items[0]);const n=s.find(({media:o})=>i.includes(o.rtp.muxId))??s[0];if(!n){return}return{mid:n.media.rtp.muxId,index:n.index}}settleStoppingTransceivers(){const e=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter(s=>s.port!==0&&s.rtp.muxId).map(s=>s.rtp.muxId));const t=this.transceiverManager.settleStoppingTransceivers(e);this.closeIdleTransports();return t}closeIdleTransports(e=this.transceiverManager.getTransceivers().filter(t=>t.stopped).map(t=>t.dtlsTransport)){const t=new Set(this.dtlsTransports.map(s=>s.id));for(const s of new Set(e)){if(!s||s.state===\"closed\"||t.has(s.id)){continue}s.stop().catch(i=>{U(\"failed to close idle transport\",i)})}}async setLocalDescription(e){const t=[\"stable\",\"have-local-offer\",\"have-remote-pranswer\"];await this.waitForPendingDescriptionTask();if(e?.type===\"rollback\"){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const u of this.transceiverManager.getTransceivers()){u.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}const s=!e?.type||!e.sdp||e.sdp.length===0;const i=s?e?.type===\"offer\"?this.lastCreatedOffer??await this.createOffer():e?.type===\"answer\"||e?.type===\"pranswer\"?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;e={type:e?.type??i.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:i.sdp};if(e.type===\"offer\"&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp){throw _(\"InvalidModificationError\",\"setLocalDescription must use the latest created offer\")}const n=e.type;const o=e.sdp;const c=this.sdpManager.parseSdp({sdp:o,isLocal:true,signalingState:this.signalingState,type:n});if(c.type===\"offer\"){this.pendingOfferChangeSeq=this.lastCreatedOffer?.sdp===e.sdp?this.lastCreatedOfferChangeSeq:void 0;this.setSignalingState(\"have-local-offer\")}else if(c.type===\"answer\"){this.setSignalingState(\"stable\")}else if(c.type===\"pranswer\"){this.setSignalingState(\"have-local-pranswer\")}if(c.type===\"answer\"){this.transceiverManager.commitRemoteOffer();for(const u of c.media){if(![\"audio\",\"video\"].includes(u.kind)||u.port!==0){continue}const g=this.transceiverManager.getTransceivers().find(S=>S.mid===u.rtp.muxId&&!S.stopped);g?.commitStopped({rejected:true})}this.closeIdleTransports()}for(const[u,g]of Uo(c.media)){const S=g.rtp.muxId;this.sdpManager.registerMid(S);if([\"audio\",\"video\"].includes(g.kind)&&g.port!==0){const p=this.transceiverManager.getTransceivers().find(f=>f.mLineIndex===u&&!f.stopped&&f.kind===g.kind&&(f.mid==null||f.mid===S));if(p){p.mid=S;if(c.type===\"offer\"){p.pendingLocalOfferCodecs=[...g.rtp.codecs]}}}if(g.kind===\"application\"&&this.sctpTransport){this.sctpTransport.mid=S}}const d=c.media.find(u=>u.dtlsParams)?.dtlsParams?.role;const h=new Map;for(const u of c.media){const g=u.rtp.muxId;const S=u.dtlsParams?.role;if(u.port===0||g==void 0||!S){continue}const p=u.kind===\"application\"?this.sctpTransport?.mid===g?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(f=>f.mid===g&&!f.stopped);if(p?.dtlsTransport&&!h.has(p.dtlsTransport)){h.set(p.dtlsTransport,S)}}this.secureManager.setLocalRole({type:c.type===\"offer\"?\"offer\":\"answer\",role:d,roleOfTransport:h});if([\"answer\",\"pranswer\"].includes(c.type)){for(const u of c.media){const g=this.transceiverManager.getTransceivers().find(p=>p.mid!=void 0&&p.mid===u.rtp.muxId);if(!g||g.stopped||g.pendingRejection){continue}const S=g.stopping?\"inactive\":oo(g.direction,g.offerDirection);g.setCurrentDirection(S)}}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);await this.gatherCandidates().catch(u=>{U(\"gatherCandidates failed\",u)});if(c.type===\"answer\"){this.connect().catch(u=>{U(\"connect failed\",u);this.secureManager.setConnectionState(\"failed\")})}this.sdpManager.setLocal(c,this.transceiverManager.getTransceivers(),this.sctpTransport);const l=c.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||l){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return c}async gatherCandidates(){await this.secureManager.gatherCandidates()}async addIceCandidate(e={}){if(this.isClosed){throw _(\"InvalidStateError\",\"is closed\")}if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){const t=this.sdpManager._remoteDescription;if(!t){return}const s=await this.secureManager.addIceCandidate(t,e);const i=this.sdpManager._remoteDescription;if(!i||!s){return}if(s.kind===\"end-of-candidates\"){for(const n of s.mediaIndices){const o=i.media[n];if(o){o.iceCandidatesComplete=true}}return}for(const n of s.mediaIndices){const o=i.media[n];if(!o){continue}o.iceCandidates.push(s.candidate)}}async flushPendingRemoteCandidates(){while(this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription){const e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){U(\"start connect\");const e=await Promise.allSettled(this.dtlsTransports.map(async t=>{const{iceTransport:s}=t;if(s.state===\"connected\"){return}if(!s.connection.remoteUsername||!s.connection.remotePassword){return}const i=a(()=>t.state===\"connected\",\"checkDtlsConnected\");if(i()){if(!s.connection.nominated){await s.start().catch(n=>{U(\"iceTransport.start failed\",n);throw n})}return}this.secureManager.setConnectionState(\"connecting\");await s.start().catch(n=>{U(\"iceTransport.start failed\",n);throw n});if(i()){return}await t.start().catch(n=>{U(\"dtlsTransport.start failed\",n);throw n});if(this.sctpTransport&&this.sctpTransport.dtlsTransport.id===t.id){await this.sctpManager.connectSctp()}}));if(e.find(t=>t.status===\"rejected\")){this.secureManager.setConnectionState(\"failed\")}else{this.secureManager.setConnectionState(\"connected\")}}restartIce(){this.needRestart=true;this.needNegotiation()}async setRemoteDescription(e){if(e instanceof ot){e=e.toSdp()}await this.waitForPendingDescriptionTask();const t=e.type===\"offer\"&&[\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState);if(t){this.sdpManager.rollbackLocalDescription(this.signalingState);this.rollbackLocalOffer();for(const m of this.transceiverManager.getTransceivers()){m.pendingLocalOfferCodecs=void 0}this.pendingOfferChangeSeq=void 0;this.shouldNegotiationneeded=true;this.setSignalingState(\"stable\");await Promise.resolve()}let s=new Map;if(e.type&&e.type!==\"rollback\"&&e.sdp){const m=this.sdpManager.parseSdp({sdp:e.sdp,isLocal:false,signalingState:this.signalingState,type:e.type});const T=new Set;s=this.transceiverManager.planRemoteRtpCodecs(m,(C,E)=>{const P=this.findTransceiverForRemoteMedia(C,E,T,e.type===\"offer\");if(P)T.add(P);return P})}this.assertAnswerKeepsSharedTransports(e);const i=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!i){const m=this.transceiverManager.getTransceivers().map(T=>T.dtlsTransport);this.transceiverManager.rollbackRemoteOffer();this.closeIdleTransports(m);this.setSignalingState(\"stable\");if(this.shouldNegotiationneeded){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions();return}if(i.type===\"offer\"){this.transceiverManager.beginRemoteOffer()}const n=this.config.bundlePolicy===\"disable\"?[]:i.group.filter(m=>m.semantic===\"BUNDLE\");const o=a(m=>m==void 0?void 0:n.find(T=>T.items.includes(m)),\"groupOfMid\");const c=new Set;const d=i.media.map((m,T)=>{if([\"audio\",\"video\"].includes(m.kind)){let C=this.findTransceiverForRemoteMedia(m,T,c,i.type===\"offer\");if(!C){if(m.port===0){return{remoteMedia:m,index:T}}C=this.addRemoteTransceiver(m,T)}else if(C.mid==null){this.transceiverManager.associateMLine(C,T)}c.add(C);return{remoteMedia:m,index:T,transceiver:C}}else if(m.kind===\"application\"){let C=this.sctpTransport;if(!C){C=this.createSctpTransport();C.mid=m.rtp.muxId}return{remoteMedia:m,index:T,sctpTransport:C}}else{throw new Error(\"invalid media kind\")}});if(i.type===\"offer\"){this.transceiverManager.releaseUnassociatedReservations(c,i.media.length)}const h=a(m=>m.transceiver??m.sctpTransport,\"ownerOf\");const l=i.type===\"offer\";const u=a(m=>!!m&&m.state!==\"closed\",\"liveTransport\");const g=new Map;const S=new Set;for(const m of n){const T=d.filter(E=>!!h(E)&&m.items.includes(E.remoteMedia.rtp.muxId));if(T.length===0){continue}let C=T.map(E=>h(E).dtlsTransport).find(E=>u(E)&&(!l||!S.has(E)));if(!C){C=this.createDtlsTransport({inheritCredentials:false})}g.set(m,C);S.add(C);for(const E of T){const P=h(E);if(P.dtlsTransport!==C){P.setDtlsTransport(C)}}}if(l){for(const m of d){const T=h(m);if(!T||m.remoteMedia.port===0||o(m.remoteMedia.rtp.muxId)){continue}if(!u(T.dtlsTransport)||S.has(T.dtlsTransport)){T.setDtlsTransport(this.createDtlsTransport({inheritCredentials:false}))}S.add(T.dtlsTransport)}}const p=new Set;for(const m of d){const{remoteMedia:T,index:C}=m;if(m.transceiver){if(this.transceiverManager.setRemoteRTP(m.transceiver,T,i.type,C,s.get(C)??[])){p.add(m)}}else if(m.sctpTransport){this.sctpManager.setRemoteSCTP(T,C);p.add(m)}}const f=new Map;for(const m of n){for(const T of m.items){const C=d.find(E=>E.remoteMedia.rtp.muxId===T&&E.remoteMedia.port!==0&&p.has(E));if(C){f.set(m,C);break}}}for(const m of d){const{remoteMedia:T}=m;const C=h(m);if(!C){continue}const E=p.has(m);const P=C.dtlsTransport;const de=o(T.rtp.muxId);if(T.port===0||!P||P.state===\"closed\"||!E&&!de){continue}const q=P.iceTransport;const pt=!de||f.get(de)===m;if(pt){if(T.iceParams){const mt=!!this.sdpManager.inactiveRemoteMedia;q.setRemoteParams(T.iceParams,mt);if(T.iceParams.iceLite&&!q.connection.iceLite){q.connection.iceControlling=true}}if(T.dtlsParams){P.setRemoteParams(T.dtlsParams)}}for(const mt of T.iceCandidates){q.addRemoteCandidate(mt).catch(He=>U(\"add candidate failed\",He))}if(T.iceCandidatesComplete){q.addRemoteCandidate(void 0).catch(mt=>U(\"end of candidates failed\",mt))}if(i.type===\"answer\"&&T.dtlsParams?.role){P.role=T.dtlsParams.role===\"client\"?\"server\":\"client\"}}if(i.type===\"answer\"){for(const m of this.transceiverManager.getTransceivers()){if(!c.has(m)&&m.mid!=void 0&&!m.stopped){m.commitStopped({rejected:true})}}this.closeIdleTransports()}if(i.type===\"offer\"){this.setSignalingState(\"have-remote-offer\")}else if(i.type===\"answer\"){this.setSignalingState(\"stable\")}else if(i.type===\"pranswer\"){this.setSignalingState(\"have-remote-pranswer\")}await this.flushPendingRemoteCandidates();if(i.type===\"answer\"){U(\"caller start connect\");this.connect().catch(m=>{U(\"connect failed\",m);this.secureManager.setConnectionState(\"failed\")})}this.negotiationneeded=false;if(i.type===\"answer\"&&this.pendingOfferChangeSeq!=void 0){this.negotiatedChangeSeq=Math.max(this.negotiatedChangeSeq,this.pendingOfferChangeSeq);this.pendingOfferChangeSeq=void 0}const y=i.type===\"answer\"&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||y){this.scheduleNegotiationneeded()}this.invalidateLastCreatedDescriptions()}assertAnswerKeepsSharedTransports(e){if(![\"answer\",\"pranswer\"].includes(e.type??\"\")||![\"have-local-offer\",\"have-local-pranswer\"].includes(this.signalingState)||!e.sdp||this.config.bundlePolicy===\"disable\"){return}const t=ot.parse(e.sdp);const s=t.group.filter(n=>n.semantic===\"BUNDLE\");const i=new Map;for(const n of t.media){const o=n.rtp.muxId;if(n.port===0||o==void 0){continue}const c=n.kind===\"application\"?this.sctpTransport?.mid===o?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(g=>g.mid===o&&!g.stopped);const d=c?.dtlsTransport;if(!d){continue}const h={group:s.find(g=>g.items.includes(o)),credentials:`${n.iceParams?.usernameFragment}:${n.iceParams?.password}`};const l=i.get(d);if(!l){i.set(d,h);continue}const u=!!h.group&&h.group===l.group;if(!u&&h.credentials!==l.credentials){throw _(\"InvalidAccessError\",`mid=${o} shares a transport in the local offer but the remote ${e.type} moves it out of that BUNDLE group`)}}}findTransceiverForRemoteMedia(e,t,s,i){const n=this.transceiverManager.getTransceivers().filter(h=>!s.has(h)&&h.kind===e.kind);const o=e.rtp.muxId;const c=o!=void 0?n.find(h=>h.mid===o):void 0;if(c){return c}if(e.port===0){return}const d=n.filter(h=>h.mid==null&&!h.stopping&&!h.stopped&&(!i||h.addedByAddTrack&&[\"sendrecv\",\"recvonly\"].includes(e.direction??\"sendrecv\")));return d.find(h=>h.mLineIndex===t)??d[0]}addRemoteTransceiver(e,t){const s=this.findOrCreateTransport();const i=this.transceiverManager.addTransceiver(e.kind,s,{direction:\"recvonly\"},{remoteMLineIndex:t});i.mid=e.rtp.muxId??null;this.secureManager.updateIceConnectionState();this.onRemoteTransceiverAdded.execute(i);return i}addTransceiver(e,t={}){const s=this.findOrCreateTransport();const i=this.transceiverManager.addTransceiver(e,s,t);this.secureManager.updateIceConnectionState();this.needNegotiation();return i}addTrack(e,...t){return this.addTrackOn(void 0,e,...t)}reusableForTrack(e){return this.transceiverManager.reusableForTrack(e,e.kind)}addTrackOn(e,t,...s){if(this.isClosed){throw _(\"InvalidStateError\",\"is closed\")}const i=this.transceiverManager.addTrack(t,s,e);if(!i.dtlsTransport){const n=this.findOrCreateTransport();i.setDtlsTransport(n)}this.needNegotiation();return i.sender}async createAnswer(){this.assertNotClosed();await this.secureManager.ensureCerts();for(const s of this.transceiverManager.getTransceivers()){if(s.codecs.length!==0&&!s.codecPreferencesNeedResolution){continue}if(s.pendingRejection||s.stopping||s.stopped){continue}const i=this.sdpManager._remoteDescription;const n=i?.media.find(o=>o.rtp.muxId!=void 0&&o.rtp.muxId===s.mid&&o.kind===s.kind)??(s.mLineIndex!=void 0?i?.media[s.mLineIndex]:void 0);if(n&&[\"audio\",\"video\"].includes(n.kind)){this.transceiverManager.resyncAnswerCodecs(s,n)}else{this.transceiverManager.assignTransceiverCodecs(s)}if(s.headerExtensions.length===0){s.headerExtensions=this.headerExtensionsFor(s.kind)}}const e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState});const t=e.toJSON();this.lastCreatedAnswer=t;return t}assertNotClosed(){if(this.isClosed){throw _(\"InvalidStateError\",\"RTCPeerConnection is closed\")}}markStable(){this.transceiverManager.markStable();const e=this.sctpTransport;this.stableSctp=e?{mid:e.mid,mLineIndex:e.mLineIndex}:void 0}rollbackLocalOffer(){this.transceiverManager.rollbackLocalOffer();const e=this.sctpTransport;if(e){e.mid=this.stableSctp?.mid;e.mLineIndex=this.stableSctp?.mLineIndex}}setSignalingState(e){if(this.signalingState===e){return}U(\"signalingStateChange\",e);this.signalingState=e;if(e===\"stable\")this.markStable();this.signalingStateChange.execute(e);if(this.onsignalingstatechange){K(()=>this.onsignalingstatechange(new globalThis.Event(\"signalingstatechange\")),t=>U(\"event handler failed\",t))}this.emit(\"signalingstatechange\")}createPeerConnectionStats(e){return{type:\"peer-connection\",id:D(\"peer-connection\",this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){const t=J();const s=[];if(!e){s.push(this.createPeerConnectionStats(t))}s.push(...this.transceiverManager.collectStats(t));const i=await this.secureManager.getStats(t);s.push(...i);if(!e&&this.sctpTransport){const n=await this.sctpManager.getStats(t);if(n){s.push(...n)}}if(!e){return Wt(s)}return Wt(s,this.transceiverManager.getStatsRootIds(e))}async close(){this.closing??=this.closeOnce();return this.closing}async closeOnce(){this.isClosed=true;this.pendingRemoteCandidates.length=0;this.setSignalingState(\"closed\");this.transceiverManager.close();await this.sctpManager.close();await this.secureManager.close();this.completePeerEvents();U(\"peerConnection closed\")}completePeerEvents(){const e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(const t of e){if(!t.ended){t.complete()}}}};var cl=[\"compatible\",\"aggressive\"];function zm(r){for(const[e,t]of Uo([...r.codecs.audio||[],...r.codecs.video||[]])){if(t.payloadType!=void 0){continue}t.payloadType=96+e;switch(t.name.toLowerCase()){case\"rtx\":{t.parameters=`apt=${t.payloadType-1}`}break;case\"red\":{if(t.contentType===\"audio\"){const s=t.payloadType+1;t.parameters=`${s}/${s}`;t.payloadType=63}}break}}}a(zm,\"assignDynamicPayloadTypes\");function dl(){return{codecs:Ad(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:\"all\",iceLite:false,iceServers:[],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:true,iceUseIpv6:true,iceUseTcp:false,iceTcpPassive:true,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:\"max-compat\",rtcpMuxPolicy:\"require\",iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:false,forceTurnTCP:false,maxMessageSize:tr,sctp:{mtu:bs},pendingRtp:false,mLineReuse:\"compatible\"}}a(dl,\"generateDefaultPeerConfig\");var t1=dl();function qm(r){const e=Object(r??{});const t={...e};if(e.sctp!==void 0){t.sctp={...e.sctp}}if(e.bundlePolicy===\"balanced\"){t.bundlePolicy=\"max-compat\"}if(\"certificates\"in e){if(e.certificates===void 0){t.certificates=void 0}else if(!Array.isArray(e.certificates)||e.certificates.some(s=>s==null)){throw Re(\"certificates must be an array of RTCCertificate\")}else{t.certificates=[...e.certificates]}}if(\"iceCandidatePoolSize\"in e){t.iceCandidatePoolSize=Fm(e.iceCandidatePoolSize,\"iceCandidatePoolSize\")}return t}a(qm,\"normalizePeerConfiguration\");function Fm(r,e){const t=Number(r);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>65535){throw Re(`${e} must be an unsigned short`)}return t}a(Fm,\"coerceUnsignedShort\");function Km(r,e){return r.length===e.length&&r.every((t,s)=>t===e[s])}a(Km,\"hasSameCertificates\");function Gm(r){return{...r,codecs:{audio:r.codecs.audio?[...r.codecs.audio]:void 0,video:r.codecs.video?[...r.codecs.video]:void 0},headerExtensions:{audio:r.headerExtensions.audio?[...r.headerExtensions.audio]:void 0,video:r.headerExtensions.video?[...r.headerExtensions.video]:void 0},iceServers:r.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:r.icePortRange?[...r.icePortRange]:void 0,iceAdditionalHostAddresses:r.iceAdditionalHostAddresses?[...r.iceAdditionalHostAddresses]:void 0,dtls:{...r.dtls},certificates:[...r.certificates],debug:{...r.debug},sctp:{...r.sctp},pendingRtp:typeof r.pendingRtp===\"object\"&&r.pendingRtp!=void 0?{...r.pendingRtp}:r.pendingRtp}}a(Gm,\"clonePeerConfiguration\");var mc=class{static{a(this,\"RTCTrackEvent\")}constructor(e){this.type=\"track\";this.track=e.track;this.streams=[...e.streams];this.transceiver=e.transceiver;this.receiver=e.receiver}};var jm={\"audio/opus\":a(()=>on(),\"audio/opus\"),\"audio/pcmu\":a(()=>an(),\"audio/pcmu\"),\"video/vp8\":a(()=>nn(),\"video/vp8\"),\"video/vp9\":a(()=>ea(),\"video/vp9\"),\"video/h264\":a(()=>Zo(),\"video/h264\")};var Wm=[\"audio/opus\",\"audio/PCMU\",\"video/VP8\",\"video/VP9\",\"video/H264\"];function $m(r){const e=jm[r.toLowerCase()];if(!e)throw new TypeError(`The codec ${r} is not supported: ${Wm.join(\", \")}`);return e()}a($m,\"engineCodecOf\");function hl(r){const e=r.map($m);return{audio:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"audio/\")),video:e.filter(t=>t.mimeType.toLowerCase().startsWith(\"video/\"))}}a(hl,\"engineCodecsOf\");function ul(r){const e={iceServers:r.iceServers,iceTransportPolicy:r.iceTransportPolicy,iceUseIpv4:r.iceUseIpv4,iceUseIpv6:r.iceUseIpv6,codecs:hl(r.codecs),maxMessageSize:262144};if(r.icePortRange)e.icePortRange=r.icePortRange;if(r.iceAdditionalHostAddresses)e.iceAdditionalHostAddresses=r.iceAdditionalHostAddresses;if(r.headerExtensions){e.headerExtensions={audio:[el(),dc(),cc(),ac()],video:[dc(),cc(),ac()]};for(const t of[...e.codecs.audio,...e.codecs.video])t.rtcpFeedback.push(rn())}return e}a(ul,\"engineConfigOf\");var gc=b(\"webrtc/peer/threads\");var Vm=4096;var ll=65536;var fl=2*1024*1024;function Ym(r){const e=new Uint8Array(r);return{bytes:e,transfer:[e.buffer]}}a(Ym,\"ownCopy\");function Qm(r){return Object.assign(new Error(r.message),{name:r.name})}a(Qm,\"threadErrorOf\");function yi(r){return r instanceof Error?{name:r.name,message:r.message}:{name:\"Error\",message:String(r)}}a(yi,\"sentError\");var Io=class{static{a(this,\"PeerThreadChannel\")}#e;#t;#s=new Map;#n=new Set;#i=[];#o=[];#u=false;#l=1;#r;#a;#c=0;constructor(e,t){this.#e=e;this.#t=t;e.on(\"message\",s=>{if(!Array.isArray(s))return;for(const i of s)this.#f(i)})}get closed(){return!!this.#r}post(e,t){if(this.#r)return;this.#i.push(e);if(t)this.#o.push(...t);this.#h()}pack(e){if(e.byteLength>=Vm)return Ym(e);let t;if(!this.#a||this.#c+e.byteLength>ll){this.#a=new Uint8Array(ll);this.#c=0;t=[this.#a.buffer]}const s=this.#a.subarray(this.#c,this.#c+e.byteLength);s.set(e);this.#c+=e.byteLength;return{bytes:s,transfer:t}}postOrExtend(e,t,s){if(this.#r)return;const i=this.#i.at(-1);if(!i||!e(i))this.#i.push(t());if(s)this.#o.push(...s);this.#h()}request(e,t){if(this.#r)return Promise.reject(this.#r);const s=this.#l++;return new Promise((i,n)=>{this.#s.set(s,{resolve:i,reject:n});this.post({...e,request:s},t)})}beforeSending(e){this.#n.add(e)}schedule(){if(!this.#r)this.#h()}flush(){this.#u=false;if(this.#r)return;for(const s of this.#n)s();this.#a=void 0;if(!this.#i.length)return;const e=this.#i;const t=this.#o;this.#i=[];this.#o=[];try{this.#e.postMessage(e,t)}catch(s){gc(\"a batch could not be sent: %O\",s);for(const i of e)if(i.request!==void 0)this.#d(i.request,void 0,s)}}close(e){this.#r??=e;this.#i=[];this.#o=[];for(const{reject:t}of this.#s.values())t(e);this.#s.clear()}#h(){if(this.#u)return;this.#u=true;setImmediate(()=>this.flush())}#f(e){if(e.type===\"reply\"){const i=this.#s.get(e.reply);this.#s.delete(e.reply);if(e.error===void 0)i?.resolve(e.result);else i?.reject(Qm(e.error));return}const t=e.request;let s;try{s=this.#t(e)}catch(i){if(t===void 0)gc(\"a message failed: %O\",i);else this.#d(t,void 0,i);return}if(t===void 0){if(s instanceof Promise)s.catch(i=>gc(\"a message failed: %O\",i));return}if(s instanceof Promise)s.then(i=>this.#d(t,i),i=>this.#d(t,void 0,i));else this.#d(t,s)}#d(e,t,s){if(this.#r)return;this.#i.push(s===void 0?{type:\"reply\",reply:e,result:t}:{type:\"reply\",reply:e,error:yi(s)});this.#h()}};function Po(r){return r?{type:r.type,sdp:r.sdp}:null}a(Po,\"plainDescription\");function pl(r){return{payloadType:r.payloadType,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,parameters:r.parameters,rtcpFeedback:r.rtcpFeedback.map(e=>({type:e.type,parameter:e.parameter}))}}a(pl,\"plainCodec\");function Xm(r){return{label:r.label,protocol:r.protocol,ordered:r.ordered,maxRetransmits:r.maxRetransmits,maxPacketLifeTime:r.maxPacketLifeTime,negotiated:r.negotiated,id:r.id??null,readyState:r.readyState}}a(Xm,\"infoOf\");var Jm=b(\"webrtc/peer/threads\");function gl(){if(!Ti.parentPort)throw new Error(\"The connections of a thread are served in a worker thread only\");const r=Ti.workerData;const e=new Map;const t=new Io(Ti.parentPort,p=>S(p));t.beforeSending(()=>{for(const p of e.values()){for(const f of p.changed)t.post({type:\"buffered\",conn:p.conn,ch:f.ref,amount:f.engine.bufferedAmount,applied:f.applied});p.changed.clear()}});const s=a(p=>{const f=e.get(p);if(!f)throw Object.assign(new Error(\"The connection is closed\"),{name:\"InvalidStateError\"});return f},\"servedOf\");const i=a((p,f,y)=>{let m=p.receivedRefs.get(f);if(m)return m;m=`r${p.next++}`;p.receivedRefs.set(f,m);p.received.set(m,{track:f,receiver:y});const T=m;f.once(\"ended\",()=>{p.received.get(T)?.unsubscribe?.();p.received.delete(T);t.post({type:\"trackEnded\",conn:p.conn,track:T})});return m},\"receivedRef\");const n=a((p,f,y)=>{let m=p.transceiverRefs.get(f);if(m)return m;m=y??`w${p.next++}`;p.transceiverRefs.set(f,m);p.transceivers.set(m,f);const T=m;f.sender.onPictureLossIndication.subscribe(()=>t.post({type:\"pli\",conn:p.conn,transceiver:T}));return m},\"transceiverRef\");const o=a((p,f)=>{const y=f.receiver.track;const m={ref:i(p,y,f.receiver),kind:y.kind,id:y.id??y.uuid,...y.codec?{codec:pl(y.codec)}:{}};const T=f.sender.track;return{ref:n(p,f),kind:f.kind,mid:f.mid,direction:f.direction,currentDirection:f.currentDirection,reusable:p.engine.reusableForTrack(f),sending:T?p.mirrorRefs.get(T)??null:null,...T?.codec?{sendingCodec:pl(T.codec)}:{},receiving:m}},\"transceiverInfo\");const c=a(p=>{const f=p.engine;const y=f.sctpTransport;const m=f.getConfiguration();return{connectionState:f.connectionState,iceConnectionState:f.iceConnectionState,iceGatheringState:f.iceGatheringState,signalingState:f.signalingState,localDescription:Po(f.localDescription),remoteDescription:Po(f.remoteDescription),maxMessageSize:y?y.remoteMaxMessageSize:null,configuration:{iceServers:m.iceServers,iceTransportPolicy:m.iceTransportPolicy},transceivers:f.getTransceivers().map(T=>o(p,T)),ops:p.ops,seq:++p.seq}},\"stateOf\");const d=a((p,f,y)=>{const m={ref:y,engine:f,applied:0};p.channels.set(y,m);f.stateChanged.subscribe(T=>{t.post({type:\"channelState\",conn:p.conn,ch:y,readyState:T,id:f.id??null});if(T===\"closed\")p.channels.delete(y)});f.onMessage.subscribe(T=>{p.engine.sctpTransport?.holdReceived(pr(T));const{bytes:C,transfer:E}=typeof T===\"string\"?{bytes:T,transfer:void 0}:t.pack(T);t.postOrExtend(P=>P.type===\"message\"&&P.conn===p.conn&&P.ch===y&&P.data.push(C)>0,()=>({type:\"message\",conn:p.conn,ch:y,data:[C]}),E)});f.bufferedAmountChanged.subscribe(()=>{p.changed.add(m);t.schedule()});f.error.subscribe(T=>t.post({type:\"channelError\",conn:p.conn,ch:y,error:yi(T)}));return m},\"adopt\");const h=a((p,f)=>{const y={conn:p,engine:f,channels:new Map,changed:new Set,transceivers:new Map,transceiverRefs:new WeakMap,mirrors:new Map,mirrorRefs:new WeakMap,received:new Map,receivedRefs:new WeakMap,next:1,ops:0,seq:0,rtpOut:0,rtpRead:0};e.set(p,y);f.onIceCandidate.subscribe(m=>{const T=m?{candidate:m.candidate,sdpMid:m.sdpMid??null,sdpMLineIndex:m.sdpMLineIndex??null,usernameFragment:m.usernameFragment??null}:null;t.post({type:\"event\",conn:p,name:\"icecandidate\",candidate:T,state:c(y)})});f.onDataChannel.subscribe(m=>{const T=`w${y.next++}`;d(y,m,T);t.post({type:\"datachannel\",conn:p,ch:T,info:Xm(m)})});f.on(\"track\",m=>{t.post({type:\"track\",conn:p,transceiver:o(y,m.transceiver),streams:m.streams.map(T=>T.id),state:c(y)})});f.onNegotiationneeded.subscribe(()=>t.post({type:\"event\",conn:p,name:\"negotiationneeded\",state:c(y)}));f.connectionStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"connectionstatechange\",value:m,state:c(y)}));f.iceConnectionStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"iceconnectionstatechange\",value:m,state:c(y)}));f.iceGatheringStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"icegatheringstatechange\",value:m,state:c(y)}));f.signalingStateChange.subscribe(m=>t.post({type:\"event\",conn:p,name:\"signalingstatechange\",value:m,state:c(y)}));return y},\"open\");const l=a((p,f)=>{const y=p.mirrors.get(f);if(!y)throw new Error(`The track ${f} is not known`);return y},\"mirrorOf\");const u=a((p,f)=>{const y=p.transceivers.get(f);if(!y)throw new Error(`The transceiver ${f} is not known`);return y},\"transceiverOf\");const g=a(async(p,f)=>{const y=a(m=>m.map(T=>new us({id:T})),\"streams\");try{switch(f.type){case\"addTrack\":{const m=f.transceiver===null?null:p.transceivers.get(f.transceiver)??null;const T=p.engine.addTrackOn(m,l(p,f.track),...y(f.streams));const C=p.engine.getTransceivers().find(E=>E.sender===T);if(C)n(p,C,f.created);break}case\"addTransceiver\":{const m=p.engine.addTransceiver(f.track===void 0?f.kind:l(p,f.track),{direction:f.direction,streams:y(f.streams)});n(p,m,f.created);break}case\"removeTrack\":p.engine.removeTrack(u(p,f.transceiver).sender);break;case\"direction\":u(p,f.transceiver).direction=f.direction;break;case\"stopTransceiver\":u(p,f.transceiver).stop();break;case\"replaceTrack\":await u(p,f.transceiver).sender.replaceTrack(f.track===null?null:l(p,f.track));break;case\"setStreams\":u(p,f.transceiver).sender.setStreams(y(f.streams));break}}finally{p.ops=Math.max(p.ops,f.op);t.post({type:\"state\",conn:p.conn,state:c(p)})}},\"change\");const S=a(async p=>{switch(p.type){case\"open\":{const f=h(p.conn,new vo(ul(p.options)));return c(f)}case\"call\":{const f=s(p.conn);const y=f.engine;let m;switch(p.method){case\"createOffer\":m=Po(await y.createOffer(p.args[0]));break;case\"createAnswer\":m=Po(await y.createAnswer());break;case\"setLocalDescription\":await y.setLocalDescription(p.args[0]);break;case\"setRemoteDescription\":await y.setRemoteDescription(p.args[0]);break;case\"addIceCandidate\":{const T=p.args[0];await y.addIceCandidate({candidate:T.candidate,sdpMid:T.sdpMid??void 0,sdpMLineIndex:T.sdpMLineIndex??void 0,usernameFragment:T.usernameFragment??void 0});break}}return{result:m,state:c(f)}}case\"close\":{const f=e.get(p.conn);if(!f)return void 0;await f.engine.close();for(const y of f.mirrors.values())y.stop();e.delete(p.conn);return c(f)}case\"restartIce\":return s(p.conn).engine.restartIce();case\"setConfiguration\":return s(p.conn).engine.setConfiguration(p.configuration);case\"channel\":{const f=s(p.conn);let y;try{y=f.engine.createDataChannel(p.label,p.options)}catch(m){t.post({type:\"channelError\",conn:p.conn,ch:p.ch,error:yi(m)});t.post({type:\"channelState\",conn:p.conn,ch:p.ch,readyState:\"closed\",id:null});return void 0}d(f,y,p.ch);t.post({type:\"channelState\",conn:p.conn,ch:p.ch,readyState:y.readyState,id:y.id??null});return void 0}case\"send\":{const f=e.get(p.conn);const y=f?.channels.get(p.ch);if(!f||!y)return void 0;f.changed.add(y);for(const m of p.data){const T=typeof m===\"string\"?m:Buffer.from(m.buffer,m.byteOffset,m.byteLength);y.applied+=pr(T);try{y.engine.send(T)}catch(C){t.post({type:\"channelError\",conn:p.conn,ch:p.ch,error:yi(C)})}}return void 0}case\"closeChannel\":return e.get(p.conn)?.channels.get(p.ch)?.engine.close();case\"mirror\":{const f=s(p.conn);const y=new Be({kind:p.kind,id:p.id,remote:p.remote,...p.codec?{codec:new re(p.codec)}:{}});f.mirrors.set(p.track,y);f.mirrorRefs.set(y,p.track);return void 0}case\"rtp\":{const f=e.get(p.conn);if(!f)return void 0;const y=f.mirrors.get(p.track);if(!f.rtpRead){setImmediate(()=>{t.post({type:\"consumed\",conn:f.conn,rtp:f.rtpRead});f.rtpRead=0})}for(const m of p.packets)f.rtpRead+=m.byteLength;p.packets.forEach((m,T)=>{y?.applyIncomingRtp(W.deSerialize(Buffer.from(m.buffer,m.byteOffset,m.byteLength)),p.extensions[T]??void 0)});return void 0}case\"consumed\":{const f=e.get(p.conn);if(!f)return void 0;f.rtpOut-=p.rtp;if(p.bytes)f.engine.sctpTransport?.releaseReceived(p.bytes);return void 0}case\"source\":return e.get(p.conn)?.mirrors.get(p.track)?.onSourceChanged.execute(p.header);case\"mirrorEnded\":return e.get(p.conn)?.mirrors.get(p.track)?.stop();case\"dropTrack\":{const f=e.get(p.conn);f?.mirrors.get(p.track)?.stop();f?.mirrors.delete(p.track);return void 0}case\"addTrack\":case\"addTransceiver\":case\"removeTrack\":case\"direction\":case\"stopTransceiver\":case\"replaceTrack\":case\"setStreams\":return await g(s(p.conn),p);case\"keyframe\":{const f=e.get(p.conn)?.received.get(p.track);const y=f?.track.ssrc;if(f&&y!==void 0)void f.receiver.sendRtcpPLI(y);return void 0}case\"want\":{const f=e.get(p.conn);const y=f?.received.get(p.track);if(!f||!y)return void 0;y.unsubscribe?.();y.unsubscribe=void 0;if(p.wanted){const m=p.track;y.unsubscribe=y.track.onReceiveRtp.subscribe((T,C)=>{const E=T.serialize();if(f.rtpOut+E.length>fl)return Jm(\"a packet of the track %s dropped: the main thread reads too slowly\",m);f.rtpOut+=E.length;const{bytes:P,transfer:de}=t.pack(E);t.postOrExtend(q=>q.type===\"rtp\"&&q.conn===f.conn&&q.track===m&&q.packets.push(P)>0&&q.extensions.push(C??null)>0,()=>({type:\"rtp\",conn:f.conn,track:m,packets:[P],extensions:[C??null]}),de)}).unSubscribe}return void 0}case\"debug\":return kc(p.enabled?(f,y)=>t.post({type:\"log\",namespace:f,message:`[thread ${r.thread}] ${(0,ml.format)(...y)}`}):void 0);case\"stop\":{const f=[...e.values()];e.clear();await Promise.all(f.map(y=>y.engine.close()));return void 0}}},\"handle\");t.post({type:\"ready\"})}a(gl,\"runPeerWorker\");gl();\n";