@urun-sh/core 0.1.42 → 0.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,136 +1,7 @@
1
- "use strict";var uN=Object.create;var o0=Object.defineProperty;var fN=Object.getOwnPropertyDescriptor;var lN=Object.getOwnPropertyNames;var hN=Object.getPrototypeOf,pN=Object.prototype.hasOwnProperty;var A=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(s){throw t=[s],s}};var se=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Tf=(r,e)=>{for(var t in e)o0(r,t,{get:e[t],enumerable:!0})},_E=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lN(e))!pN.call(r,n)&&n!==t&&o0(r,n,{get:()=>e[n],enumerable:!(s=fN(e,n))||s.enumerable});return r};var Ge=(r,e,t)=>(t=r!=null?uN(hN(r)):{},_E(e||!r||!r.__esModule?o0(t,"default",{value:r,enumerable:!0}):t,r)),Bx=r=>_E(o0({},"__esModule",{value:!0}),r);var Nx=se((QV,EE)=>{"use strict";var md=1e3,gd=md*60,yd=gd*60,Ra=yd*24,mN=Ra*7,gN=Ra*365.25;EE.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return yN(r);if(t==="number"&&isFinite(r))return e.long?bN(r):xN(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function yN(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*gN;case"weeks":case"week":case"w":return t*mN;case"days":case"day":case"d":return t*Ra;case"hours":case"hour":case"hrs":case"hr":case"h":return t*yd;case"minutes":case"minute":case"mins":case"min":case"m":return t*gd;case"seconds":case"second":case"secs":case"sec":case"s":return t*md;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function xN(r){var e=Math.abs(r);return e>=Ra?Math.round(r/Ra)+"d":e>=yd?Math.round(r/yd)+"h":e>=gd?Math.round(r/gd)+"m":e>=md?Math.round(r/md)+"s":r+"ms"}function bN(r){var e=Math.abs(r);return e>=Ra?a0(r,e,Ra,"day"):e>=yd?a0(r,e,yd,"hour"):e>=gd?a0(r,e,gd,"minute"):e>=md?a0(r,e,md,"second"):r+" ms"}function a0(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var Ox=se((ZV,CE)=>{"use strict";function vN(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Nx(),t.destroy=d,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let h=0;h<u.length;h++)f=(f<<5)-f+u.charCodeAt(h),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,h=null,y,v;function S(...C){if(!S.enabled)return;let O=S,K=Number(new Date),z=K-(f||K);O.diff=z,O.prev=f,O.curr=K,f=K,C[0]=t.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let Q=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(te,Ee)=>{if(te==="%%")return"%";Q++;let ge=t.formatters[Ee];if(typeof ge=="function"){let Y=C[Q];te=ge.call(O,Y),C.splice(Q,1),Q--}return te}),t.formatArgs.call(O,C),(O.log||t.log).apply(O,C)}return S.namespace=u,S.useColors=t.useColors(),S.color=t.selectColor(u),S.extend=s,S.destroy=t.destroy,Object.defineProperty(S,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,v=t.enabled(u)),v),set:C=>{h=C}}),typeof t.init=="function"&&t.init(S),S}function s(u,f){let h=t(this.namespace+(typeof f>"u"?":":f)+u);return h.log=this.log,h}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of f)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function i(u,f){let h=0,y=0,v=-1,S=0;for(;h<u.length;)if(y<f.length&&(f[y]===u[h]||f[y]==="*"))f[y]==="*"?(v=y,S=h,y++):(h++,y++);else if(v!==-1)y=v+1,S++,h=S;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function o(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(i(u,f))return!1;for(let f of t.names)if(i(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}CE.exports=vN});var TE=se((os,c0)=>{"use strict";os.formatArgs=SN;os.save=_N;os.load=EN;os.useColors=wN;os.storage=CN();os.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();os.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function wN(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function SN(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+c0.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}os.log=console.debug||console.log||(()=>{});function _N(r){try{r?os.storage.setItem("debug",r):os.storage.removeItem("debug")}catch{}}function EN(){let r;try{r=os.storage.getItem("debug")||os.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function CN(){try{return localStorage}catch{}}c0.exports=Ox()(os);var{formatters:TN}=c0.exports;TN.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Mx={};Tf(Mx,{createSupportsColor:()=>Dx,default:()=>PN});function Os(r,e=globalThis.Deno?globalThis.Deno.args:u0.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}function AN(){if(!("FORCE_COLOR"in Jt))return;if(Jt.FORCE_COLOR==="true")return 1;if(Jt.FORCE_COLOR==="false")return 0;if(Jt.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Jt.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function IN(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function RN(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=AN();s!==void 0&&(d0=s);let n=t?d0:s;if(n===0)return 0;if(t){if(Os("color=16m")||Os("color=full")||Os("color=truecolor"))return 3;if(Os("color=256"))return 2}if("TF_BUILD"in Jt&&"AGENT_NAME"in Jt)return 1;if(r&&!e&&n===void 0)return 0;let i=n||0;if(Jt.TERM==="dumb")return i;if(u0.default.platform==="win32"){let o=AE.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Jt)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Jt)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Jt)||Jt.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Jt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Jt.TEAMCITY_VERSION)?1:0;if(Jt.COLORTERM==="truecolor"||Jt.TERM==="xterm-kitty"||Jt.TERM==="xterm-ghostty"||Jt.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Jt){let o=Number.parseInt((Jt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Jt.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Jt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Jt.TERM)||"COLORTERM"in Jt?1:i}function Dx(r,e={}){let t=RN(r,{streamIsTTY:r&&r.isTTY,...e});return IN(t)}var u0,AE,Lx,Jt,d0,kN,PN,Ux=A(()=>{"use strict";u0=Ge(require("process"),1),AE=Ge(require("os"),1),Lx=Ge(require("tty"),1);({env:Jt}=u0.default);Os("no-color")||Os("no-colors")||Os("color=false")||Os("color=never")?d0=0:(Os("color")||Os("colors")||Os("color=true")||Os("color=always"))&&(d0=1);kN={stdout:Dx({isTTY:Lx.default.isatty(1)}),stderr:Dx({isTTY:Lx.default.isatty(2)})},PN=kN});var RE=se((Sr,l0)=>{"use strict";var BN=require("tty"),f0=require("util");Sr.init=jN;Sr.log=DN;Sr.formatArgs=ON;Sr.save=MN;Sr.load=UN;Sr.useColors=NN;Sr.destroy=f0.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Sr.colors=[6,2,3,4,5,1];try{let r=(Ux(),Bx(Mx));r&&(r.stderr||r).level>=2&&(Sr.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Sr.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function NN(){return"colors"in Sr.inspectOpts?!!Sr.inspectOpts.colors:BN.isatty(process.stderr.fd)}function ON(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),i=` ${n};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
1
+ "use strict";var oo=Object.create;var Ot=Object.defineProperty;var ao=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var po=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var uo=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(r){throw t=[r],r}};var C=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Us=(s,e)=>{for(var t in e)Ot(s,t,{get:e[t],enumerable:!0})},zs=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of co(e))!lo.call(s,n)&&n!==t&&Ot(s,n,{get:()=>e[n],enumerable:!(r=ao(e,n))||r.enumerable});return s};var Se=(s,e,t)=>(t=s!=null?oo(po(s)):{},zs(e||!s||!s.__esModule?Ot(t,"default",{value:s,enumerable:!0}):t,s)),Bs=s=>zs(Ot({},"__esModule",{value:!0}),s);var Ws=C((vp,Vs)=>{"use strict";var $e=1e3,Ue=$e*60,ze=Ue*60,Ee=ze*24,ho=Ee*7,fo=Ee*365.25;Vs.exports=function(s,e){e=e||{};var t=typeof s;if(t==="string"&&s.length>0)return mo(s);if(t==="number"&&isFinite(s))return e.long?_o(s):go(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};function mo(s){if(s=String(s),!(s.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*fo;case"weeks":case"week":case"w":return t*ho;case"days":case"day":case"d":return t*Ee;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ze;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ue;case"seconds":case"second":case"secs":case"sec":case"s":return t*$e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function go(s){var e=Math.abs(s);return e>=Ee?Math.round(s/Ee)+"d":e>=ze?Math.round(s/ze)+"h":e>=Ue?Math.round(s/Ue)+"m":e>=$e?Math.round(s/$e)+"s":s+"ms"}function _o(s){var e=Math.abs(s);return e>=Ee?At(s,e,Ee,"day"):e>=ze?At(s,e,ze,"hour"):e>=Ue?At(s,e,Ue,"minute"):e>=$e?At(s,e,$e,"second"):s+" ms"}function At(s,e,t,r){var n=e>=t*1.5;return Math.round(s/t)+" "+r+(n?"s":"")}});var xr=C((wp,Hs)=>{"use strict";function vo(s){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Ws(),t.destroy=d,Object.keys(s).forEach(p=>{t[p]=s[p]}),t.names=[],t.skips=[],t.formatters={};function e(p){let l=0;for(let u=0;u<p.length;u++)l=(l<<5)-l+p.charCodeAt(u),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(p){let l,u=null,m,f;function h(...g){if(!h.enabled)return;let _=h,y=Number(new Date),x=y-(l||y);_.diff=x,_.prev=l,_.curr=y,l=y,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let P=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(I,he)=>{if(I==="%%")return"%";P++;let ae=t.formatters[he];if(typeof ae=="function"){let Y=g[P];I=ae.call(_,Y),g.splice(P,1),P--}return I}),t.formatArgs.call(_,g),(_.log||t.log).apply(_,g)}return h.namespace=p,h.useColors=t.useColors(),h.color=t.selectColor(p),h.extend=r,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(m!==t.namespaces&&(m=t.namespaces,f=t.enabled(p)),f),set:g=>{u=g}}),typeof t.init=="function"&&t.init(h),h}function r(p,l){let u=t(this.namespace+(typeof l>"u"?":":l)+p);return u.log=this.log,u}function n(p){t.save(p),t.namespaces=p,t.names=[],t.skips=[];let l=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let u of l)u[0]==="-"?t.skips.push(u.slice(1)):t.names.push(u)}function i(p,l){let u=0,m=0,f=-1,h=0;for(;u<p.length;)if(m<l.length&&(l[m]===p[u]||l[m]==="*"))l[m]==="*"?(f=m,h=u,m++):(u++,m++);else if(f!==-1)m=f+1,h++,u=h;else return!1;for(;m<l.length&&l[m]==="*";)m++;return m===l.length}function o(){let p=[...t.names,...t.skips.map(l=>"-"+l)].join(",");return t.enable(""),p}function a(p){for(let l of t.skips)if(i(p,l))return!1;for(let l of t.names)if(i(p,l))return!0;return!1}function c(p){return p instanceof Error?p.stack||p.message:p}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Hs.exports=vo});var Gs=C((H,Nt)=>{"use strict";H.formatArgs=yo;H.save=bo;H.load=So;H.useColors=wo;H.storage=Ro();H.destroy=(()=>{let s=!1;return()=>{s||(s=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();H.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function wo(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let s;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(s=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(s[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function yo(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+Nt.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;s.splice(1,0,e,"color: inherit");let t=0,r=0;s[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(r=t))}),s.splice(r,0,e)}H.log=console.debug||console.log||(()=>{});function bo(s){try{s?H.storage.setItem("debug",s):H.storage.removeItem("debug")}catch{}}function So(){let s;try{s=H.storage.getItem("debug")||H.storage.getItem("DEBUG")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=process.env.DEBUG),s}function Ro(){try{return localStorage}catch{}}Nt.exports=xr()(H);var{formatters:Co}=Nt.exports;Co.j=function(s){try{return JSON.stringify(s)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Qs={};Us(Qs,{createSupportsColor:()=>Dr,default:()=>Po});function J(s,e=globalThis.Deno?globalThis.Deno.args:Ft.default.argv){let t=s.startsWith("-")?"":s.length===1?"-":"--",r=e.indexOf(t+s),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}function To(){if(!("FORCE_COLOR"in O))return;if(O.FORCE_COLOR==="true")return 1;if(O.FORCE_COLOR==="false")return 0;if(O.FORCE_COLOR.length===0)return 1;let s=Math.min(Number.parseInt(O.FORCE_COLOR,10),3);if([0,1,2,3].includes(s))return s}function Eo(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function ko(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let r=To();r!==void 0&&(jt=r);let n=t?jt:r;if(n===0)return 0;if(t){if(J("color=16m")||J("color=full")||J("color=truecolor"))return 3;if(J("color=256"))return 2}if("TF_BUILD"in O&&"AGENT_NAME"in O)return 1;if(s&&!e&&n===void 0)return 0;let i=n||0;if(O.TERM==="dumb")return i;if(Ft.default.platform==="win32"){let o=Ks.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in O)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in O)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in O)||O.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in O)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(O.TEAMCITY_VERSION)?1:0;if(O.COLORTERM==="truecolor"||O.TERM==="xterm-kitty"||O.TERM==="xterm-ghostty"||O.TERM==="wezterm")return 3;if("TERM_PROGRAM"in O){let o=Number.parseInt((O.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(O.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(O.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(O.TERM)||"COLORTERM"in O?1:i}function Dr(s,e={}){let t=ko(s,{streamIsTTY:s&&s.isTTY,...e});return Eo(t)}var Ft,Ks,Pr,O,jt,xo,Po,Ys=uo(()=>{"use strict";Ft=Se(require("process"),1),Ks=Se(require("os"),1),Pr=Se(require("tty"),1);({env:O}=Ft.default);J("no-color")||J("no-colors")||J("color=false")||J("color=never")?jt=0:(J("color")||J("colors")||J("color=true")||J("color=always"))&&(jt=1);xo={stdout:Dr({isTTY:Pr.default.isatty(1)}),stderr:Dr({isTTY:Pr.default.isatty(2)})},Po=xo});var Xs=C((F,$t)=>{"use strict";var Do=require("tty"),qt=require("util");F.init=jo;F.log=Oo;F.formatArgs=Lo;F.save=Ao;F.load=No;F.useColors=Io;F.destroy=qt.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");F.colors=[6,2,3,4,5,1];try{let s=(Ys(),Bs(Qs));s&&(s.stderr||s).level>=2&&(F.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}F.inspectOpts=Object.keys(process.env).filter(s=>/^debug_/i.test(s)).reduce((s,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),s[t]=r,s},{});function Io(){return"colors"in F.inspectOpts?!!F.inspectOpts.colors:Do.isatty(process.stderr.fd)}function Lo(s){let{namespace:e,useColors:t}=this;if(t){let r=this.color,n="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${n};1m${e} \x1B[0m`;s[0]=i+s[0].split(`
2
2
  `).join(`
3
- `+i),r.push(n+"m+"+l0.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=LN()+e+" "+r[0]}function LN(){return Sr.inspectOpts.hideDate?"":new Date().toISOString()+" "}function DN(...r){return process.stderr.write(f0.formatWithOptions(Sr.inspectOpts,...r)+`
4
- `)}function MN(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function UN(){return process.env.DEBUG}function jN(r){r.inspectOpts={};let e=Object.keys(Sr.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Sr.inspectOpts[e[t]]}l0.exports=Ox()(Sr);var{formatters:IE}=l0.exports;IE.o=function(r){return this.inspectOpts.colors=this.useColors,f0.inspect(r,this.inspectOpts).split(`
5
- `).map(e=>e.trim()).join(" ")};IE.O=function(r){return this.inspectOpts.colors=this.useColors,f0.inspect(r,this.inspectOpts)}});var Af=se((eK,jx)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?jx.exports=TE():jx.exports=RE()});var PE=se(kE=>{"use strict";Object.defineProperty(kE,"__esModule",{value:!0})});var Yr=se(h0=>{"use strict";Object.defineProperty(h0,"__esModule",{value:!0});h0.Logger=void 0;var xd=Af(),bd="media-client",Hx=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,xd.default)(`${bd}:${e}`),this._warn=(0,xd.default)(`${bd}:WARN:${e}`),this._error=(0,xd.default)(`${bd}:ERROR:${e}`)):(this._debug=(0,xd.default)(bd),this._warn=(0,xd.default)(`${bd}:WARN`),this._error=(0,xd.default)(`${bd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};h0.Logger=Hx});var qE=se((sK,Fx)=>{"use strict";var vd=typeof Reflect=="object"?Reflect:null,BE=vd&&typeof vd.apply=="function"?vd.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)},p0;vd&&typeof vd.ownKeys=="function"?p0=vd.ownKeys:Object.getOwnPropertySymbols?p0=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:p0=function(e){return Object.getOwnPropertyNames(e)};function HN(r){console&&console.warn&&console.warn(r)}var OE=Number.isNaN||function(e){return e!==e};function Ht(){Ht.init.call(this)}Fx.exports=Ht;Fx.exports.once=$N;Ht.EventEmitter=Ht;Ht.prototype._events=void 0;Ht.prototype._eventsCount=0;Ht.prototype._maxListeners=void 0;var NE=10;function m0(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(Ht,"defaultMaxListeners",{enumerable:!0,get:function(){return NE},set:function(r){if(typeof r!="number"||r<0||OE(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");NE=r}});Ht.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ht.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||OE(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function LE(r){return r._maxListeners===void 0?Ht.defaultMaxListeners:r._maxListeners}Ht.prototype.getMaxListeners=function(){return LE(this)};Ht.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")BE(c,this,t);else for(var d=c.length,u=HE(c,d),s=0;s<d;++s)BE(u[s],this,t);return!0};function DE(r,e,t,s){var n,i,o;if(m0(t),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),i=r._events),o=i[e]),o===void 0)o=i[e]=t,++r._eventsCount;else if(typeof o=="function"?o=i[e]=s?[t,o]:[o,t]:s?o.unshift(t):o.push(t),n=LE(r),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,HN(a)}return r}Ht.prototype.addListener=function(e,t){return DE(this,e,t,!1)};Ht.prototype.on=Ht.prototype.addListener;Ht.prototype.prependListener=function(e,t){return DE(this,e,t,!0)};function FN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ME(r,e,t){var s={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},n=FN.bind(s);return n.listener=t,s.wrapFn=n,n}Ht.prototype.once=function(e,t){return m0(t),this.on(e,ME(this,e,t)),this};Ht.prototype.prependOnceListener=function(e,t){return m0(t),this.prependListener(e,ME(this,e,t)),this};Ht.prototype.removeListener=function(e,t){var s,n,i,o,a;if(m0(t),n=this._events,n===void 0)return this;if(s=n[e],s===void 0)return this;if(s===t||s.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||t));else if(typeof s!="function"){for(i=-1,o=s.length-1;o>=0;o--)if(s[o]===t||s[o].listener===t){a=s[o].listener,i=o;break}if(i<0)return this;i===0?s.shift():qN(s,i),s.length===1&&(n[e]=s[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};Ht.prototype.off=Ht.prototype.removeListener;Ht.prototype.removeAllListeners=function(e){var t,s,n;if(s=this._events,s===void 0)return this;if(s.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):s[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete s[e]),this;if(arguments.length===0){var i=Object.keys(s),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=s[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function UE(r,e,t){var s=r._events;if(s===void 0)return[];var n=s[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?zN(n):HE(n,n.length)}Ht.prototype.listeners=function(e){return UE(this,e,!0)};Ht.prototype.rawListeners=function(e){return UE(this,e,!1)};Ht.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):jE.call(r,e)};Ht.prototype.listenerCount=jE;function jE(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Ht.prototype.eventNames=function(){return this._eventsCount>0?p0(this._events):[]};function HE(r,e){for(var t=new Array(e),s=0;s<e;++s)t[s]=r[s];return t}function qN(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function zN(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function $N(r,e){return new Promise(function(t,s){function n(o){r.removeListener(e,i),s(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",n),t([].slice.call(arguments))}FE(r,e,i,{once:!0}),e!=="error"&&VN(r,n,{once:!0})})}function VN(r,e,t){typeof r.on=="function"&&FE(r,"error",e,t)}function FE(r,e,t,s){if(typeof r.on=="function")s.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function n(i){s.once&&r.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var as=se(g0=>{"use strict";Object.defineProperty(g0,"__esModule",{value:!0});g0.EnhancedEventEmitter=void 0;var KN=qE(),WN=Yr(),GN=new WN.Logger("EnhancedEventEmitter"),qx=class extends KN.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(s){GN.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,s);try{super.emit("listenererror",e,s)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};g0.EnhancedEventEmitter=qx});var Ls=se(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.InvalidStateError=wd.UnsupportedError=void 0;var zx=class r extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};wd.UnsupportedError=zx;var $x=class r extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};wd.InvalidStateError=$x});var ka=se(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});If.clone=XN;If.generateRandomNumber=YN;If.deepFreeze=zE;function XN(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}function YN(){return Math.round(Math.random()*1e7)}function zE(r){let e=Reflect.ownKeys(r);for(let t of e){let s=r[t];(s&&typeof s=="object"||typeof s=="function")&&zE(s)}return Object.freeze(r)}});var $E=se(y0=>{"use strict";Object.defineProperty(y0,"__esModule",{value:!0});y0.Logger=void 0;var Sd=Af(),_d="h264-profile-level-id",Vx=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Sd.default)(`${_d}:${e}`),this._warn=(0,Sd.default)(`${_d}:WARN:${e}`),this._error=(0,Sd.default)(`${_d}:ERROR:${e}`)):(this._debug=(0,Sd.default)(_d),this._warn=(0,Sd.default)(`${_d}:WARN`),this._error=(0,Sd.default)(`${_d}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};y0.Logger=Vx});var YE=se(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.ProfileLevelId=Tr.Level=Tr.Profile=void 0;Tr.parseProfileLevelId=GE;Tr.profileLevelIdToString=XE;Tr.profileToString=eO;Tr.levelToString=tO;Tr.parseSdpProfileLevelId=Pa;Tr.isSameProfile=rO;Tr.isSameProfileAndLevel=sO;Tr.generateProfileLevelIdStringForAnswer=nO;Tr.supportedLevel=iO;var JN=$E(),rn=new JN.Logger,zt;(function(r){r[r.ConstrainedBaseline=1]="ConstrainedBaseline",r[r.Baseline=2]="Baseline",r[r.Main=3]="Main",r[r.ConstrainedHigh=4]="ConstrainedHigh",r[r.High=5]="High",r[r.PredictiveHigh444=6]="PredictiveHigh444"})(zt||(Tr.Profile=zt={}));var De;(function(r){r[r.L1_b=0]="L1_b",r[r.L1=10]="L1",r[r.L1_1=11]="L1_1",r[r.L1_2=12]="L1_2",r[r.L1_3=13]="L1_3",r[r.L2=20]="L2",r[r.L2_1=21]="L2_1",r[r.L2_2=22]="L2_2",r[r.L3=30]="L3",r[r.L3_1=31]="L3_1",r[r.L3_2=32]="L3_2",r[r.L4=40]="L4",r[r.L4_1=41]="L4_1",r[r.L4_2=42]="L4_2",r[r.L5=50]="L5",r[r.L5_1=51]="L5_1",r[r.L5_2=52]="L5_2"})(De||(Tr.Level=De={}));var Ed=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};Tr.ProfileLevelId=Ed;var QN=new Ed(zt.ConstrainedBaseline,De.L3_1),en=class{mask;masked_value;constructor(e){this.mask=~KE("x",e),this.masked_value=KE("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},tn=class{profile_idc;profile_iop;profile;constructor(e,t,s){this.profile_idc=e,this.profile_iop=t,this.profile=s}},ZN=[new tn(66,new en("x1xx0000"),zt.ConstrainedBaseline),new tn(77,new en("1xxx0000"),zt.ConstrainedBaseline),new tn(88,new en("11xx0000"),zt.ConstrainedBaseline),new tn(66,new en("x0xx0000"),zt.Baseline),new tn(88,new en("10xx0000"),zt.Baseline),new tn(77,new en("0x0x0000"),zt.Main),new tn(100,new en("00000000"),zt.High),new tn(100,new en("00001100"),zt.ConstrainedHigh),new tn(244,new en("00000000"),zt.PredictiveHigh444)],VE=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:De.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:De.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:De.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:De.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:De.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:De.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:De.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:De.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:De.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:De.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:De.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:De.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:De.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:De.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:De.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:De.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:De.L5_2}];function GE(r){if(typeof r!="string"||r.length!==6)return;let t=parseInt(r,16);if(t===0)return;let s=t&255,n=t>>8&255,i=t>>16&255,o;switch(s){case De.L1_1:{o=(n&16)!==0?De.L1_b:De.L1_1;break}case De.L1:case De.L1_2:case De.L1_3:case De.L2:case De.L2_1:case De.L2_2:case De.L3:case De.L3_1:case De.L3_2:case De.L4:case De.L4_1:case De.L4_2:case De.L5:case De.L5_1:case De.L5_2:{o=s;break}default:{rn.warn(`parseProfileLevelId() | unrecognized level_idc [str:${r}, level_idc:${s}]`);return}}for(let a of ZN)if(i===a.profile_idc&&a.profile_iop.isMatch(n))return rn.debug(`parseProfileLevelId() | result [str:${r}, profile:${a.profile}, level:${o}]`),new Ed(a.profile,o);rn.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${r}, profile_idc:${i}, profile_iop:${n}]`)}function XE(r){if(r.level==De.L1_b)switch(r.profile){case zt.ConstrainedBaseline:return"42f00b";case zt.Baseline:return"42100b";case zt.Main:return"4d100b";default:{rn.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${r.profile}`);return}}let e;switch(r.profile){case zt.ConstrainedBaseline:{e="42e0";break}case zt.Baseline:{e="4200";break}case zt.Main:{e="4d00";break}case zt.ConstrainedHigh:{e="640c";break}case zt.High:{e="6400";break}case zt.PredictiveHigh444:{e="f400";break}default:{rn.warn(`profileLevelIdToString() | unrecognized profile ${r.profile}`);return}}let t=r.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function eO(r){switch(r){case zt.ConstrainedBaseline:return"ConstrainedBaseline";case zt.Baseline:return"Baseline";case zt.Main:return"Main";case zt.ConstrainedHigh:return"ConstrainedHigh";case zt.High:return"High";case zt.PredictiveHigh444:return"PredictiveHigh444";default:{rn.warn(`profileToString() | unrecognized profile ${r}`);return}}}function tO(r){switch(r){case De.L1_b:return"1b";case De.L1:return"1";case De.L1_1:return"1.1";case De.L1_2:return"1.2";case De.L1_3:return"1.3";case De.L2:return"2";case De.L2_1:return"2.1";case De.L2_2:return"2.2";case De.L3:return"3";case De.L3_1:return"3.1";case De.L3_2:return"3.2";case De.L4:return"4";case De.L4_1:return"4.1";case De.L4_2:return"4.2";case De.L5:return"5";case De.L5_1:return"5.1";case De.L5_2:return"5.2";default:{rn.warn(`levelToString() | unrecognized level ${r}`);return}}}function Pa(r={}){let e=r["profile-level-id"];return e?GE(e):QN}function rO(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile)}function sO(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile&&t.level==s.level)}function nO(r={},e={}){if(!r["profile-level-id"]&&!e["profile-level-id"]){rn.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=Pa(r),s=Pa(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!s)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==s.profile)throw new TypeError("H264 Profile mismatch");let n=WE(r)&&WE(e),i=t.level,o=s.level,a=aO(i,o),c=n?i:a;return rn.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),XE(new Ed(t.profile,c))}function iO(r,e){for(let s=VE.length-1;s>=0;--s){let n=VE[s];if(n.max_macroblock_frame_size*256<=r&&n.max_macroblocks_per_second<=e*n.max_macroblock_frame_size)return rn.debug(`supportedLevel() | result [max_frame_pixel_count:${r}, max_fps:${e}, level:${n.level}]`),n.level}rn.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${r}, max_fps:${e}]`)}function KE(r,e){return+(e[0]===r)<<7|+(e[1]===r)<<6|+(e[2]===r)<<5|+(e[3]===r)<<4|+(e[4]===r)<<3|+(e[5]===r)<<2|+(e[6]===r)<<1|+(e[7]===r)<<0}function oO(r,e){return r===De.L1_b?e!==De.L1&&e!==De.L1_b:e===De.L1_b?r!==De.L1:r<e}function aO(r,e){return oO(r,e)?r:e}function WE(r={}){let e=r["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var kn=se(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.validateAndNormalizeRtpCapabilities=lO;Jr.validateAndNormalizeRtpParameters=Wx;Jr.validateAndNormalizeSctpStreamParameters=hO;Jr.validateSctpCapabilities=pO;Jr.getExtendedRtpCapabilities=mO;Jr.getRecvRtpCapabilities=gO;Jr.getSendRtpCapabilities=yO;Jr.getSendingRtpParameters=xO;Jr.getSendingRemoteRtpParameters=bO;Jr.reduceCodecs=vO;Jr.generateProbatorRtpParameters=wO;Jr.canSend=SO;Jr.canReceive=_O;var JE=YE(),cO=ka(),dO="probator",uO=1234,fO=127;function lO(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(r.codecs&&!Array.isArray(r.codecs))throw new TypeError("caps.codecs is not an array");r.codecs||(r.codecs=[]);for(let e of r.codecs)EO(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)CO(e)}function Wx(r){if(typeof r!="object")throw new TypeError("params is not an object");if(r.mid&&typeof r.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(r.codecs))throw new TypeError("missing params.codecs");for(let e of r.codecs)TO(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("params.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)AO(e);if(r.encodings&&!Array.isArray(r.encodings))throw new TypeError("params.encodings is not an array");r.encodings||(r.encodings=[]);for(let e of r.encodings)IO(e);if(r.rtcp&&typeof r.rtcp!="object")throw new TypeError("params.rtcp is not an object");r.rtcp||(r.rtcp={}),RO(r.rtcp)}function hO(r){if(typeof r!="object")throw new TypeError("params is not an object");if(typeof r.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof r.ordered=="boolean"?e=!0:r.ordered=!0,r.maxPacketLifeTime&&typeof r.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(r.maxRetransmits&&typeof r.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(r.maxPacketLifeTime&&r.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&r.ordered&&(r.maxPacketLifeTime||r.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(r.maxPacketLifeTime||r.maxRetransmits)&&(r.ordered=!1),r.label&&typeof r.label!="string")throw new TypeError("invalid params.label");if(r.protocol&&typeof r.protocol!="string")throw new TypeError("invalid params.protocol")}function pO(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(!r.numStreams||typeof r.numStreams!="object")throw new TypeError("missing caps.numStreams");kO(r.numStreams)}function mO(r,e,t){let s={codecs:[],headerExtensions:[]};if(t)for(let n of r.codecs??[]){if(Cd(n))continue;let i=(e.codecs??[]).find(a=>Kx(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:n.kind,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,localPayloadType:n.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:n.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:QE(n,i)};s.codecs.push(o)}else for(let n of e.codecs??[]){if(Cd(n))continue;let i=(r.codecs??[]).find(a=>Kx(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:n.parameters??{},rtcpFeedback:QE(i,n)};s.codecs.push(o)}for(let n of s.codecs){let i=r.codecs.find(a=>Cd(a)&&a.parameters?.apt===n.localPayloadType),o=e.codecs.find(a=>Cd(a)&&a.parameters?.apt===n.remotePayloadType);i&&o&&(n.localRtxPayloadType=i.preferredPayloadType,n.remoteRtxPayloadType=o.preferredPayloadType)}for(let n of e.headerExtensions){let i=r.headerExtensions.find(a=>PO(a,n));if(!i)continue;let o={kind:n.kind,uri:n.uri,sendId:i.preferredId,recvId:n.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(n.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}s.headerExtensions.push(o)}return s}function gO(r){return eC({direction:"recvonly",extendedRtpCapabilities:r})}function yO(r){return eC({direction:"sendonly",extendedRtpCapabilities:r})}function xO(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let s of e.codecs){if(s.kind!==r)continue;let n={mimeType:s.mimeType,payloadType:s.localPayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.localParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),s.localRtxPayloadType){let i={mimeType:`${s.kind}/rtx`,payloadType:s.localRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let s of e.headerExtensions){if(s.kind&&s.kind!==r||s.direction!=="sendrecv"&&s.direction!=="sendonly")continue;let n={uri:s.uri,id:s.sendId,encrypt:s.encrypt,parameters:{}};t.headerExtensions.push(n)}return t}function bO(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let s of e.codecs){if(s.kind!==r)continue;let n={mimeType:s.mimeType,payloadType:s.localPayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.remoteParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),s.localRtxPayloadType){let i={mimeType:`${s.kind}/rtx`,payloadType:s.localRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let s of e.headerExtensions){if(s.kind&&s.kind!==r||s.direction!=="sendrecv"&&s.direction!=="sendonly")continue;let n={uri:s.uri,id:s.sendId,encrypt:s.encrypt,parameters:{}};t.headerExtensions.push(n)}if(t.headerExtensions.some(s=>s.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="goog-remb");else if(t.headerExtensions.some(s=>s.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc");else for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc"&&n.type!=="goog-remb");return t}function vO(r,e){let t=[];if(!e)t.push(r[0]),Cd(r[1])&&t.push(r[1]);else{for(let s=0;s<r.length;++s)if(Kx(r[s],e,{strict:!0})){t.push(r[s]),Cd(r[s+1])&&t.push(r[s+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function wO(r){r=cO.clone(r),Wx(r);let e={mid:dO,codecs:[],headerExtensions:[],encodings:[{ssrc:uO}],rtcp:{cname:"probator"}};return e.codecs.push(r.codecs[0]),e.codecs[0].payloadType=fO,e.headerExtensions=r.headerExtensions,e}function SO(r,e){return(e.codecs??[]).some(t=>t.kind===r)}function _O(r,e){if(Wx(r),r.codecs.length===0)return!1;let t=r.codecs[0];return(e.codecs??[]).some(s=>s.preferredPayloadType===t.payloadType)}function EO(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(r.kind=t[1].toLowerCase(),typeof r.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");r.kind==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let s of Object.keys(r.parameters)){let n=r.parameters[s];if(n===void 0&&(r.parameters[s]="",n=""),typeof n!="string"&&typeof n!="number")throw new TypeError(`invalid codec parameter [key:${s}s, value:${n}]`);if(s==="apt"&&typeof n!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let s of r.rtcpFeedback)ZE(s)}function ZE(r){if(typeof r!="object")throw new TypeError("fb is not an object");if(!r.type||typeof r.type!="string")throw new TypeError("missing fb.type");(!r.parameter||typeof r.parameter!="string")&&(r.parameter="")}function CO(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(r.kind!=="audio"&&r.kind!=="video")throw new TypeError("invalid ext.kind");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.preferredId!="number")throw new TypeError("missing ext.preferredId");if(r.preferredEncrypt&&typeof r.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(r.preferredEncrypt||(r.preferredEncrypt=!1),r.direction&&typeof r.direction!="string")throw new TypeError("invalid ext.direction");r.direction||(r.direction="sendrecv")}function TO(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof r.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let n of Object.keys(r.parameters)){let i=r.parameters[n];if(i===void 0&&(r.parameters[n]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${i}]`);if(n==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let n of r.rtcpFeedback)ZE(n)}function AO(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.id!="number")throw new TypeError("missing ext.id");if(r.encrypt&&typeof r.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");r.encrypt||(r.encrypt=!1),(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let e of Object.keys(r.parameters)){let t=r.parameters[e];if(t===void 0&&(r.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function IO(r){if(typeof r!="object")throw new TypeError("encoding is not an object");if(r.ssrc&&typeof r.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(r.rid&&typeof r.rid!="string")throw new TypeError("invalid encoding.rid");if(r.rtx&&typeof r.rtx!="object")throw new TypeError("invalid encoding.rtx");if(r.rtx&&typeof r.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!r.dtx||typeof r.dtx!="boolean")&&(r.dtx=!1),r.scalabilityMode&&typeof r.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function RO(r){if(typeof r!="object")throw new TypeError("rtcp is not an object");if(r.cname&&typeof r.cname!="string")throw new TypeError("invalid rtcp.cname");(!r.reducedSize||typeof r.reducedSize!="boolean")&&(r.reducedSize=!0)}function kO(r){if(typeof r!="object")throw new TypeError("numStreams is not an object");if(typeof r.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof r.MIS!="number")throw new TypeError("missing numStreams.MIS")}function eC({direction:r,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let s of e.codecs){let n={kind:s.kind,mimeType:s.mimeType,preferredPayloadType:s.remotePayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.localParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),!s.remoteRtxPayloadType)continue;let i={kind:s.kind,mimeType:`${s.kind}/rtx`,preferredPayloadType:s.remoteRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let s of e.headerExtensions){if(s.direction!=="sendrecv"&&s.direction!==r)continue;let n={kind:s.kind,uri:s.uri,preferredId:s.recvId,preferredEncrypt:s.encrypt??!1,direction:s.direction};t.headerExtensions.push(n)}return t}function Cd(r){return r?/.+\/rtx$/i.test(r.mimeType):!1}function Kx(r,e,{strict:t=!1,modify:s=!1}={}){let n=r.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(n!==i||r.clockRate!==e.clockRate||r.channels!==e.channels)return!1;switch(n){case"video/h264":{if(t){let o=r.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!JE.isSameProfile(r.parameters,e.parameters))return!1;let c;try{c=JE.generateProfileLevelIdStringForAnswer(r.parameters,e.parameters)}catch{return!1}s&&(c?(r.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete r.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=r.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function PO(r,e){return!(r.kind&&e.kind&&r.kind!==e.kind||r.uri!==e.uri)}function QE(r,e){let t=[];for(let s of r.rtcpFeedback??[]){let n=(e.rtcpFeedback??[]).find(i=>i.type===s.type&&(i.parameter===s.parameter||!i.parameter&&!s.parameter));n&&t.push(n)}return t}});var tC=se(x0=>{"use strict";Object.defineProperty(x0,"__esModule",{value:!0});x0.Logger=void 0;var Td=Af(),Ad="awaitqueue",Gx=class{_debug;_warn;_error;constructor(e){e?(this._debug=Td(`${Ad}:${e}`),this._warn=Td(`${Ad}:WARN:${e}`),this._error=Td(`${Ad}:ERROR:${e}`)):(this._debug=Td(Ad),this._warn=Td(`${Ad}:WARN`),this._error=Td(`${Ad}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};x0.Logger=Gx});var Jx=se(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.AwaitQueueRemovedTaskError=Id.AwaitQueueStoppedError=void 0;var Xx=class r extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueStoppedError=Xx;var Yx=class r extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueRemovedTaskError=Yx});var rC=se(b0=>{"use strict";Object.defineProperty(b0,"__esModule",{value:!0});b0.AwaitQueue=void 0;var BO=tC(),Qx=Jx(),bi=new BO.Logger("AwaitQueue"),Zx=class{pendingTasks=new Map;nextTaskId=0;constructor(){bi.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,s){if(t=t??e.name,bi.debug(`push() [name:${t}, options:%o]`,s),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((n,i)=>{if(t&&s?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new Qx.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),bi.debug(`resolving task [name:${o.name}]`),n(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),bi.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){bi.debug("stop()");for(let e of this.pendingTasks.values())bi.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Qx.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){bi.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){bi.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new Qx.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(s=>({idx:t++,task:s.task,name:s.name,enqueuedTime:s.executedAt?s.executedAt-s.enqueuedAt:e-s.enqueuedAt,executionTime:s.executedAt?e-s.executedAt:0}))}async execute(e){if(bi.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};b0.AwaitQueue=Zx});var nC=se(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.AwaitQueueRemovedTaskError=xo.AwaitQueueStoppedError=xo.AwaitQueue=void 0;var NO=rC();Object.defineProperty(xo,"AwaitQueue",{enumerable:!0,get:function(){return NO.AwaitQueue}});var sC=Jx();Object.defineProperty(xo,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return sC.AwaitQueueStoppedError}});Object.defineProperty(xo,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return sC.AwaitQueueRemovedTaskError}})});var oC=se(v0=>{"use strict";Object.defineProperty(v0,"__esModule",{value:!0});v0.Producer=void 0;var OO=Yr(),iC=as(),Rd=Ls(),Pn=new OO.Logger("Producer"),eb=class extends iC.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new iC.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:s,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),Pn.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=s,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=a?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=d??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Pn.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Pn.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Rd.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Pn.debug("pause()"),this._closed){Pn.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(Pn.debug("resume()"),this._closed){Pn.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(Pn.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new Rd.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new Rd.InvalidStateError("track ended");if(e===this._track){Pn.debug("replaceTrack() | same track, ignored");return}await new Promise((t,s)=>{this.safeEmit("@replacetrack",e,t,s)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new Rd.InvalidStateError("closed");if(this._kind!=="video")throw new Rd.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,s)=>{this.safeEmit("@setmaxspatiallayer",e,t,s)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Rd.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,s)=>{this.safeEmit("@setrtpencodingparameters",e,t,s)})}onTrackEnded(){Pn.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};v0.Producer=eb});var cC=se(w0=>{"use strict";Object.defineProperty(w0,"__esModule",{value:!0});w0.Consumer=void 0;var LO=Yr(),aC=as(),DO=Ls(),Bn=new LO.Logger("Consumer"),tb=class extends aC.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new aC.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:s,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),Bn.debug("constructor()"),this._id=e,this._localId=t,this._producerId=s,this._rtpReceiver=n,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Bn.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Bn.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new DO.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Bn.debug("pause()"),this._closed){Bn.error("pause() | Consumer closed");return}if(this._paused){Bn.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Bn.debug("resume()"),this._closed){Bn.error("resume() | Consumer closed");return}if(!this._paused){Bn.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Bn.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};w0.Consumer=tb});var uC=se(S0=>{"use strict";Object.defineProperty(S0,"__esModule",{value:!0});S0.DataProducer=void 0;var MO=Yr(),dC=as(),UO=Ls(),vi=new MO.Logger("DataProducer"),rb=class extends dC.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new dC.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:s,appData:n}){super(),vi.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=s,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(vi.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(vi.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(vi.debug("send()"),this._closed)throw new UO.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(vi.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?vi.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):vi.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(vi.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||vi.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};S0.DataProducer=rb});var lC=se(_0=>{"use strict";Object.defineProperty(_0,"__esModule",{value:!0});_0.DataConsumer=void 0;var jO=Yr(),fC=as(),Ba=new jO.Logger("DataConsumer"),sb=class extends fC.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new fC.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:s,sctpStreamParameters:n,appData:i}){super(),Ba.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=s,this._sctpStreamParameters=n,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ba.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ba.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Ba.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Ba.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Ba.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Ba.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};_0.DataConsumer=sb});var pC=se(E0=>{"use strict";Object.defineProperty(E0,"__esModule",{value:!0});E0.Transport=void 0;var HO=nC(),FO=Yr(),hC=as(),yr=Ls(),nb=ka(),Rf=kn(),qO=oC(),zO=cC(),$O=uC(),VO=lC(),dr=new FO.Logger("Transport"),ib=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,s)=>{this.resolve=t,this.reject=s})}},ob=class extends hC.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new HO.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new hC.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u,handlerFactory:f,getSendExtendedRtpCapabilities:h,recvRtpCapabilities:y,canProduceByKind:v}){super(),dr.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=h,this._recvRtpCapabilities=y,this._canProduceByKind=v,this._maxSctpMessageSize=o?.maxMessageSize;let S=nb.clone(d)??{};delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,this._handler=f.factory({direction:e,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:S,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=u??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){dr.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new yr.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(dr.debug("restartIce()"),this._closed)throw new yr.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(dr.debug("updateIceServers()"),this._closed)throw new yr.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:d=!1,onRtpSender:u,appData:f={}}={}){if(dr.debug("produce() [track:%o]",e),this._closed)throw new yr.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new yr.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new yr.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(f&&typeof f!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let h;if(s&&!Array.isArray(s))throw TypeError("encodings must be an array");s?.length===0?h=void 0:s&&(h=s.map(C=>{let O={active:!0};return C.active===!1&&(O.active=!1),typeof C.dtx=="boolean"&&(O.dtx=C.dtx),typeof C.scalabilityMode=="string"&&(O.scalabilityMode=C.scalabilityMode),typeof C.scaleResolutionDownBy=="number"&&(O.scaleResolutionDownBy=C.scaleResolutionDownBy),typeof C.maxBitrate=="number"&&(O.maxBitrate=C.maxBitrate),typeof C.maxFramerate=="number"&&(O.maxFramerate=C.maxFramerate),typeof C.adaptivePtime=="boolean"&&(O.adaptivePtime=C.adaptivePtime),typeof C.priority=="string"&&(O.priority=C.priority),typeof C.networkPriority=="string"&&(O.networkPriority=C.networkPriority),O}));let{localId:y,rtpParameters:v,rtpSender:S}=await this._handler.send({track:e,streamId:t,encodings:h,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:u});try{Rf.validateAndNormalizeRtpParameters(v);let{id:C}=await new Promise((K,z)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:v,appData:f},K,z)}),O=new qO.Producer({id:C,localId:y,rtpSender:S,track:e,rtpParameters:v,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:d,appData:f});return this._producers.set(O.id,O),this.handleProducer(O),this._observer.safeEmit("newproducer",O),O}catch(C){throw this._handler.stopSending(y).catch(()=>{}),C}},"transport.produce()").catch(h=>{if(a)try{e.stop()}catch{}throw h})}async consume({id:e,producerId:t,kind:s,rtpParameters:n,streamId:i,onRtpReceiver:o,appData:a={}}){if(dr.debug("consume()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="recv")throw new yr.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(s!=="audio"&&s!=="video")throw new TypeError(`invalid kind '${s}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=nb.clone(n);if(!Rf.canReceive(c,this._recvRtpCapabilities))throw new yr.UnsupportedError("cannot consume this Producer");let u=new ib({id:e,producerId:t,kind:s,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(u),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),u.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:s,label:n="",protocol:i="",appData:o={}}={}){if(dr.debug("produceData()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="send")throw new yr.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError("SCTP not enabled by remote Transport");return(t||s)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:s,label:n,protocol:i}});Rf.validateAndNormalizeSctpStreamParameters(c);let{id:d}=await new Promise((f,h)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:n,protocol:i,appData:o},f,h)}),u=new $O.DataProducer({id:d,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(u.id,u),this.handleDataProducer(u),this._observer.safeEmit("newdataproducer",u),u},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:s,label:n="",protocol:i="",appData:o={}}){if(dr.debug("consumeData()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="recv")throw new yr.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError("SCTP not enabled by remote Transport");let a=nb.clone(s);return Rf.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new VO.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(d.id,d),this.handleDataConsumer(d),this._observer.safeEmit("newdataconsumer",d),d},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){dr.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,s=[];for(let n of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d}=n.consumerOptions;s.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d})}try{let n=await this._handler.receive(s);for(let i=0;i<n.length;++i){let o=e[i],a=n[i],{id:c,producerId:d,kind:u,rtpParameters:f,appData:h}=o.consumerOptions,{localId:y,rtpReceiver:v,track:S}=a,C=new zO.Consumer({id:c,localId:y,producerId:d,rtpReceiver:v,track:S,rtpParameters:f,appData:h});this._consumers.set(C.id,C),this.handleConsumer(C),!this._probatorConsumerCreated&&!t&&u==="video"&&(t=C),this._observer.safeEmit("newconsumer",C),o.resolve(C)}}catch(n){for(let i of e)i.reject(n)}if(t)try{let n=Rf.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:n}]),dr.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(n){dr.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",n)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){dr.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(s=>s.localId);await this._handler.pauseReceiving(t)}catch(t){dr.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){dr.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(s=>s.localId);await this._handler.resumeReceiving(t)}catch(t){dr.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){dr.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){dr.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},s,n)=>{if(this._closed){n(new yr.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},s,n)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(dr.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{dr.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(dr.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>dr.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,s)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(s)}),e.on("@resume",(t,s)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(s)}),e.on("@replacetrack",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(s).catch(n)}),e.on("@setmaxspatiallayer",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(s).catch(n)}),e.on("@setrtpencodingparameters",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(s).catch(n)}),e.on("@getstats",(t,s)=>{if(this._closed)return s(new yr.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(s)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,s)=>{if(this._closed)return s(new yr.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(s)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};E0.Transport=ob});var C0=se((bK,gC)=>{"use strict";var mC=gC.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(mC).forEach(function(r){var e=mC[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var bC=se(wi=>{"use strict";var kd=function(r){return String(Number(r))===r?Number(r):r},KO=function(r,e,t,s){if(s&&!t)e[s]=kd(r[1]);else for(var n=0;n<t.length;n+=1)r[n+1]!=null&&(e[t[n]]=kd(r[n+1]))},WO=function(r,e,t){var s=r.name&&r.names;r.push&&!e[r.push]?e[r.push]=[]:s&&!e[r.name]&&(e[r.name]={});var n=r.push?{}:s?e[r.name]:e;KO(t.match(r.reg),n,r.names,r.name),r.push&&e[r.push].push(n)},yC=C0(),GO=RegExp.prototype.test.bind(/^([a-z])=(.*)/);wi.parse=function(r){var e={},t=[],s=e;return r.split(/(\r\n|\r|\n)/).filter(GO).forEach(function(n){var i=n[0],o=n.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),s=t[t.length-1]);for(var a=0;a<(yC[i]||[]).length;a+=1){var c=yC[i][a];if(c.reg.test(o))return WO(c,s,o)}}),e.media=t,e};var xC=function(r,e){var t=e.split(/=(.+)/,2);return t.length===2?r[t[0]]=kd(t[1]):t.length===1&&e.length>1&&(r[t[0]]=void 0),r};wi.parseParams=function(r){return r.split(/;\s?/).reduce(xC,{})};wi.parseFmtpConfig=wi.parseParams;wi.parsePayloads=function(r){return r.toString().split(" ").map(Number)};wi.parseRemoteCandidates=function(r){for(var e=[],t=r.split(" ").map(kd),s=0;s<t.length;s+=3)e.push({component:t[s],ip:t[s+1],port:t[s+2]});return e};wi.parseImageAttributes=function(r){return r.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(xC,{})})};wi.parseSimulcastStreamList=function(r){return r.split(";").map(function(e){return e.split(",").map(function(t){var s,n=!1;return t[0]!=="~"?s=kd(t):(s=kd(t.substring(1,t.length)),n=!0),{scid:s,paused:n}})})}});var wC=se((wK,vC)=>{"use strict";var ab=C0(),XO=/%[sdv%]/g,YO=function(r){var e=1,t=arguments,s=t.length;return r.replace(XO,function(n){if(e>=s)return n;var i=t[e];switch(e+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},kf=function(r,e,t){var s=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,n=[r+"="+s];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?n.push(t[e.name][o]):n.push(t[e.names[i]])}else n.push(t[e.name]);return YO.apply(null,n)},JO=["v","o","s","i","u","e","p","c","b","t","r","z","a"],QO=["i","c","b","a"];vC.exports=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||JO,s=e.innerOrder||QO,n=[];return t.forEach(function(i){ab[i].forEach(function(o){o.name in r&&r[o.name]!=null?n.push(kf(i,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){n.push(kf(i,o,a))})})}),r.media.forEach(function(i){n.push(kf("m",ab.m[0],i)),s.forEach(function(o){ab[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(kf(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(kf(o,a,c))})})})}),n.join(`\r
3
+ `+i),s.push(n+"m+"+$t.exports.humanize(this.diff)+"\x1B[0m")}else s[0]=Mo()+e+" "+s[0]}function Mo(){return F.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Oo(...s){return process.stderr.write(qt.formatWithOptions(F.inspectOpts,...s)+`
4
+ `)}function Ao(s){s?process.env.DEBUG=s:delete process.env.DEBUG}function No(){return process.env.DEBUG}function jo(s){s.inspectOpts={};let e=Object.keys(F.inspectOpts);for(let t=0;t<e.length;t++)s.inspectOpts[e[t]]=F.inspectOpts[e[t]]}$t.exports=xr()(F);var{formatters:Js}=$t.exports;Js.o=function(s){return this.inspectOpts.colors=this.useColors,qt.inspect(s,this.inspectOpts).split(`
5
+ `).map(e=>e.trim()).join(" ")};Js.O=function(s){return this.inspectOpts.colors=this.useColors,qt.inspect(s,this.inspectOpts)}});var gt=C((yp,Ir)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ir.exports=Gs():Ir.exports=Xs()});var en=C(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0})});var z=C(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Logger=void 0;var Be=gt(),Ve="media-client",Lr=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Be.default)(`${Ve}:${e}`),this._warn=(0,Be.default)(`${Ve}:WARN:${e}`),this._error=(0,Be.default)(`${Ve}:ERROR:${e}`)):(this._debug=(0,Be.default)(Ve),this._warn=(0,Be.default)(`${Ve}:WARN`),this._error=(0,Be.default)(`${Ve}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Ut.Logger=Lr});var un=C((Rp,Mr)=>{"use strict";var We=typeof Reflect=="object"?Reflect:null,tn=We&&typeof We.apply=="function"?We.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},zt;We&&typeof We.ownKeys=="function"?zt=We.ownKeys:Object.getOwnPropertySymbols?zt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zt=function(e){return Object.getOwnPropertyNames(e)};function Fo(s){console&&console.warn&&console.warn(s)}var sn=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}Mr.exports=L;Mr.exports.once=zo;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var rn=10;function Bt(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return rn},set:function(s){if(typeof s!="number"||s<0||sn(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");rn=s}});L.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};L.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||sn(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function nn(s){return s._maxListeners===void 0?L.defaultMaxListeners:s._maxListeners}L.prototype.getMaxListeners=function(){return nn(this)};L.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")tn(c,this,t);else for(var d=c.length,p=pn(c,d),r=0;r<d;++r)tn(p[r],this,t);return!0};function on(s,e,t,r){var n,i,o;if(Bt(t),i=s._events,i===void 0?(i=s._events=Object.create(null),s._eventsCount=0):(i.newListener!==void 0&&(s.emit("newListener",e,t.listener?t.listener:t),i=s._events),o=i[e]),o===void 0)o=i[e]=t,++s._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),n=nn(s),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=s,a.type=e,a.count=o.length,Fo(a)}return s}L.prototype.addListener=function(e,t){return on(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return on(this,e,t,!0)};function qo(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function an(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=qo.bind(r);return n.listener=t,r.wrapFn=n,n}L.prototype.once=function(e,t){return Bt(t),this.on(e,an(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Bt(t),this.prependListener(e,an(this,e,t)),this};L.prototype.removeListener=function(e,t){var r,n,i,o,a;if(Bt(t),n=this._events,n===void 0)return this;if(r=n[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():$o(r,i),r.length===1&&(n[e]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};L.prototype.off=L.prototype.removeListener;L.prototype.removeAllListeners=function(e){var t,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function cn(s,e,t){var r=s._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?Uo(n):pn(n,n.length)}L.prototype.listeners=function(e){return cn(this,e,!0)};L.prototype.rawListeners=function(e){return cn(this,e,!1)};L.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):dn.call(s,e)};L.prototype.listenerCount=dn;function dn(s){var e=this._events;if(e!==void 0){var t=e[s];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?zt(this._events):[]};function pn(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function $o(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function Uo(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function zo(s,e){return new Promise(function(t,r){function n(o){s.removeListener(e,i),r(o)}function i(){typeof s.removeListener=="function"&&s.removeListener("error",n),t([].slice.call(arguments))}ln(s,e,i,{once:!0}),e!=="error"&&Bo(s,n,{once:!0})})}function Bo(s,e,t){typeof s.on=="function"&&ln(s,"error",e,t)}function ln(s,e,t,r){if(typeof s.on=="function")r.once?s.once(e,t):s.on(e,t);else if(typeof s.addEventListener=="function")s.addEventListener(e,function n(i){r.once&&s.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}});var G=C(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.EnhancedEventEmitter=void 0;var Vo=un(),Wo=z(),Ho=new Wo.Logger("EnhancedEventEmitter"),Or=class extends Vo.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(r){Ho.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,r);try{super.emit("listenererror",e,r)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};Vt.EnhancedEventEmitter=Or});var X=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.InvalidStateError=He.UnsupportedError=void 0;var Ar=class s extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,s):this.stack=new Error(e).stack}};He.UnsupportedError=Ar;var Nr=class s extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,s):this.stack=new Error(e).stack}};He.InvalidStateError=Nr});var ke=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.clone=Go;_t.generateRandomNumber=Ko;_t.deepFreeze=hn;function Go(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function Ko(){return Math.round(Math.random()*1e7)}function hn(s){let e=Reflect.ownKeys(s);for(let t of e){let r=s[t];(r&&typeof r=="object"||typeof r=="function")&&hn(r)}return Object.freeze(s)}});var fn=C(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.Logger=void 0;var Ge=gt(),Ke="h264-profile-level-id",jr=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ge.default)(`${Ke}:${e}`),this._warn=(0,Ge.default)(`${Ke}:WARN:${e}`),this._error=(0,Ge.default)(`${Ke}:ERROR:${e}`)):(this._debug=(0,Ge.default)(Ke),this._warn=(0,Ge.default)(`${Ke}:WARN`),this._error=(0,Ge.default)(`${Ke}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Wt.Logger=jr});var yn=C(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.ProfileLevelId=q.Level=q.Profile=void 0;q.parseProfileLevelId=vn;q.profileLevelIdToString=wn;q.profileToString=Xo;q.levelToString=Zo;q.parseSdpProfileLevelId=xe;q.isSameProfile=ea;q.isSameProfileAndLevel=ta;q.generateProfileLevelIdStringForAnswer=ra;q.supportedLevel=sa;var Qo=fn(),ne=new Qo.Logger,M;(function(s){s[s.ConstrainedBaseline=1]="ConstrainedBaseline",s[s.Baseline=2]="Baseline",s[s.Main=3]="Main",s[s.ConstrainedHigh=4]="ConstrainedHigh",s[s.High=5]="High",s[s.PredictiveHigh444=6]="PredictiveHigh444"})(M||(q.Profile=M={}));var v;(function(s){s[s.L1_b=0]="L1_b",s[s.L1=10]="L1",s[s.L1_1=11]="L1_1",s[s.L1_2=12]="L1_2",s[s.L1_3=13]="L1_3",s[s.L2=20]="L2",s[s.L2_1=21]="L2_1",s[s.L2_2=22]="L2_2",s[s.L3=30]="L3",s[s.L3_1=31]="L3_1",s[s.L3_2=32]="L3_2",s[s.L4=40]="L4",s[s.L4_1=41]="L4_1",s[s.L4_2=42]="L4_2",s[s.L5=50]="L5",s[s.L5_1=51]="L5_1",s[s.L5_2=52]="L5_2"})(v||(q.Level=v={}));var Qe=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};q.ProfileLevelId=Qe;var Yo=new Qe(M.ConstrainedBaseline,v.L3_1),re=class{mask;masked_value;constructor(e){this.mask=~gn("x",e),this.masked_value=gn("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},se=class{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}},Jo=[new se(66,new re("x1xx0000"),M.ConstrainedBaseline),new se(77,new re("1xxx0000"),M.ConstrainedBaseline),new se(88,new re("11xx0000"),M.ConstrainedBaseline),new se(66,new re("x0xx0000"),M.Baseline),new se(88,new re("10xx0000"),M.Baseline),new se(77,new re("0x0x0000"),M.Main),new se(100,new re("00000000"),M.High),new se(100,new re("00001100"),M.ConstrainedHigh),new se(244,new re("00000000"),M.PredictiveHigh444)],mn=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:v.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:v.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:v.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:v.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:v.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:v.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:v.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:v.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:v.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:v.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:v.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:v.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:v.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:v.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:v.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:v.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:v.L5_2}];function vn(s){if(typeof s!="string"||s.length!==6)return;let t=parseInt(s,16);if(t===0)return;let r=t&255,n=t>>8&255,i=t>>16&255,o;switch(r){case v.L1_1:{o=(n&16)!==0?v.L1_b:v.L1_1;break}case v.L1:case v.L1_2:case v.L1_3:case v.L2:case v.L2_1:case v.L2_2:case v.L3:case v.L3_1:case v.L3_2:case v.L4:case v.L4_1:case v.L4_2:case v.L5:case v.L5_1:case v.L5_2:{o=r;break}default:{ne.warn(`parseProfileLevelId() | unrecognized level_idc [str:${s}, level_idc:${r}]`);return}}for(let a of Jo)if(i===a.profile_idc&&a.profile_iop.isMatch(n))return ne.debug(`parseProfileLevelId() | result [str:${s}, profile:${a.profile}, level:${o}]`),new Qe(a.profile,o);ne.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${s}, profile_idc:${i}, profile_iop:${n}]`)}function wn(s){if(s.level==v.L1_b)switch(s.profile){case M.ConstrainedBaseline:return"42f00b";case M.Baseline:return"42100b";case M.Main:return"4d100b";default:{ne.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${s.profile}`);return}}let e;switch(s.profile){case M.ConstrainedBaseline:{e="42e0";break}case M.Baseline:{e="4200";break}case M.Main:{e="4d00";break}case M.ConstrainedHigh:{e="640c";break}case M.High:{e="6400";break}case M.PredictiveHigh444:{e="f400";break}default:{ne.warn(`profileLevelIdToString() | unrecognized profile ${s.profile}`);return}}let t=s.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Xo(s){switch(s){case M.ConstrainedBaseline:return"ConstrainedBaseline";case M.Baseline:return"Baseline";case M.Main:return"Main";case M.ConstrainedHigh:return"ConstrainedHigh";case M.High:return"High";case M.PredictiveHigh444:return"PredictiveHigh444";default:{ne.warn(`profileToString() | unrecognized profile ${s}`);return}}}function Zo(s){switch(s){case v.L1_b:return"1b";case v.L1:return"1";case v.L1_1:return"1.1";case v.L1_2:return"1.2";case v.L1_3:return"1.3";case v.L2:return"2";case v.L2_1:return"2.1";case v.L2_2:return"2.2";case v.L3:return"3";case v.L3_1:return"3.1";case v.L3_2:return"3.2";case v.L4:return"4";case v.L4_1:return"4.1";case v.L4_2:return"4.2";case v.L5:return"5";case v.L5_1:return"5.1";case v.L5_2:return"5.2";default:{ne.warn(`levelToString() | unrecognized level ${s}`);return}}}function xe(s={}){let e=s["profile-level-id"];return e?vn(e):Yo}function ea(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile)}function ta(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile&&t.level==r.level)}function ra(s={},e={}){if(!s["profile-level-id"]&&!e["profile-level-id"]){ne.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=xe(s),r=xe(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!r)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==r.profile)throw new TypeError("H264 Profile mismatch");let n=_n(s)&&_n(e),i=t.level,o=r.level,a=ia(i,o),c=n?i:a;return ne.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),wn(new Qe(t.profile,c))}function sa(s,e){for(let r=mn.length-1;r>=0;--r){let n=mn[r];if(n.max_macroblock_frame_size*256<=s&&n.max_macroblocks_per_second<=e*n.max_macroblock_frame_size)return ne.debug(`supportedLevel() | result [max_frame_pixel_count:${s}, max_fps:${e}, level:${n.level}]`),n.level}ne.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${s}, max_fps:${e}]`)}function gn(s,e){return+(e[0]===s)<<7|+(e[1]===s)<<6|+(e[2]===s)<<5|+(e[3]===s)<<4|+(e[4]===s)<<3|+(e[5]===s)<<2|+(e[6]===s)<<1|+(e[7]===s)<<0}function na(s,e){return s===v.L1_b?e!==v.L1&&e!==v.L1_b:e===v.L1_b?s!==v.L1:s<e}function ia(s,e){return na(s,e)?s:e}function _n(s={}){let e=s["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var ce=C(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.validateAndNormalizeRtpCapabilities=pa;B.validateAndNormalizeRtpParameters=qr;B.validateAndNormalizeSctpStreamParameters=la;B.validateSctpCapabilities=ua;B.getExtendedRtpCapabilities=ha;B.getRecvRtpCapabilities=fa;B.getSendRtpCapabilities=ma;B.getSendingRtpParameters=ga;B.getSendingRemoteRtpParameters=_a;B.reduceCodecs=va;B.generateProbatorRtpParameters=wa;B.canSend=ya;B.canReceive=ba;var bn=yn(),oa=ke(),aa="probator",ca=1234,da=127;function pa(s){if(typeof s!="object")throw new TypeError("caps is not an object");if(s.codecs&&!Array.isArray(s.codecs))throw new TypeError("caps.codecs is not an array");s.codecs||(s.codecs=[]);for(let e of s.codecs)Sa(e);if(s.headerExtensions&&!Array.isArray(s.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");s.headerExtensions||(s.headerExtensions=[]);for(let e of s.headerExtensions)Ra(e)}function qr(s){if(typeof s!="object")throw new TypeError("params is not an object");if(s.mid&&typeof s.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(s.codecs))throw new TypeError("missing params.codecs");for(let e of s.codecs)Ca(e);if(s.headerExtensions&&!Array.isArray(s.headerExtensions))throw new TypeError("params.headerExtensions is not an array");s.headerExtensions||(s.headerExtensions=[]);for(let e of s.headerExtensions)Ta(e);if(s.encodings&&!Array.isArray(s.encodings))throw new TypeError("params.encodings is not an array");s.encodings||(s.encodings=[]);for(let e of s.encodings)Ea(e);if(s.rtcp&&typeof s.rtcp!="object")throw new TypeError("params.rtcp is not an object");s.rtcp||(s.rtcp={}),ka(s.rtcp)}function la(s){if(typeof s!="object")throw new TypeError("params is not an object");if(typeof s.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof s.ordered=="boolean"?e=!0:s.ordered=!0,s.maxPacketLifeTime&&typeof s.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(s.maxRetransmits&&typeof s.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(s.maxPacketLifeTime&&s.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&s.ordered&&(s.maxPacketLifeTime||s.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(s.maxPacketLifeTime||s.maxRetransmits)&&(s.ordered=!1),s.label&&typeof s.label!="string")throw new TypeError("invalid params.label");if(s.protocol&&typeof s.protocol!="string")throw new TypeError("invalid params.protocol")}function ua(s){if(typeof s!="object")throw new TypeError("caps is not an object");if(!s.numStreams||typeof s.numStreams!="object")throw new TypeError("missing caps.numStreams");xa(s.numStreams)}function ha(s,e,t){let r={codecs:[],headerExtensions:[]};if(t)for(let n of s.codecs??[]){if(Ye(n))continue;let i=(e.codecs??[]).find(a=>Fr(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:n.kind,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,localPayloadType:n.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:n.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:Sn(n,i)};r.codecs.push(o)}else for(let n of e.codecs??[]){if(Ye(n))continue;let i=(s.codecs??[]).find(a=>Fr(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:n.parameters??{},rtcpFeedback:Sn(i,n)};r.codecs.push(o)}for(let n of r.codecs){let i=s.codecs.find(a=>Ye(a)&&a.parameters?.apt===n.localPayloadType),o=e.codecs.find(a=>Ye(a)&&a.parameters?.apt===n.remotePayloadType);i&&o&&(n.localRtxPayloadType=i.preferredPayloadType,n.remoteRtxPayloadType=o.preferredPayloadType)}for(let n of e.headerExtensions){let i=s.headerExtensions.find(a=>Pa(a,n));if(!i)continue;let o={kind:n.kind,uri:n.uri,sendId:i.preferredId,recvId:n.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(n.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}r.headerExtensions.push(o)}return r}function fa(s){return Cn({direction:"recvonly",extendedRtpCapabilities:s})}function ma(s){return Cn({direction:"sendonly",extendedRtpCapabilities:s})}function ga(s,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==s)continue;let n={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==s||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let n={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(n)}return t}function _a(s,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==s)continue;let n={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.remoteParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==s||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let n={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(n)}if(t.headerExtensions.some(r=>r.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="goog-remb");else if(t.headerExtensions.some(r=>r.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc");else for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc"&&n.type!=="goog-remb");return t}function va(s,e){let t=[];if(!e)t.push(s[0]),Ye(s[1])&&t.push(s[1]);else{for(let r=0;r<s.length;++r)if(Fr(s[r],e,{strict:!0})){t.push(s[r]),Ye(s[r+1])&&t.push(s[r+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function wa(s){s=oa.clone(s),qr(s);let e={mid:aa,codecs:[],headerExtensions:[],encodings:[{ssrc:ca}],rtcp:{cname:"probator"}};return e.codecs.push(s.codecs[0]),e.codecs[0].payloadType=da,e.headerExtensions=s.headerExtensions,e}function ya(s,e){return(e.codecs??[]).some(t=>t.kind===s)}function ba(s,e){if(qr(s),s.codecs.length===0)return!1;let t=s.codecs[0];return(e.codecs??[]).some(r=>r.preferredPayloadType===t.payloadType)}function Sa(s){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof s!="object")throw new TypeError("codec is not an object");if(!s.mimeType||typeof s.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(s.kind=t[1].toLowerCase(),typeof s.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof s.clockRate!="number")throw new TypeError("missing codec.clockRate");s.kind==="audio"?typeof s.channels!="number"&&(s.channels=1):delete s.channels,(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let r of Object.keys(s.parameters)){let n=s.parameters[r];if(n===void 0&&(s.parameters[r]="",n=""),typeof n!="string"&&typeof n!="number")throw new TypeError(`invalid codec parameter [key:${r}s, value:${n}]`);if(r==="apt"&&typeof n!="number")throw new TypeError("invalid codec apt parameter")}(!s.rtcpFeedback||!Array.isArray(s.rtcpFeedback))&&(s.rtcpFeedback=[]);for(let r of s.rtcpFeedback)Rn(r)}function Rn(s){if(typeof s!="object")throw new TypeError("fb is not an object");if(!s.type||typeof s.type!="string")throw new TypeError("missing fb.type");(!s.parameter||typeof s.parameter!="string")&&(s.parameter="")}function Ra(s){if(typeof s!="object")throw new TypeError("ext is not an object");if(s.kind!=="audio"&&s.kind!=="video")throw new TypeError("invalid ext.kind");if(!s.uri||typeof s.uri!="string")throw new TypeError("missing ext.uri");if(typeof s.preferredId!="number")throw new TypeError("missing ext.preferredId");if(s.preferredEncrypt&&typeof s.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(s.preferredEncrypt||(s.preferredEncrypt=!1),s.direction&&typeof s.direction!="string")throw new TypeError("invalid ext.direction");s.direction||(s.direction="sendrecv")}function Ca(s){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof s!="object")throw new TypeError("codec is not an object");if(!s.mimeType||typeof s.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof s.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof s.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof s.channels!="number"&&(s.channels=1):delete s.channels,(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let n of Object.keys(s.parameters)){let i=s.parameters[n];if(i===void 0&&(s.parameters[n]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${i}]`);if(n==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!s.rtcpFeedback||!Array.isArray(s.rtcpFeedback))&&(s.rtcpFeedback=[]);for(let n of s.rtcpFeedback)Rn(n)}function Ta(s){if(typeof s!="object")throw new TypeError("ext is not an object");if(!s.uri||typeof s.uri!="string")throw new TypeError("missing ext.uri");if(typeof s.id!="number")throw new TypeError("missing ext.id");if(s.encrypt&&typeof s.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");s.encrypt||(s.encrypt=!1),(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let e of Object.keys(s.parameters)){let t=s.parameters[e];if(t===void 0&&(s.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function Ea(s){if(typeof s!="object")throw new TypeError("encoding is not an object");if(s.ssrc&&typeof s.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(s.rid&&typeof s.rid!="string")throw new TypeError("invalid encoding.rid");if(s.rtx&&typeof s.rtx!="object")throw new TypeError("invalid encoding.rtx");if(s.rtx&&typeof s.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!s.dtx||typeof s.dtx!="boolean")&&(s.dtx=!1),s.scalabilityMode&&typeof s.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function ka(s){if(typeof s!="object")throw new TypeError("rtcp is not an object");if(s.cname&&typeof s.cname!="string")throw new TypeError("invalid rtcp.cname");(!s.reducedSize||typeof s.reducedSize!="boolean")&&(s.reducedSize=!0)}function xa(s){if(typeof s!="object")throw new TypeError("numStreams is not an object");if(typeof s.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof s.MIS!="number")throw new TypeError("missing numStreams.MIS")}function Cn({direction:s,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let r of e.codecs){let n={kind:r.kind,mimeType:r.mimeType,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),!r.remoteRtxPayloadType)continue;let i={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let r of e.headerExtensions){if(r.direction!=="sendrecv"&&r.direction!==s)continue;let n={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(n)}return t}function Ye(s){return s?/.+\/rtx$/i.test(s.mimeType):!1}function Fr(s,e,{strict:t=!1,modify:r=!1}={}){let n=s.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(n!==i||s.clockRate!==e.clockRate||s.channels!==e.channels)return!1;switch(n){case"video/h264":{if(t){let o=s.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!bn.isSameProfile(s.parameters,e.parameters))return!1;let c;try{c=bn.generateProfileLevelIdStringForAnswer(s.parameters,e.parameters)}catch{return!1}r&&(c?(s.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete s.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=s.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function Pa(s,e){return!(s.kind&&e.kind&&s.kind!==e.kind||s.uri!==e.uri)}function Sn(s,e){let t=[];for(let r of s.rtcpFeedback??[]){let n=(e.rtcpFeedback??[]).find(i=>i.type===r.type&&(i.parameter===r.parameter||!i.parameter&&!r.parameter));n&&t.push(n)}return t}});var Tn=C(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.Logger=void 0;var Je=gt(),Xe="awaitqueue",$r=class{_debug;_warn;_error;constructor(e){e?(this._debug=Je(`${Xe}:${e}`),this._warn=Je(`${Xe}:WARN:${e}`),this._error=Je(`${Xe}:ERROR:${e}`)):(this._debug=Je(Xe),this._warn=Je(`${Xe}:WARN`),this._error=Je(`${Xe}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Ht.Logger=$r});var Br=C(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.AwaitQueueRemovedTaskError=Ze.AwaitQueueStoppedError=void 0;var Ur=class s extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Ze.AwaitQueueStoppedError=Ur;var zr=class s extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Ze.AwaitQueueRemovedTaskError=zr});var En=C(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AwaitQueue=void 0;var Da=Tn(),Vr=Br(),me=new Da.Logger("AwaitQueue"),Wr=class{pendingTasks=new Map;nextTaskId=0;constructor(){me.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,me.debug(`push() [name:${t}, options:%o]`,r),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new Vr.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),me.debug(`resolving task [name:${o.name}]`),n(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),me.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){me.debug("stop()");for(let e of this.pendingTasks.values())me.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Vr.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){me.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){me.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new Vr.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}async execute(e){if(me.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};Gt.AwaitQueue=Wr});var xn=C(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.AwaitQueueRemovedTaskError=Re.AwaitQueueStoppedError=Re.AwaitQueue=void 0;var Ia=En();Object.defineProperty(Re,"AwaitQueue",{enumerable:!0,get:function(){return Ia.AwaitQueue}});var kn=Br();Object.defineProperty(Re,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return kn.AwaitQueueStoppedError}});Object.defineProperty(Re,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return kn.AwaitQueueRemovedTaskError}})});var Dn=C(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.Producer=void 0;var La=z(),Pn=G(),et=X(),de=new La.Logger("Producer"),Hr=class extends Pn.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Pn.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),de.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=a?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=d??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(de.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(de.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new et.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(de.debug("pause()"),this._closed){de.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(de.debug("resume()"),this._closed){de.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(de.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new et.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new et.InvalidStateError("track ended");if(e===this._track){de.debug("replaceTrack() | same track, ignored");return}await new Promise((t,r)=>{this.safeEmit("@replacetrack",e,t,r)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new et.InvalidStateError("closed");if(this._kind!=="video")throw new et.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new et.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){de.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};Kt.Producer=Hr});var Ln=C(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.Consumer=void 0;var Ma=z(),In=G(),Oa=X(),pe=new Ma.Logger("Consumer"),Gr=class extends In.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new In.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),pe.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(pe.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(pe.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Oa.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(pe.debug("pause()"),this._closed){pe.error("pause() | Consumer closed");return}if(this._paused){pe.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(pe.debug("resume()"),this._closed){pe.error("resume() | Consumer closed");return}if(!this._paused){pe.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){pe.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};Qt.Consumer=Gr});var On=C(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DataProducer=void 0;var Aa=z(),Mn=G(),Na=X(),ge=new Aa.Logger("DataProducer"),Kr=class extends Mn.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Mn.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),ge.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ge.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ge.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(ge.debug("send()"),this._closed)throw new Na.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ge.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?ge.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):ge.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(ge.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||ge.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};Yt.DataProducer=Kr});var Nn=C(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.DataConsumer=void 0;var ja=z(),An=G(),Pe=new ja.Logger("DataConsumer"),Qr=class extends An.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new An.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),Pe.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Pe.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Pe.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Pe.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Pe.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Pe.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Pe.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};Jt.DataConsumer=Qr});var Fn=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.Transport=void 0;var Fa=xn(),qa=z(),jn=G(),j=X(),Yr=ke(),vt=ce(),$a=Dn(),Ua=Ln(),za=On(),Ba=Nn(),N=new qa.Logger("Transport"),Jr=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,r)=>{this.resolve=t,this.reject=r})}},Xr=class extends jn.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new Fa.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new jn.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p,handlerFactory:l,getSendExtendedRtpCapabilities:u,recvRtpCapabilities:m,canProduceByKind:f}){super(),N.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=u,this._recvRtpCapabilities=m,this._canProduceByKind=f,this._maxSctpMessageSize=o?.maxMessageSize;let h=Yr.clone(d)??{};delete h.iceServers,delete h.iceTransportPolicy,delete h.bundlePolicy,delete h.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:h,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=p??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){N.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new j.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(N.debug("restartIce()"),this._closed)throw new j.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(N.debug("updateIceServers()"),this._closed)throw new j.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:d=!1,onRtpSender:p,appData:l={}}={}){if(N.debug("produce() [track:%o]",e),this._closed)throw new j.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new j.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new j.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(l&&typeof l!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let u;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");r?.length===0?u=void 0:r&&(u=r.map(g=>{let _={active:!0};return g.active===!1&&(_.active=!1),typeof g.dtx=="boolean"&&(_.dtx=g.dtx),typeof g.scalabilityMode=="string"&&(_.scalabilityMode=g.scalabilityMode),typeof g.scaleResolutionDownBy=="number"&&(_.scaleResolutionDownBy=g.scaleResolutionDownBy),typeof g.maxBitrate=="number"&&(_.maxBitrate=g.maxBitrate),typeof g.maxFramerate=="number"&&(_.maxFramerate=g.maxFramerate),typeof g.adaptivePtime=="boolean"&&(_.adaptivePtime=g.adaptivePtime),typeof g.priority=="string"&&(_.priority=g.priority),typeof g.networkPriority=="string"&&(_.networkPriority=g.networkPriority),_}));let{localId:m,rtpParameters:f,rtpSender:h}=await this._handler.send({track:e,streamId:t,encodings:u,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:p});try{vt.validateAndNormalizeRtpParameters(f);let{id:g}=await new Promise((y,x)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:f,appData:l},y,x)}),_=new $a.Producer({id:g,localId:m,rtpSender:h,track:e,rtpParameters:f,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:d,appData:l});return this._producers.set(_.id,_),this.handleProducer(_),this._observer.safeEmit("newproducer",_),_}catch(g){throw this._handler.stopSending(m).catch(()=>{}),g}},"transport.produce()").catch(u=>{if(a)try{e.stop()}catch{}throw u})}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:o,appData:a={}}){if(N.debug("consume()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="recv")throw new j.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(r!=="audio"&&r!=="video")throw new TypeError(`invalid kind '${r}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=Yr.clone(n);if(!vt.canReceive(c,this._recvRtpCapabilities))throw new j.UnsupportedError("cannot consume this Producer");let p=new Jr({id:e,producerId:t,kind:r,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(p),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),p.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:o={}}={}){if(N.debug("produceData()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="send")throw new j.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError("SCTP not enabled by remote Transport");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}});vt.validateAndNormalizeSctpStreamParameters(c);let{id:d}=await new Promise((l,u)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:n,protocol:i,appData:o},l,u)}),p=new za.DataProducer({id:d,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(p.id,p),this.handleDataProducer(p),this._observer.safeEmit("newdataproducer",p),p},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:n="",protocol:i="",appData:o={}}){if(N.debug("consumeData()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="recv")throw new j.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError("SCTP not enabled by remote Transport");let a=Yr.clone(r);return vt.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new Ba.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(d.id,d),this.handleDataConsumer(d),this._observer.safeEmit("newdataconsumer",d),d},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){N.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,r=[];for(let n of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d}=n.consumerOptions;r.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d})}try{let n=await this._handler.receive(r);for(let i=0;i<n.length;++i){let o=e[i],a=n[i],{id:c,producerId:d,kind:p,rtpParameters:l,appData:u}=o.consumerOptions,{localId:m,rtpReceiver:f,track:h}=a,g=new Ua.Consumer({id:c,localId:m,producerId:d,rtpReceiver:f,track:h,rtpParameters:l,appData:u});this._consumers.set(g.id,g),this.handleConsumer(g),!this._probatorConsumerCreated&&!t&&p==="video"&&(t=g),this._observer.safeEmit("newconsumer",g),o.resolve(g)}}catch(n){for(let i of e)i.reject(n)}if(t)try{let n=vt.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:n}]),N.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(n){N.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",n)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){N.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.pauseReceiving(t)}catch(t){N.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){N.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.resumeReceiving(t)}catch(t){N.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){N.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){N.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},r,n)=>{if(this._closed){n(new j.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},r,n)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(N.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{N.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(N.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>N.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(r)}),e.on("@resume",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(r)}),e.on("@replacetrack",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(n)}),e.on("@setmaxspatiallayer",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(n)}),e.on("@setrtpencodingparameters",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(n)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new j.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new j.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};Xt.Transport=Xr});var Zt=C((qp,$n)=>{"use strict";var qn=$n.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var e="candidate:%s %d %s %d %s %d typ %s";return e+=s.raddr!=null?" raddr %s rport %d":"%v%v",e+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(e+=" generation %d"),e+=s["network-id"]!=null?" network-id %d":"%v",e+=s["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var e="ssrc:%d";return s.attribute!=null&&(e+=" %s",s.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var e="mediaclk:";return e+=s.id!=null?"id=%s %s":"%v%s",e+=s.mediaClockValue!=null?"=%s":"",e+=s.rateNumerator!=null?" rate=%s":"",e+=s.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(qn).forEach(function(s){var e=qn[s];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var Bn=C(_e=>{"use strict";var tt=function(s){return String(Number(s))===s?Number(s):s},Va=function(s,e,t,r){if(r&&!t)e[r]=tt(s[1]);else for(var n=0;n<t.length;n+=1)s[n+1]!=null&&(e[t[n]]=tt(s[n+1]))},Wa=function(s,e,t){var r=s.name&&s.names;s.push&&!e[s.push]?e[s.push]=[]:r&&!e[s.name]&&(e[s.name]={});var n=s.push?{}:r?e[s.name]:e;Va(t.match(s.reg),n,s.names,s.name),s.push&&e[s.push].push(n)},Un=Zt(),Ha=RegExp.prototype.test.bind(/^([a-z])=(.*)/);_e.parse=function(s){var e={},t=[],r=e;return s.split(/(\r\n|\r|\n)/).filter(Ha).forEach(function(n){var i=n[0],o=n.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),r=t[t.length-1]);for(var a=0;a<(Un[i]||[]).length;a+=1){var c=Un[i][a];if(c.reg.test(o))return Wa(c,r,o)}}),e.media=t,e};var zn=function(s,e){var t=e.split(/=(.+)/,2);return t.length===2?s[t[0]]=tt(t[1]):t.length===1&&e.length>1&&(s[t[0]]=void 0),s};_e.parseParams=function(s){return s.split(/;\s?/).reduce(zn,{})};_e.parseFmtpConfig=_e.parseParams;_e.parsePayloads=function(s){return s.toString().split(" ").map(Number)};_e.parseRemoteCandidates=function(s){for(var e=[],t=s.split(" ").map(tt),r=0;r<t.length;r+=3)e.push({component:t[r],ip:t[r+1],port:t[r+2]});return e};_e.parseImageAttributes=function(s){return s.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(zn,{})})};_e.parseSimulcastStreamList=function(s){return s.split(";").map(function(e){return e.split(",").map(function(t){var r,n=!1;return t[0]!=="~"?r=tt(t):(r=tt(t.substring(1,t.length)),n=!0),{scid:r,paused:n}})})}});var Wn=C((Up,Vn)=>{"use strict";var Zr=Zt(),Ga=/%[sdv%]/g,Ka=function(s){var e=1,t=arguments,r=t.length;return s.replace(Ga,function(n){if(e>=r)return n;var i=t[e];switch(e+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},wt=function(s,e,t){var r=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,n=[s+"="+r];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?n.push(t[e.name][o]):n.push(t[e.names[i]])}else n.push(t[e.name]);return Ka.apply(null,n)},Qa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ya=["i","c","b","a"];Vn.exports=function(s,e){e=e||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||Qa,r=e.innerOrder||Ya,n=[];return t.forEach(function(i){Zr[i].forEach(function(o){o.name in s&&s[o.name]!=null?n.push(wt(i,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(a){n.push(wt(i,o,a))})})}),s.media.forEach(function(i){n.push(wt("m",Zr.m[0],i)),r.forEach(function(o){Zr[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(wt(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(wt(o,a,c))})})})}),n.join(`\r
6
6
  `)+`\r
7
- `}});var Si=se(Nn=>{"use strict";var Na=bC(),ZO=wC(),eL=C0();Nn.grammar=eL;Nn.write=ZO;Nn.parse=Na.parse;Nn.parseParams=Na.parseParams;Nn.parseFmtpConfig=Na.parseFmtpConfig;Nn.parsePayloads=Na.parsePayloads;Nn.parseRemoteCandidates=Na.parseRemoteCandidates;Nn.parseImageAttributes=Na.parseImageAttributes;Nn.parseSimulcastStreamList=Na.parseSimulcastStreamList});var Oa=se(cb=>{"use strict";Object.defineProperty(cb,"__esModule",{value:!0});cb.parse=rL;var tL=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function rL(r){let e=tL.exec(r??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var EC=se(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.OfferMediaSection=bo.AnswerMediaSection=bo.MediaSection=void 0;var sL=Si(),SC=ka(),Pf=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let n of t){let i={foundation:n.foundation,component:1,ip:n.address??n.ip,port:n.port,priority:n.priority,transport:n.protocol,type:n.type};n.tcpType&&(i.tcptype=n.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}s&&this.setDtlsRole(s.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};bo.MediaSection=Pf;var db=class extends Pf{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let u of c.codecs){let f={payload:u.payloadType,codec:_C(u),rate:u.clockRate};u.channels>1&&(f.encoding=u.channels),this._mediaObject.rtp.push(f);let h=SC.clone(u.parameters)??{},y=SC.clone(u.rtcpFeedback)??[];if(d){let{opusStereo:S,opusFec:C,opusDtx:O,opusMaxPlaybackRate:K,opusMaxAverageBitrate:z,opusPtime:Q,opusNack:oe,videoGoogleStartBitrate:te,videoGoogleMaxBitrate:Ee,videoGoogleMinBitrate:ge}=d,Y=a.codecs.find(Ze=>Ze.payloadType===u.payloadType);switch(u.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{S!==void 0&&(Y.parameters["sprop-stereo"]=S?1:0,h.stereo=S?1:0),C!==void 0&&(Y.parameters.useinbandfec=C?1:0,h.useinbandfec=C?1:0),O!==void 0&&(Y.parameters.usedtx=O?1:0,h.usedtx=O?1:0),K!==void 0&&(h.maxplaybackrate=K),z!==void 0&&(h.maxaveragebitrate=z),Q!==void 0&&(Y.parameters.ptime=Q,h.ptime=Q),oe||(Y.rtcpFeedback=Y.rtcpFeedback.filter(Ze=>Ze.type!=="nack"||Ze.parameter),y=y.filter(Ze=>Ze.type!=="nack"||Ze.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{te!==void 0&&(h["x-google-start-bitrate"]=te),Ee!==void 0&&(h["x-google-max-bitrate"]=Ee),ge!==void 0&&(h["x-google-min-bitrate"]=ge);break}}}let v={payload:u.payloadType,config:""};for(let S of Object.keys(h))v.config&&(v.config+=";"),v.config+=`${S}=${h[S]}`;v.config&&this._mediaObject.fmtp.push(v);for(let S of y)this._mediaObject.rtcpFb.push({payload:u.payloadType,type:S.type,subtype:S.parameter})}this._mediaObject.payloads=c.codecs.map(u=>u.payloadType).join(" "),this._mediaObject.ext=[];for(let u of c.headerExtensions)(o.ext??[]).some(h=>h.uri===u.uri)&&this._mediaObject.ext.push({uri:u.uri,value:u.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let u of o.rids??[])u.direction==="send"&&this._mediaObject.rids.push({id:u.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let u of o.rids??[])u.direction==="send"&&this._mediaObject.rids.push({id:u.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let s=this._mediaObject.simulcast.list1,n=sL.parseSimulcastStreamList(s);for(let i of n)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=n.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};bo.AnswerMediaSection=db;var ub=class extends Pf{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:u}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},n?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:d,appdata:u}];for(let v of c.codecs){let S={payload:v.payloadType,codec:_C(v),rate:v.clockRate};v.channels>1&&(S.encoding=v.channels),this._mediaObject.rtp.push(S);let C={payload:v.payloadType,config:""};for(let O of Object.keys(v.parameters??{}))C.config&&(C.config+=";"),C.config+=`${O}=${v.parameters[O]}`;C.config&&this._mediaObject.fmtp.push(C);for(let O of v.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:v.payloadType,type:O.type,subtype:O.parameter})}this._mediaObject.payloads=c.codecs.map(v=>v.payloadType).join(" "),this._mediaObject.ext=[];for(let v of c.headerExtensions)this._mediaObject.ext.push({uri:v.uri,value:v.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let f=c.encodings[0],h=f.ssrc,y=f.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],h&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:h,attribute:"cname",value:c.rtcp.cname}),y&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:y,attribute:"cname",value:c.rtcp.cname}),h&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${h} ${y}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};bo.OfferMediaSection=ub;function _C(r){let t=new RegExp("^(audio|video)/(.+)","i").exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Pd=se(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.RemoteSdp=void 0;var nL=Si(),iL=Yr(),T0=EC(),oL=lb(),aL=["av1","h264"],A0=new iL.Logger("RemoteSdp"),fb=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=s,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${oL.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),s){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:s.fingerprints[o-1].algorithm,hash:s.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){A0.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){A0.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){A0.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:s,answerRtpParameters:n,codecOptions:i}){let o=new T0.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:s,answerRtpParameters:n,codecOptions:i}),a=o.getObject();a.rtp.find(d=>aL.includes(d.codec.toLowerCase()))||(a.ext=a.ext?.filter(d=>d.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:s,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();let o=new T0.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:s,streamId:n,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(A0.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let s=this.findMediaSection(e);s.muxSimulcastStreams(t),this.replaceMediaSection(s)}sendSctpAssociation({offerMediaObject:e}){let t=new T0.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new T0.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,nL.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let s=this._midToIndex.get(t);if(s===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let n=this._mediaSections[s];this._mediaSections[s]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,s),this._sdpObject.media[s]=e.getObject(),this.regenerateBundleMids()}else{let s=this._midToIndex.get(e.mid);if(s===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[s]=e,this._sdpObject.media[s]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};I0.RemoteSdp=fb});var Bd=se(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.extractRtpCapabilities=cL;La.extractDtlsParameters=dL;La.getCname=uL;La.applyCodecParameters=fL;La.addHeaderExtension=lL;var CC=Si();function cL({sdpObject:r}){let e=new Map,t=new Map;for(let n of r.media){let i=n.type;switch(i){case"audio":case"video":break;default:continue}for(let o of n.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of n.fmtp??[]){let a=CC.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of n.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of n.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function dL({sdpObject:r}){let e=r.setup,t=r.fingerprint;if(!e||!t){let i=(r.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let s;switch(e){case"active":{s="client";break}case"passive":{s="server";break}case"actpass":{s="auto";break}}return{role:s,fingerprints:[{algorithm:t.type,value:t.hash}]}}function uL({offerMediaObject:r}){let e=(r.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function fL({offerRtpParameters:r,answerMediaObject:e}){for(let t of r.codecs){let s=t.mimeType.toLowerCase();if(s!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=CC.parseParams(i.config);if(s==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function lL({offerMediaObject:r,headerExtensionUri:e,headerExtensionId:t}){r.ext||(r.ext=[]),r.ext.push({uri:e,value:t})}});var Nd=se(R0=>{"use strict";Object.defineProperty(R0,"__esModule",{value:!0});R0.getRtpEncodings=hL;R0.addLegacySimulcast=pL;function hL({offerMediaObject:r,codecs:e}){let t=new Set;for(let i of r.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let s=new Map;for(let i of r.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),s.set(a,c))}for(let i of t)s.set(i,void 0);let n=[];for(let[i,o]of s){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),n.push(a)}return n}function pL({offerMediaObject:r,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(r.ssrcs??[]).find(f=>f.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[s,n]=t.value.split(" "),i=Number(t.id),o;(r.ssrcGroups??[]).some(f=>{if(f.semantics!=="FID")return!1;let h=f.ssrcs.split(/\s+/);return Number(h[0])===i?(o=Number(h[1]),!0):!1});let a=(r.ssrcs??[]).find(f=>f.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,d=[],u=[];for(let f=0;f<e;++f)d.push(i+f),o&&u.push(o+f);r.ssrcGroups=[],r.ssrcs=[],r.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(let f of d)r.ssrcs.push({id:f,attribute:"cname",value:c}),r.ssrcs.push({id:f,attribute:"msid",value:`${s} ${n}`});for(let f=0;f<u.length;++f){let h=d[f],y=u[f];r.ssrcs.push({id:y,attribute:"cname",value:c}),r.ssrcs.push({id:y,attribute:"msid",value:`${s} ${n}`}),r.ssrcGroups.push({semantics:"FID",ssrcs:`${h} ${y}`})}}});var Od=se(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});Bf.addNackSupportForOpus=mL;Bf.addHeaderExtensionSupport=gL;Bf.getMsidStreamIdAndTrackId=yL;function mL(r){for(let e of r.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function gL(r,e){let t,s=r.headerExtensions?.find(i=>i.uri===e.uri);if(s){if(s.kind===e.kind)return;t=s.preferredId}if(r.headerExtensions||(r.headerExtensions=[]),t===void 0){t=1;let i=new Set(r.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let n={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};r.headerExtensions.push(n)}function yL(r){if(!r||typeof r!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=r.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var RC=se(k0=>{"use strict";Object.defineProperty(k0,"__esModule",{value:!0});k0.Chrome111=void 0;var On=Si(),xL=as(),bL=Yr(),Nf=kn(),vL=Ls(),wL=Oa(),SL=Pd(),Of=Bd(),TC=Nd(),hb=Od(),et=new bL.Logger("Chrome111"),AC="Chrome111",IC={OS:65535,MIS:65535},pb=class r extends xL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:AC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{et.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=On.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(et.debug("getNativeSctpCapabilities()"),{numStreams:IC})}}static getLocalRtpCapabilities(e,t=[]){let s=Of.extractRtpCapabilities({sdpObject:e});Nf.validateAndNormalizeRtpCapabilities(s),hb.addNackSupportForOpus(s);for(let n of t)hb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),et.debug("constructor()"),this._direction=e,this._remoteSdp=new SL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(et.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return AC}close(){if(et.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),et.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),et.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});et.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),et.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1){let Q=1;for(let oe of s){let te=oe.scalabilityMode?(0,wL.parse)(oe.scalabilityMode).temporalLayers:3;te>Q&&(Q=te)}s.forEach((oe,te)=>{oe.rid=`r${te}`,oe.scalabilityMode=`L1T${Q}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});a&&a(d.sender);let u=await this._pc.createOffer(),f=On.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Nf.getSendingRtpParameters(e.kind,v);S.codecs=Nf.reduceCodecs(S.codecs,o);let C=Nf.getSendingRemoteRtpParameters(e.kind,v);if(C.codecs=Nf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),i?.absCaptureTime){let Q=f.media[c.idx];Of.addHeaderExtension({offerMediaObject:Q,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:On.write(f)}}et.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let O=d.mid;S.mid=O,f=On.parse(this._pc.localDescription.sdp);let K=f.media[c.idx];if(S.rtcp.cname=Of.getCname({offerMediaObject:K}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=TC.getRtpEncodings({offerMediaObject:K,codecs:S.codecs});else if(s.length===1){let Q=TC.getRtpEncodings({offerMediaObject:K,codecs:S.codecs});Object.assign(Q[0],s[0]),S.encodings=Q}else S.encodings=s;this._remoteSdp.send({offerMediaObject:K,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let z={type:"answer",sdp:this._remoteSdp.getSdp()};return et.debug("send() | calling pc.setRemoteDescription() [answer:%o]",z),await this._pc.setRemoteDescription(z),this._mapMidTransceiver.set(O,d),{localId:O,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),et.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();et.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),et.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();et.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),et.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();et.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?et.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):et.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),et.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();et.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),et.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();et.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};et.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%IC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=On.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),et.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;et.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=hb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=On.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Of.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:On.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),et.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){et.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){et.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){et.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};et.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=On.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:On.write(y)},et.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=On.parse(this._pc.localDescription.sdp));let s=Of.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new vL.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};k0.Chrome111=pb});var BC=se(P0=>{"use strict";Object.defineProperty(P0,"__esModule",{value:!0});P0.Chrome74=void 0;var Ds=Si(),_L=Yr(),EL=as(),Lf=kn(),CL=Ls(),TL=Oa(),AL=Pd(),Df=Bd(),mb=Nd(),gb=Od(),Je=new _L.Logger("Chrome74"),kC="Chrome74",PC={OS:1024,MIS:1024},yb=class r extends EL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:kC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Je.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Ds.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Je.debug("getNativeSctpCapabilities()"),{numStreams:PC})}}static getLocalRtpCapabilities(e,t=[]){let s=Df.extractRtpCapabilities({sdpObject:e});Lf.validateAndNormalizeRtpCapabilities(s),gb.addNackSupportForOpus(s);for(let n of t)gb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Je.debug("constructor()"),this._direction=e,this._remoteSdp=new AL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Je.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return kC}close(){if(Je.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Je.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Je.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Je.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),Je.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((oe,te)=>{oe.rid=`r${te}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s}),d=await this._pc.createOffer(),u=Ds.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let f=[];f.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let h=r.getLocalRtpCapabilities(u,f),y=this._getSendExtendedRtpCapabilities(h),v=Lf.getSendingRtpParameters(e.kind,y);v.codecs=Lf.reduceCodecs(v.codecs,o);let S=Lf.getSendingRemoteRtpParameters(e.kind,y);S.codecs=Lf.reduceCodecs(S.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let C=!1,O=(0,TL.parse)((s??[{}])[0].scalabilityMode),K;s?.length===1&&O.spatialLayers>1&&v.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(Je.debug("send() | enabling legacy simulcast for VP9 SVC"),C=!0,u=Ds.parse(d.sdp),K=u.media[a.idx],mb.addLegacySimulcast({offerMediaObject:K,numStreams:O.spatialLayers}),d={type:"offer",sdp:Ds.write(u)}),Je.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),i?.absCaptureTime&&(K=u.media[a.idx],Df.addHeaderExtension({offerMediaObject:K,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:S.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Ds.write(u)}),await this._pc.setLocalDescription(d);let z=c.mid;if(v.mid=z,u=Ds.parse(this._pc.localDescription.sdp),K=u.media[a.idx],v.rtcp.cname=Df.getCname({offerMediaObject:K}),v.msid=`${t??this._sendStream.id} ${e.id}`,!s)v.encodings=mb.getRtpEncodings({offerMediaObject:K,codecs:v.codecs});else if(s.length===1){let oe=mb.getRtpEncodings({offerMediaObject:K,codecs:v.codecs});Object.assign(oe[0],s[0]),C&&(oe=[oe[0]]),v.encodings=oe}else v.encodings=s;if(v.encodings.length>1&&(v.codecs[0].mimeType.toLowerCase()==="video/vp8"||v.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let oe of v.encodings)oe.scalabilityMode?oe.scalabilityMode=`L1T${O.temporalLayers}`:oe.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:K,reuseMid:a.reuseMid,offerRtpParameters:v,answerRtpParameters:S,codecOptions:n});let Q={type:"answer",sdp:this._remoteSdp.getSdp()};return Je.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Q),await this._pc.setRemoteDescription(Q),this._mapMidTransceiver.set(z,c),{localId:z,rtpParameters:v,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),Je.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Je.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Je.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Je.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Je.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();Je.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Je.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Je.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Je.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Je.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Je.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Je.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Je.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%PC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ds.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Je.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Je.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=gb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer(),o=Ds.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Df.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Ds.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Je.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Je.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Je.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Je.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Je.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Ds.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Ds.write(y)},Je.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ds.parse(this._pc.localDescription.sdp));let s=Df.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new CL.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};P0.Chrome74=yb});var MC=se(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});N0.Firefox120=void 0;var _i=Si(),IL=as(),RL=Yr(),NC=Ls(),Mf=kn(),kL=Oa(),PL=Pd(),B0=Bd(),OC=Nd(),BL=Od(),tt=new RL.Logger("Firefox120"),LC="Firefox120",DC={OS:16,MIS:2048},xb=class r extends IL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:LC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{tt.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),s=document.createElement("canvas");s.getContext("2d");let i=s.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{s.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=_i.parse(o.sdp);return r.getLocalRtpCapabilities(a)}catch(o){try{s.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(tt.debug("getNativeSctpCapabilities()"),{numStreams:DC})}}static getLocalRtpCapabilities(e){let t=B0.extractRtpCapabilities({sdpObject:e});return Mf.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),tt.debug("constructor()"),this._direction=e,this._remoteSdp=new PL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(tt.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return LC}close(){if(tt.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new NC.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),tt.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});tt.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),tt.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((K,z)=>{K.rid=`r${z}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});o&&o(a.sender);let c=await this._pc.createOffer(),d=_i.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=r.getLocalRtpCapabilities(d),f=this._getSendExtendedRtpCapabilities(u),h=Mf.getSendingRtpParameters(e.kind,f);h.codecs=Mf.reduceCodecs(h.codecs,i);let y=Mf.getSendingRemoteRtpParameters(e.kind,f);y.codecs=Mf.reduceCodecs(y.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let v=(0,kL.parse)((s??[{}])[0].scalabilityMode);tt.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let S=a.mid;h.mid=S,d=_i.parse(this._pc.localDescription.sdp);let C=d.media[d.media.length-1];if(h.rtcp.cname=B0.getCname({offerMediaObject:C}),h.msid=`${t??this._sendStream.id} ${e.id}`,!s)h.encodings=OC.getRtpEncodings({offerMediaObject:C,codecs:h.codecs});else if(s.length===1){let K=OC.getRtpEncodings({offerMediaObject:C,codecs:h.codecs});Object.assign(K[0],s[0]),h.encodings=K}else h.encodings=s;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let K of h.encodings)K.scalabilityMode?K.scalabilityMode=`L1T${v.temporalLayers}`:K.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:C,offerRtpParameters:h,answerRtpParameters:y,codecOptions:n});let O={type:"answer",sdp:this._remoteSdp.getSdp()};return tt.debug("send() | calling pc.setRemoteDescription() [answer:%o]",O),await this._pc.setRemoteDescription(O),this._mapMidTransceiver.set(S,a),{localId:S,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),tt.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let s=await this._pc.createOffer();tt.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),tt.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();tt.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),tt.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let s=await this._pc.createOffer();tt.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?tt.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):tt.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),tt.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated transceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();tt.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),tt.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();tt.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};tt.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%DC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=_i.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),tt.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;tt.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=BL.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=_i.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);B0.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f}),i={type:"answer",sdp:_i.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),tt.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(!u)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){tt.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){tt.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){tt.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};tt.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=_i.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:y}),h={type:"answer",sdp:_i.write(y)},tt.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=_i.parse(this._pc.localDescription.sdp));let s=B0.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new NC.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};N0.Firefox120=xb});var FC=se(O0=>{"use strict";Object.defineProperty(O0,"__esModule",{value:!0});O0.Safari12=void 0;var Ms=Si(),NL=as(),OL=Yr(),Uf=kn(),LL=Ls(),DL=Oa(),ML=Pd(),jf=Bd(),UC=Nd(),bb=Od(),Qe=new OL.Logger("Safari12"),jC="Safari12",HC={OS:65535,MIS:65535},vb=class r extends NL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:jC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Qe.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Ms.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Qe.debug("getNativeSctpCapabilities()"),{numStreams:HC})}}static getLocalRtpCapabilities(e,t=[]){let s=jf.extractRtpCapabilities({sdpObject:e});Uf.validateAndNormalizeRtpCapabilities(s),bb.addNackSupportForOpus(s);for(let n of t)bb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Qe.debug("constructor()"),this._direction=e,this._remoteSdp=new ML.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",u=>{this.emit("@icecandidateerror",u)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Qe.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return jC}close(){if(Qe.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Qe.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Qe.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Qe.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(d.sender);let u=await this._pc.createOffer(),f=Ms.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Uf.getSendingRtpParameters(e.kind,v);S.codecs=Uf.reduceCodecs(S.codecs,o);let C=Uf.getSendingRemoteRtpParameters(e.kind,v);C.codecs=Uf.reduceCodecs(C.codecs,o);let O;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let K=(0,DL.parse)((s??[{}])[0].scalabilityMode);s&&s.length>1&&(Qe.debug("send() | enabling legacy simulcast"),f=Ms.parse(u.sdp),O=f.media[c.idx],UC.addLegacySimulcast({offerMediaObject:O,numStreams:s.length}),u={type:"offer",sdp:Ms.write(f)}),i?.absCaptureTime&&(O=f.media[c.idx],jf.addHeaderExtension({offerMediaObject:O,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:Ms.write(f)}),Qe.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let z=d.mid;if(S.mid=z,f=Ms.parse(this._pc.localDescription.sdp),O=f.media[c.idx],S.rtcp.cname=jf.getCname({offerMediaObject:O}),S.msid=`${t??this._sendStream.id} ${e.id}`,S.encodings=UC.getRtpEncodings({offerMediaObject:O,codecs:S.codecs}),s)for(let oe=0;oe<S.encodings.length;++oe)s[oe]&&Object.assign(S.encodings[oe],s[oe]);if(S.encodings.length>1&&(S.codecs[0].mimeType.toLowerCase()==="video/vp8"||S.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let oe of S.encodings)oe.scalabilityMode?oe.scalabilityMode=`L1T${K.temporalLayers}`:oe.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:O,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let Q={type:"answer",sdp:this._remoteSdp.getSdp()};return Qe.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Q),await this._pc.setRemoteDescription(Q),this._mapMidTransceiver.set(z,d),{localId:z,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Qe.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Qe.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Qe.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let s=await this._pc.createOffer();Qe.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Qe.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Qe.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Qe.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Qe.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Qe.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%HC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ms.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Qe.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Qe.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=bb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=Ms.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);jf.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Ms.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Qe.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(!u)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Qe.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Qe.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Qe.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Qe.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Ms.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Ms.write(y)},Qe.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ms.parse(this._pc.localDescription.sdp));let s=jf.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new LL.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};O0.Safari12=vb});var $C=se(L0=>{"use strict";Object.defineProperty(L0,"__esModule",{value:!0});L0.ReactNative106=void 0;var Us=Si(),UL=as(),jL=Yr(),Hf=kn(),HL=Ls(),FL=Oa(),qL=Pd(),Ff=Bd(),wb=Nd(),Sb=Od(),Ye=new jL.Logger("ReactNative106"),qC="ReactNative106",zC={OS:65535,MIS:65535},_b=class r extends UL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:qC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Ye.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Us.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Ye.debug("getNativeSctpCapabilities()"),{numStreams:zC})}}static getLocalRtpCapabilities(e,t=[]){let s=Ff.extractRtpCapabilities({sdpObject:e});Hf.validateAndNormalizeRtpCapabilities(s),Sb.addNackSupportForOpus(s);for(let n of t)Sb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Ye.debug("constructor()"),this._direction=e,this._remoteSdp=new qL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Ye.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return qC}close(){if(Ye.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Ye.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ye.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Ye.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((te,Ee)=>{te.rid=`r${Ee}`});let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});a&&a(d.sender);let u=await this._pc.createOffer(),f=Us.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Hf.getSendingRtpParameters(e.kind,v);S.codecs=Hf.reduceCodecs(S.codecs,o);let C=Hf.getSendingRemoteRtpParameters(e.kind,v);C.codecs=Hf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let O=!1,K=(0,FL.parse)((s??[{}])[0].scalabilityMode),z;s?.length===1&&K.spatialLayers>1&&S.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(Ye.debug("send() | enabling legacy simulcast for VP9 SVC"),O=!0,f=Us.parse(u.sdp),z=f.media[c.idx],wb.addLegacySimulcast({offerMediaObject:z,numStreams:K.spatialLayers}),u={type:"offer",sdp:Us.write(f)}),i?.absCaptureTime&&(z=f.media[c.idx],Ff.addHeaderExtension({offerMediaObject:z,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(te=>te.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:Us.write(f)}),Ye.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let Q=d.mid??void 0;if(Q||Ye.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),S.mid=Q,f=Us.parse(this._pc.localDescription.sdp),z=f.media[c.idx],S.rtcp.cname=Ff.getCname({offerMediaObject:z}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=wb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});else if(s.length===1){let te=wb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});Object.assign(te[0],s[0]),O&&(te=[te[0]]),S.encodings=te}else S.encodings=s;if(S.encodings.length>1&&(S.codecs[0].mimeType.toLowerCase()==="video/vp8"||S.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let te of S.encodings)te.scalabilityMode?te.scalabilityMode=`L1T${K.temporalLayers}`:te.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:z,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let oe={type:"answer",sdp:this._remoteSdp.getSdp()};return Ye.debug("send() | calling pc.setRemoteDescription() [answer:%o]",oe),await this._pc.setRemoteDescription(oe),Q||(Q=d.mid,S.mid=Q),this._mapMidTransceiver.set(Q,d),{localId:Q,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Ye.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Ye.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Ye.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();Ye.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ye.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ye.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Ye.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Ye.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Ye.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%zC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Us.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Ye.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Ye.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=Sb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=Us.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Ff.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Us.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Ye.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Ye.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Ye.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Ye.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Ye.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Us.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Us.write(y)},Ye.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Us.parse(this._pc.localDescription.sdp));let s=Ff.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new HL.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};L0.ReactNative106=_b});var GC=se(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});Ld.Device=void 0;Ld.detectDevice=VC;Ld.detectDeviceAsync=KC;var zL=Yr(),$L=as(),vo=Ls(),D0=ka(),Ss=kn(),VL=pC(),KL=RC(),WL=BC(),GL=MC(),XL=FC(),YL=$C(),He=new zL.Logger("Device");function VC(r,e){return He.debug("detectDevice()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),WC(r,e)}async function KC(r,e){return He.debug("detectDeviceAsync()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),WC(r,e)}var Eb=class r{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new $L.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(He.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await KC(),!e))throw new vo.UnsupportedError("device not supported");return new r({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(He.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)He.debug("constructor() | handler given: %s",e);else if(e=VC(),e)He.debug("constructor() | detected handler: %s",e);else throw new vo.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=KL.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=WL.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=GL.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=XL.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=YL.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new vo.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new vo.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new vo.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(He.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new vo.InvalidStateError("already loaded");let s=D0.clone(e);Ss.validateAndNormalizeRtpCapabilities(s);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=D0.clone(await n({direction:"recvonly"}));He.debug("load() | got native receiving RTP capabilities:%o",o),Ss.validateAndNormalizeRtpCapabilities(o);let a=D0.clone(await n({direction:"sendonly"}));He.debug("load() | got native sending RTP capabilities:%o",a),Ss.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=u=>D0.clone(Ss.getExtendedRtpCapabilities(u,s,t));let c=Ss.getExtendedRtpCapabilities(o,s,!1);this._recvRtpCapabilities=Ss.getRecvRtpCapabilities(c),He.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),Ss.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let d=Ss.getExtendedRtpCapabilities(a,s,t);this._sendRtpCapabilities=Ss.getSendRtpCapabilities(d),He.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),Ss.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=Ss.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=Ss.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),Ss.validateSctpCapabilities(this._sctpCapabilities),He.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),He.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new vo.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return He.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return He.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createTransport({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof s!="object")throw new TypeError("missing iceParameters");if(Array.isArray(n)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(u&&typeof u!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new vo.InvalidStateError("not loaded");let f=new VL.Transport({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",f),f}};Ld.Device=Eb;function WC(r,e){He.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',r,e);let t=JL(r,e);if(t){if(t>=111)return He.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return He.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";He.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let s=QL(r);if(s){if(s>=120)return He.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";He.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let n=ZL(r);if(n){if(n>=605)return He.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";He.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=eD(r);if(i){if(i>=605)return He.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";He.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(qf()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return He.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";He.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}He.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',r,e)}function JL(r,e){if(He.debug("getChromiumMajorVersion()"),M0(r,e)){He.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(qf()){He.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let n=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(n){let i=Number(n.version);return He.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=r?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let s=Number(t[1]);return He.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${s}`),s}He.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function QL(r){if(He.debug("getFirefoxMajorVersion()"),M0(r)){He.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(qf()){He.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return He.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}He.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function ZL(r){if(He.debug("getMacOSWebKitMajorVersion()"),M0(r)){He.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(qf()){He.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(r&&/\bSafari\b/i.test(r)&&!/\bChrome\b/i.test(r)&&!/\bChromium\b/i.test(r)&&!/\bFirefox\b/i.test(r))){He.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=r.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let s=Number(t[1]);return He.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${s}`),s}He.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function eD(r){if(He.debug("getIOSWebKitMajorVersion()"),!M0(r)){He.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(qf()){He.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return He.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}He.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function M0(r,e){return He.debug("isIOS()"),e?.platform==="iOS"?(He.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(He.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):r&&/iPad|iPhone|iPod/.test(r)?(He.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(He.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(He.debug("isIOS() | this is not iOS => false"),!1)}function qf(){return He.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(He.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(He.debug("isReactNative() | this is not React-Native => false"),!1)}});var YC=se(XC=>{"use strict";var Da=256,j0=[],U0;for(;Da--;)j0[Da]=(Da+256).toString(16).substring(1);function tD(){var r=0,e,t="";if(!U0||Da+16>256){for(U0=Array(r=256);r--;)U0[r]=256*Math.random()|0;r=Da=0}for(;r<16;r++)e=U0[Da+r],r==6?t+=j0[e&15|64]:r==8?t+=j0[e&63|128]:t+=j0[e],r&1&&r>1&&r<11&&(t+="-");return Da++,t}XC.v4=tD});var JC=se(H0=>{"use strict";Object.defineProperty(H0,"__esModule",{value:!0});H0.FakeEventTarget=void 0;var Cb=class{listeners={};addEventListener(e,t,s){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof s=="object"&&s.once===!0}))}removeEventListener(e,t,s){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let s of[...t]){try{s.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}s.once&&this.removeEventListener(e.type,s.callback)}return!e.defaultPrevented}};H0.FakeEventTarget=Cb});var QC=se(F0=>{"use strict";Object.defineProperty(F0,"__esModule",{value:!0});F0.FakeEvent=void 0;var Tb=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,s){}};F0.FakeEvent=Tb});var ZC=se(Ab=>{"use strict";Object.defineProperty(Ab,"__esModule",{value:!0});Ab.clone=rD;function rD(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}});var t6=se(z0=>{"use strict";Object.defineProperty(z0,"__esModule",{value:!0});z0.FakeMediaStreamTrack=void 0;var e6=YC(),sD=JC(),Dd=QC(),q0=ZC(),Ib=class r extends sD.FakeEventTarget{#m;#f;#l;#e;#r;#t;#s;#h;#n;#p;#i;#o=null;#a=null;#c=null;#d=null;#u=null;constructor({kind:e,id:t,label:s,contentHint:n,enabled:i,muted:o,readyState:a,capabilities:c,constraints:d,settings:u,data:f}){super(),this.#m=t??(0,e6.v4)(),this.#f=e,this.#l=s??"",this.#s=n??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#n=d??{},this.#p=u??{},this.#i=f??{}}get id(){return this.#m}get kind(){return this.#f}get label(){return this.#l}get contentHint(){return this.#s}set contentHint(e){this.#s=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new Dd.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#u}set onstopped(e){this.#u&&this.removeEventListener("stopped",this.#u),this.#u=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,s){super.addEventListener(e,t,s)}removeEventListener(e,t,s){super.removeEventListener(e,t,s)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Dd.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new r({id:e??(0,e6.v4)(),kind:this.#f,label:this.#l,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,q0.clone)(this.#h),constraints:(0,q0.clone)(this.#n),settings:(0,q0.clone)(this.#p),data:t??(0,q0.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#n}async applyConstraints(e={}){return this.#n=e,Promise.resolve()}getSettings(){return this.#p}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Dd.FakeEvent("stopped")),this.dispatchEvent(new Dd.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new Dd.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new Dd.FakeEvent("unmute")))}};z0.FakeMediaStreamTrack=Ib});var r6=se($0=>{"use strict";Object.defineProperty($0,"__esModule",{value:!0});$0.FakeEventTarget=void 0;var Rb=class{listeners={};addEventListener(e,t,s){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof s=="object"&&s.once===!0}))}removeEventListener(e,t,s){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let s of[...t]){try{s.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}s.once&&this.removeEventListener(e.type,s.callback)}return!e.defaultPrevented}};$0.FakeEventTarget=Rb});var i6=se(K0=>{"use strict";Object.defineProperty(K0,"__esModule",{value:!0});K0.FakeHandler=void 0;var nD=t6(),iD=as(),oD=Yr(),Md=ka(),kb=kn(),n6=Ls(),aD=r6(),Ar=new oD.Logger("FakeHandler"),s6="FakeHandler",Pb=class r extends iD.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Md.generateRandomNumber()}`;_defaultSendStreamId=`${Md.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:s6,factory:t=>new r(t,e),getNativeRtpCapabilities:async({direction:t})=>(Ar.debug("getNativeRtpCapabilities() [direction:%o]",t),r.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Ar.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return kb.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Ar.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return s6}close(){Ar.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),Ar.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Ar.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:s,codecOptions:n,codec:i}){this.assertNotClosed(),Ar.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=r.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=kb.getSendingRtpParameters(e.kind,a);c.codecs=kb.reduceCodecs(c.codecs,i);let d=c.codecs.some(f=>/.+\/rtx$/i.test(f.mimeType));c.mid=`mid-${Md.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,s||(s=[{}]);for(let f of s)f.ssrc=Md.generateRandomNumber(),d&&(f.rtx={ssrc:Md.generateRandomNumber()});c.encodings=s,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let u=this._nextLocalId++;return this._tracks.set(u,e),{localId:String(u),rtpParameters:c}}async stopSending(e){if(Ar.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?Ar.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ar.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Ar.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Ar.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Ar.debug("sendDataChannel()");let t=new V0({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),s={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:s}}async receive(e){this.assertNotClosed();let t=[];for(let s of e){let{trackId:n,kind:i}=s;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ar.debug("receive() [trackId:%s, kind:%s]",n,i);let o=this._nextLocalId++,a=new nD.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)Ar.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:s}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ar.debug("receiveDataChannel()"),{dataChannel:new V0({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:s})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let s=Md.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(s.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((n,i)=>this.emit("@connect",{dtlsParameters:s},n,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new n6.InvalidStateError("method called in a closed handler")}};K0.FakeHandler=Pb;var V0=class extends aD.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:s=null,maxRetransmits:n=null,label:i="",protocol:o=""}){super(),Ar.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${s}, maxRetransmits:${n}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=s,this._maxRetransmits=n,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,s){super.addEventListener(e,t,s)}removeEventListener(e,t,s){super.removeEventListener(e,t,s)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new n6.InvalidStateError("not open")}}});var o6=se(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.generateRouterRtpCapabilities=cD;sn.generateNativeRtpCapabilities=dD;sn.generateNativeSctpCapabilities=uD;sn.generateLocalDtlsParameters=fD;sn.generateTransportRemoteParameters=lD;sn.generateProducerRemoteParameters=hD;sn.generateConsumerRemoteParameters=pD;sn.generateDataProducerRemoteParameters=mD;sn.generateDataConsumerRemoteParameters=gD;var Qr=ka();function _s(){return String(Qr.generateRandomNumber())}function cD(){return Qr.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function dD(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function uD(){return Qr.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function fD(){return Qr.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function lD(){return{id:_s(),iceParameters:Qr.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Qr.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:Qr.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:Qr.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function hD(){return Qr.deepFreeze({id:_s()})}function pD({id:r,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:r??_s(),producerId:_s(),kind:"audio",rtpParameters:Qr.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:r??_s(),producerId:_s(),kind:"audio",rtpParameters:Qr.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:r??_s(),producerId:_s(),kind:"video",rtpParameters:Qr.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:r??_s(),producerId:_s(),kind:"video",rtpParameters:Qr.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function mD(){return Qr.deepFreeze({id:_s()})}function gD({id:r}={}){return{id:r??_s(),dataProducerId:_s(),sctpStreamParameters:Qr.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var lb=se(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.debug=Qt.testFakeParameters=Qt.FakeHandler=Qt.enhancedEvents=Qt.ortc=Qt.parseScalabilityMode=Qt.detectDeviceAsync=Qt.detectDevice=Qt.Device=Qt.version=Qt.types=void 0;var yD=Af();Qt.debug=yD.default;Qt.types=PE();Qt.version="3.20.0";var Bb=GC();Object.defineProperty(Qt,"Device",{enumerable:!0,get:function(){return Bb.Device}});Object.defineProperty(Qt,"detectDevice",{enumerable:!0,get:function(){return Bb.detectDevice}});Object.defineProperty(Qt,"detectDeviceAsync",{enumerable:!0,get:function(){return Bb.detectDeviceAsync}});var xD=Oa();Object.defineProperty(Qt,"parseScalabilityMode",{enumerable:!0,get:function(){return xD.parse}});Qt.ortc=kn();Qt.enhancedEvents=as();var bD=i6();Object.defineProperty(Qt,"FakeHandler",{enumerable:!0,get:function(){return bD.FakeHandler}});Qt.testFakeParameters=o6()});var c6=se(($K,Nb)=>{"use strict";var vD=Object.prototype.hasOwnProperty,Zr="~";function zf(){}Object.create&&(zf.prototype=Object.create(null),new zf().__proto__||(Zr=!1));function wD(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function a6(r,e,t,s,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new wD(t,s||r,n),o=Zr?Zr+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function W0(r,e){--r._eventsCount===0?r._events=new zf:delete r._events[e]}function qr(){this._events=new zf,this._eventsCount=0}qr.prototype.eventNames=function(){var e=[],t,s;if(this._eventsCount===0)return e;for(s in t=this._events)vD.call(t,s)&&e.push(Zr?s.slice(1):s);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};qr.prototype.listeners=function(e){var t=Zr?Zr+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var n=0,i=s.length,o=new Array(i);n<i;n++)o[n]=s[n].fn;return o};qr.prototype.listenerCount=function(e){var t=Zr?Zr+e:e,s=this._events[t];return s?s.fn?1:s.length:0};qr.prototype.emit=function(e,t,s,n,i,o){var a=Zr?Zr+e:e;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,s),!0;case 4:return c.fn.call(c.context,t,s,n),!0;case 5:return c.fn.call(c.context,t,s,n,i),!0;case 6:return c.fn.call(c.context,t,s,n,i,o),!0}for(f=1,u=new Array(d-1);f<d;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var h=c.length,y;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),d){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,s);break;case 4:c[f].fn.call(c[f].context,t,s,n);break;default:if(!u)for(y=1,u=new Array(d-1);y<d;y++)u[y-1]=arguments[y];c[f].fn.apply(c[f].context,u)}}return!0};qr.prototype.on=function(e,t,s){return a6(this,e,t,s,!1)};qr.prototype.once=function(e,t,s){return a6(this,e,t,s,!0)};qr.prototype.removeListener=function(e,t,s,n){var i=Zr?Zr+e:e;if(!this._events[i])return this;if(!t)return W0(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!s||o.context===s)&&W0(this,i);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==t||n&&!o[a].once||s&&o[a].context!==s)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:W0(this,i)}return this};qr.prototype.removeAllListeners=function(e){var t;return e?(t=Zr?Zr+e:e,this._events[t]&&W0(this,t)):(this._events=new zf,this._eventsCount=0),this};qr.prototype.off=qr.prototype.removeListener;qr.prototype.addListener=qr.prototype.on;qr.prefixed=Zr;qr.EventEmitter=qr;typeof Nb<"u"&&(Nb.exports=qr)});var wo=se(d6=>{"use strict";function SD(){var r,e=!1,t=this;t._DeArray=function(s,n,i){return[s.slice(n,n+i)]},t._EnArray=function(s,n,i,o){for(var a=0;a<i;s[n+a]=o[a]?o[a]:0,a++);},t._DeChar=function(s,n){return String.fromCharCode(s[n])},t._EnChar=function(s,n,i){s[n]=i.charCodeAt(0)},t._DeInt=function(s,n){var i=e?r.len-1:0,o=e?-1:1,a=i+o*r.len,c,d,u;for(c=0,d=i,u=1;d!=a;c+=s[n+d]*u,d+=o,u*=256);return r.bSigned&&c&Math.pow(2,r.len*8-1)&&(c-=Math.pow(2,r.len*8)),c},t._EnInt=function(s,n,i){var o=e?r.len-1:0,a=e?-1:1,c=o+a*r.len,d;for(i=i<r.min?r.min:i>r.max?r.max:i,d=o;d!=c;s[n+d]=i&255,d+=a,i>>=8);},t._DeString=function(s,n,i){for(var o=new Array(i),a=0;a<i;o[a]=String.fromCharCode(s[n+a]),a++);return o.join("")},t._EnString=function(s,n,i,o){for(var a,c=0;c<i;s[n+c]=(a=o.charCodeAt(c))?a:0,c++);},t._De754=function(s,n){var i,o,a,c,d,u,f,h,y,v;for(f=r.mLen,h=r.len*8-r.mLen-1,v=(1<<h)-1,y=v>>1,c=e?0:r.len-1,d=e?1:-1,i=s[n+c],c+=d,u=-7,o=i&(1<<-u)-1,i>>=-u,u+=h;u>0;o=o*256+s[n+c],c+=d,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=f;u>0;a=a*256+s[n+c],c+=d,u-=8);switch(o){case 0:o=1-y;break;case v:return a?NaN:(i?-1:1)*(1/0);default:a=a+Math.pow(2,f),o=o-y;break}return(i?-1:1)*a*Math.pow(2,o-f)},t._En754=function(s,n,i){var o,a,c,d,u,f,h,y,v,S;for(h=r.mLen,y=r.len*8-r.mLen-1,S=(1<<y)-1,v=S>>1,o=i<0?1:0,i=Math.abs(i),isNaN(i)||i==1/0?(c=isNaN(i)?1:0,a=S):(a=Math.floor(Math.log(i)/Math.LN2),i*(f=Math.pow(2,-a))<1&&(a--,f*=2),a+v>=1?i+=r.rt/f:i+=r.rt*Math.pow(2,1-v),i*f>=2&&(a++,f/=2),a+v>=S?(c=0,a=S):a+v>=1?(c=(i*f-1)*Math.pow(2,h),a=a+v):(c=i*Math.pow(2,v-1)*Math.pow(2,h),a=0)),d=e?r.len-1:0,u=e?-1:1;h>=8;s[n+d]=c&255,d+=u,c/=256,h-=8);for(a=a<<h|c,y+=h;y>0;s[n+d]=a&255,d+=u,a/=256,y-=8);s[n+d-u]|=o*128},t._DeInt64=function(s,n){var i=e?0:7,o=e?1:-1,a=i+o*8,c=[0,0,!r.bSigned],d,u,f;for(d=i,f=1,u=0;d!=a;c[f]=(c[f]<<8>>>0)+s[n+d],d+=o,u++,f=u<4?1:0);return c},t._EnInt64=function(s,n,i){var o=e?0:7,a=e?1:-1,c=o+a*8,d,u,f,h;for(d=o,f=1,u=0,h=24;d!=c;s[n+d]=i[f]>>h&255,d+=a,u++,f=u<4?1:0,h=24-8*(u%4));},t._sPattern="(\\d + )?([AxcbBhHsfdiIlLqQ])",t._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},t._elLut={A:{en:t._EnArray,de:t._DeArray},s:{en:t._EnString,de:t._DeString},c:{en:t._EnChar,de:t._DeChar},b:{en:t._EnInt,de:t._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:t._EnInt,de:t._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:t._EnInt,de:t._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:t._EnInt,de:t._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:t._En754,de:t._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:t._En754,de:t._De754,len:8,mLen:52,rt:0},q:{en:t._EnInt64,de:t._DeInt64,bSigned:!0},Q:{en:t._EnInt64,de:t._DeInt64,bSigned:!1}},t._UnpackSeries=function(s,n,i,o){for(var a=r.de,c=[],d=0;d<s;c.push(a(i,o+d*n)),d++);return c},t._PackSeries=function(s,n,i,o,a,c){for(var d=r.en,u=0;u<s;d(i,o+u*n,a[c+u]),u++);},t.Unpack=function(s,n,i){e=s.charAt(0)!="<",i=i||0;for(var o=new RegExp(this._sPattern,"g"),a,c,d,u=[];a=o.exec(s);){if(c=a[1]==null||a[1]==""?1:parseInt(a[1]),d=this._lenLut[a[2]],i+c*d>n.length)return;switch(a[2]){case"A":case"s":u.push(this._elLut[a[2]].de(n,i,c));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":r=this._elLut[a[2]],u.push(this._UnpackSeries(c,d,n,i));break}i+=c*d}return Array.prototype.concat.apply([],u)},t.PackTo=function(s,n,i,o){e=s.charAt(0)!="<";for(var a=new RegExp(this._sPattern,"g"),c,d,u,f,h=0;c=a.exec(s);){if(d=c[1]==null||c[1]==""?1:parseInt(c[1]),u=this._lenLut[c[2]],i+d*u>n.length)return!1;switch(c[2]){case"A":case"s":if(h+1>o.length)return!1;this._elLut[c[2]].en(n,i,d,o[h]),h+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(r=this._elLut[c[2]],h+d>o.length)return!1;this._PackSeries(d,u,n,i,o,h),h+=d;break;case"x":for(f=0;f<d;f++)n[i+f]=0;break}i+=d*u}return n},t.Pack=function(s,n){return this.PackTo(s,new Array(this.CalcLength(s)),0,n)},t.CalcLength=function(s){for(var n=new RegExp(this._sPattern,"g"),i=0,o;o=n.exec(s);)i+=(o[1]==null||o[1]==""?1:parseInt(o[1]))*this._lenLut[o[2]];return i}}d6.jspack=new SD});var Lb=se((WK,u6)=>{"use strict";function _D(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Nx(),t.destroy=d,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let h=0;h<u.length;h++)f=(f<<5)-f+u.charCodeAt(h),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,h=null,y,v;function S(...C){if(!S.enabled)return;let O=S,K=Number(new Date),z=K-(f||K);O.diff=z,O.prev=f,O.curr=K,f=K,C[0]=t.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let Q=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(te,Ee)=>{if(te==="%%")return"%";Q++;let ge=t.formatters[Ee];if(typeof ge=="function"){let Y=C[Q];te=ge.call(O,Y),C.splice(Q,1),Q--}return te}),t.formatArgs.call(O,C),(O.log||t.log).apply(O,C)}return S.namespace=u,S.useColors=t.useColors(),S.color=t.selectColor(u),S.extend=s,S.destroy=t.destroy,Object.defineProperty(S,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,v=t.enabled(u)),v),set:C=>{h=C}}),typeof t.init=="function"&&t.init(S),S}function s(u,f){let h=t(this.namespace+(typeof f>"u"?":":f)+u);return h.log=this.log,h}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(" ",",").split(",").filter(Boolean);for(let h of f)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function i(u,f){let h=0,y=0,v=-1,S=0;for(;h<u.length;)if(y<f.length&&(f[y]===u[h]||f[y]==="*"))f[y]==="*"?(v=y,S=h,y++):(h++,y++);else if(v!==-1)y=v+1,S++,h=S;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function o(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(i(u,f))return!1;for(let f of t.names)if(i(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}u6.exports=_D});var f6=se((Es,G0)=>{"use strict";Es.formatArgs=CD;Es.save=TD;Es.load=AD;Es.useColors=ED;Es.storage=ID();Es.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Es.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ED(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function CD(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+G0.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}Es.log=console.debug||console.log||(()=>{});function TD(r){try{r?Es.storage.setItem("debug",r):Es.storage.removeItem("debug")}catch{}}function AD(){let r;try{r=Es.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ID(){try{return localStorage}catch{}}G0.exports=Lb()(Es);var{formatters:RD}=G0.exports;RD.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var h6=se((_r,Y0)=>{"use strict";var kD=require("tty"),X0=require("util");_r.init=MD;_r.log=OD;_r.formatArgs=BD;_r.save=LD;_r.load=DD;_r.useColors=PD;_r.destroy=X0.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");_r.colors=[6,2,3,4,5,1];try{let r=(Ux(),Bx(Mx));r&&(r.stderr||r).level>=2&&(_r.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}_r.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function PD(){return"colors"in _r.inspectOpts?!!_r.inspectOpts.colors:kD.isatty(process.stderr.fd)}function BD(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),i=` ${n};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
8
- `).join(`
9
- `+i),r.push(n+"m+"+Y0.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=ND()+e+" "+r[0]}function ND(){return _r.inspectOpts.hideDate?"":new Date().toISOString()+" "}function OD(...r){return process.stderr.write(X0.formatWithOptions(_r.inspectOpts,...r)+`
10
- `)}function LD(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function DD(){return process.env.DEBUG}function MD(r){r.inspectOpts={};let e=Object.keys(_r.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=_r.inspectOpts[e[t]]}Y0.exports=Lb()(_r);var{formatters:l6}=Y0.exports;l6.o=function(r){return this.inspectOpts.colors=this.useColors,X0.inspect(r,this.inspectOpts).split(`
11
- `).map(e=>e.trim()).join(" ")};l6.O=function(r){return this.inspectOpts.colors=this.useColors,X0.inspect(r,this.inspectOpts)}});var p6=se((GK,Db)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Db.exports=f6():Db.exports=h6()});var J0=se(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var UD=require("net");function jD(r){switch(UD.isIP(r)){case 4:return Buffer.from(r.split(".").map(n=>parseInt(n,10)));case 6:let e=r.split(":"),t=Buffer.alloc(16),s=0;e[e.length-1]===""&&(e[e.length-1]="0");for(let n=0;n<e.length;n++){if(e[n]===""){n+1<e.length&&e[n+1]!==""&&(s=16-(e.length-n-1)*2);continue}t.writeUInt16BE(parseInt(e[n],16),s),s+=2}return t;default:return null}}Ud.bytesFromIP=jD;function HD(r){switch(r.length){case 4:return[r[0],r[1],r[2],r[3]].join(".");case 16:let e=[],t=-1,s=0,n=-1,i=0;for(let o=0;o<r.length;o+=2){let a=r[o]<<8|r[o+1];a===0?(s++,t===-1&&(t=e.length),s>i&&(i=s,n=t)):(t=-1,s=0),e.push(a.toString(16))}if(i>0){let o="",a=e.slice(n+i);e.length=n,e.length===0&&(o+=":"),a.length===0&&(o+=":"),e.push(o,...a)}return e.join(":");default:return""}}Ud.bytesToIP=HD;var So=Object.create(null),m6=/^[0-9.]+$/;function FD(r){return m6.test(r)&&So[r]!==""?r:So[r]==null?"":So[r]}Ud.getOID=FD;function qD(r){return!m6.test(r)&&So[r]!==""||So[r]==null?r:So[r]}Ud.getOIDName=qD;function Z(r,e){So[r]=e,So[e]=r}Z("1.2.840.113549.1.1.1","rsaEncryption");Z("1.2.840.113549.1.1.4","md5WithRsaEncryption");Z("1.2.840.113549.1.1.5","sha1WithRsaEncryption");Z("1.2.840.113549.1.1.8","mgf1");Z("1.2.840.113549.1.1.10","RSASSA-PSS");Z("1.2.840.113549.1.1.11","sha256WithRsaEncryption");Z("1.2.840.113549.1.1.12","sha384WithRsaEncryption");Z("1.2.840.113549.1.1.13","sha512WithRsaEncryption");Z("1.2.840.10045.2.1","ecEncryption");Z("1.2.840.10045.4.1","ecdsaWithSha1");Z("1.2.840.10045.4.3.2","ecdsaWithSha256");Z("1.2.840.10045.4.3.3","ecdsaWithSha384");Z("1.2.840.10045.4.3.4","ecdsaWithSha512");Z("1.2.840.10040.4.3","dsaWithSha1");Z("2.16.840.1.101.3.4.3.2","dsaWithSha256");Z("1.3.14.3.2.7","desCBC");Z("1.3.14.3.2.26","sha1");Z("2.16.840.1.101.3.4.2.1","sha256");Z("2.16.840.1.101.3.4.2.2","sha384");Z("2.16.840.1.101.3.4.2.3","sha512");Z("1.2.840.113549.2.5","md5");Z("1.3.101.110","X25519");Z("1.3.101.111","X448");Z("1.3.101.112","Ed25519");Z("1.3.101.113","Ed448");Z("1.2.840.113549.1.7.1","data");Z("1.2.840.113549.1.7.2","signedData");Z("1.2.840.113549.1.7.3","envelopedData");Z("1.2.840.113549.1.7.4","signedAndEnvelopedData");Z("1.2.840.113549.1.7.5","digestedData");Z("1.2.840.113549.1.7.6","encryptedData");Z("1.2.840.113549.1.9.1","emailAddress");Z("1.2.840.113549.1.9.2","unstructuredName");Z("1.2.840.113549.1.9.3","contentType");Z("1.2.840.113549.1.9.4","messageDigest");Z("1.2.840.113549.1.9.5","signingTime");Z("1.2.840.113549.1.9.6","counterSignature");Z("1.2.840.113549.1.9.7","challengePassword");Z("1.2.840.113549.1.9.8","unstructuredAddress");Z("1.2.840.113549.1.9.14","extensionRequest");Z("1.2.840.113549.1.9.20","friendlyName");Z("1.2.840.113549.1.9.21","localKeyId");Z("1.2.840.113549.1.9.22.1","x509Certificate");Z("1.2.840.113549.1.12.10.1.1","keyBag");Z("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");Z("1.2.840.113549.1.12.10.1.3","certBag");Z("1.2.840.113549.1.12.10.1.4","crlBag");Z("1.2.840.113549.1.12.10.1.5","secretBag");Z("1.2.840.113549.1.12.10.1.6","safeContentsBag");Z("1.2.840.113549.1.5.13","pkcs5PBES2");Z("1.2.840.113549.1.5.12","pkcs5PBKDF2");Z("1.2.840.113549.2.7","hmacWithSha1");Z("1.2.840.113549.2.9","hmacWithSha256");Z("1.2.840.113549.2.10","hmacWithSha384");Z("1.2.840.113549.2.11","hmacWithSha512");Z("1.2.840.113549.3.7","3desCBC");Z("2.16.840.1.101.3.4.1.2","aesCBC128");Z("2.16.840.1.101.3.4.1.42","aesCBC256");Z("2.5.4.3","commonName");Z("2.5.4.5","serialName");Z("2.5.4.6","countryName");Z("2.5.4.7","localityName");Z("2.5.4.8","stateOrProvinceName");Z("2.5.4.10","organizationName");Z("2.5.4.11","organizationalUnitName");Z("2.5.4.15","businessCategory");Z("2.16.840.1.113730.1.1","nsCertType");Z("2.5.29.2","keyAttributes");Z("2.5.29.4","keyUsageRestriction");Z("2.5.29.6","subtreesConstraint");Z("2.5.29.9","subjectDirectoryAttributes");Z("2.5.29.14","subjectKeyIdentifier");Z("2.5.29.15","keyUsage");Z("2.5.29.16","privateKeyUsagePeriod");Z("2.5.29.17","subjectAltName");Z("2.5.29.18","issuerAltName");Z("2.5.29.19","basicConstraints");Z("2.5.29.20","cRLNumber");Z("2.5.29.21","cRLReason");Z("2.5.29.22","expirationDate");Z("2.5.29.23","instructionCode");Z("2.5.29.24","invalidityDate");Z("2.5.29.27","deltaCRLIndicator");Z("2.5.29.28","issuingDistributionPoint");Z("2.5.29.29","certificateIssuer");Z("2.5.29.30","nameConstraints");Z("2.5.29.31","cRLDistributionPoints");Z("2.5.29.32","certificatePolicies");Z("2.5.29.33","policyMappings");Z("2.5.29.35","authorityKeyIdentifier");Z("2.5.29.36","policyConstraints");Z("2.5.29.37","extKeyUsage");Z("2.5.29.46","freshestCRL");Z("2.5.29.54","inhibitAnyPolicy");Z("1.3.6.1.4.1.311.60.2.1.2","jurisdictionST");Z("1.3.6.1.4.1.311.60.2.1.3","jurisdictionC");Z("1.3.6.1.4.1.11129.2.4.2","timestampList");Z("1.3.6.1.5.5.7.1.1","authorityInfoAccess");Z("1.3.6.1.5.5.7.3.1","serverAuth");Z("1.3.6.1.5.5.7.3.2","clientAuth");Z("1.3.6.1.5.5.7.3.3","codeSigning");Z("1.3.6.1.5.5.7.3.4","emailProtection");Z("1.3.6.1.5.5.7.3.8","timeStamping");Z("1.3.6.1.5.5.7.48.1","authorityInfoAccessOcsp");Z("1.3.6.1.5.5.7.48.2","authorityInfoAccessIssuers")});var Z0=se((YK,Q0)=>{"use strict";(function(r){"use strict";var e=function(m){var b,x=new Float64Array(16);if(m)for(b=0;b<m.length;b++)x[b]=m[b];return x},t=function(){throw new Error("no PRNG")},s=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var i=e(),o=e([1]),a=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),u=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),f=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),h=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function y(m,b,x,l){m[b]=x>>24&255,m[b+1]=x>>16&255,m[b+2]=x>>8&255,m[b+3]=x&255,m[b+4]=l>>24&255,m[b+5]=l>>16&255,m[b+6]=l>>8&255,m[b+7]=l&255}function v(m,b,x,l,w){var k,N=0;for(k=0;k<w;k++)N|=m[b+k]^x[l+k];return(1&N-1>>>8)-1}function S(m,b,x,l){return v(m,b,x,l,16)}function C(m,b,x,l){return v(m,b,x,l,32)}function O(m,b,x,l){for(var w=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,k=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,G=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,ue=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Le=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,Se=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,Pt=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,Re=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,rt=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,nt=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,pt=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,lt=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,it=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,dt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,ot=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Pe=w,qe=k,_e=N,Be=G,Oe=ue,ve=Le,U=Se,j=Pt,re=Re,W=rt,X=nt,ae=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,wt=0;wt<20;wt+=2)E=Pe+Xe|0,Oe^=E<<7|E>>>25,E=Oe+Pe|0,re^=E<<9|E>>>23,E=re+Oe|0,Xe^=E<<13|E>>>19,E=Xe+re|0,Pe^=E<<18|E>>>14,E=ve+qe|0,W^=E<<7|E>>>25,E=W+ve|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,ve^=E<<18|E>>>14,E=X+U|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,U^=E<<13|E>>>19,E=U+_e|0,X^=E<<18|E>>>14,E=gt+ae|0,Be^=E<<7|E>>>25,E=Be+gt|0,j^=E<<9|E>>>23,E=j+Be|0,ae^=E<<13|E>>>19,E=ae+j|0,gt^=E<<18|E>>>14,E=Pe+Be|0,qe^=E<<7|E>>>25,E=qe+Pe|0,_e^=E<<9|E>>>23,E=_e+qe|0,Be^=E<<13|E>>>19,E=Be+_e|0,Pe^=E<<18|E>>>14,E=ve+Oe|0,U^=E<<7|E>>>25,E=U+ve|0,j^=E<<9|E>>>23,E=j+U|0,Oe^=E<<13|E>>>19,E=Oe+j|0,ve^=E<<18|E>>>14,E=X+W|0,ae^=E<<7|E>>>25,E=ae+X|0,re^=E<<9|E>>>23,E=re+ae|0,W^=E<<13|E>>>19,E=W+re|0,X^=E<<18|E>>>14,E=gt+yt|0,Xe^=E<<7|E>>>25,E=Xe+gt|0,mt^=E<<9|E>>>23,E=mt+Xe|0,yt^=E<<13|E>>>19,E=yt+mt|0,gt^=E<<18|E>>>14;Pe=Pe+w|0,qe=qe+k|0,_e=_e+N|0,Be=Be+G|0,Oe=Oe+ue|0,ve=ve+Le|0,U=U+Se|0,j=j+Pt|0,re=re+Re|0,W=W+rt|0,X=X+nt|0,ae=ae+pt|0,Xe=Xe+lt|0,mt=mt+it|0,yt=yt+dt|0,gt=gt+ot|0,m[0]=Pe>>>0&255,m[1]=Pe>>>8&255,m[2]=Pe>>>16&255,m[3]=Pe>>>24&255,m[4]=qe>>>0&255,m[5]=qe>>>8&255,m[6]=qe>>>16&255,m[7]=qe>>>24&255,m[8]=_e>>>0&255,m[9]=_e>>>8&255,m[10]=_e>>>16&255,m[11]=_e>>>24&255,m[12]=Be>>>0&255,m[13]=Be>>>8&255,m[14]=Be>>>16&255,m[15]=Be>>>24&255,m[16]=Oe>>>0&255,m[17]=Oe>>>8&255,m[18]=Oe>>>16&255,m[19]=Oe>>>24&255,m[20]=ve>>>0&255,m[21]=ve>>>8&255,m[22]=ve>>>16&255,m[23]=ve>>>24&255,m[24]=U>>>0&255,m[25]=U>>>8&255,m[26]=U>>>16&255,m[27]=U>>>24&255,m[28]=j>>>0&255,m[29]=j>>>8&255,m[30]=j>>>16&255,m[31]=j>>>24&255,m[32]=re>>>0&255,m[33]=re>>>8&255,m[34]=re>>>16&255,m[35]=re>>>24&255,m[36]=W>>>0&255,m[37]=W>>>8&255,m[38]=W>>>16&255,m[39]=W>>>24&255,m[40]=X>>>0&255,m[41]=X>>>8&255,m[42]=X>>>16&255,m[43]=X>>>24&255,m[44]=ae>>>0&255,m[45]=ae>>>8&255,m[46]=ae>>>16&255,m[47]=ae>>>24&255,m[48]=Xe>>>0&255,m[49]=Xe>>>8&255,m[50]=Xe>>>16&255,m[51]=Xe>>>24&255,m[52]=mt>>>0&255,m[53]=mt>>>8&255,m[54]=mt>>>16&255,m[55]=mt>>>24&255,m[56]=yt>>>0&255,m[57]=yt>>>8&255,m[58]=yt>>>16&255,m[59]=yt>>>24&255,m[60]=gt>>>0&255,m[61]=gt>>>8&255,m[62]=gt>>>16&255,m[63]=gt>>>24&255}function K(m,b,x,l){for(var w=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,k=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,G=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,ue=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Le=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,Se=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,Pt=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,Re=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,rt=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,nt=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,pt=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,lt=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,it=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,dt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,ot=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Pe=w,qe=k,_e=N,Be=G,Oe=ue,ve=Le,U=Se,j=Pt,re=Re,W=rt,X=nt,ae=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,wt=0;wt<20;wt+=2)E=Pe+Xe|0,Oe^=E<<7|E>>>25,E=Oe+Pe|0,re^=E<<9|E>>>23,E=re+Oe|0,Xe^=E<<13|E>>>19,E=Xe+re|0,Pe^=E<<18|E>>>14,E=ve+qe|0,W^=E<<7|E>>>25,E=W+ve|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,ve^=E<<18|E>>>14,E=X+U|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,U^=E<<13|E>>>19,E=U+_e|0,X^=E<<18|E>>>14,E=gt+ae|0,Be^=E<<7|E>>>25,E=Be+gt|0,j^=E<<9|E>>>23,E=j+Be|0,ae^=E<<13|E>>>19,E=ae+j|0,gt^=E<<18|E>>>14,E=Pe+Be|0,qe^=E<<7|E>>>25,E=qe+Pe|0,_e^=E<<9|E>>>23,E=_e+qe|0,Be^=E<<13|E>>>19,E=Be+_e|0,Pe^=E<<18|E>>>14,E=ve+Oe|0,U^=E<<7|E>>>25,E=U+ve|0,j^=E<<9|E>>>23,E=j+U|0,Oe^=E<<13|E>>>19,E=Oe+j|0,ve^=E<<18|E>>>14,E=X+W|0,ae^=E<<7|E>>>25,E=ae+X|0,re^=E<<9|E>>>23,E=re+ae|0,W^=E<<13|E>>>19,E=W+re|0,X^=E<<18|E>>>14,E=gt+yt|0,Xe^=E<<7|E>>>25,E=Xe+gt|0,mt^=E<<9|E>>>23,E=mt+Xe|0,yt^=E<<13|E>>>19,E=yt+mt|0,gt^=E<<18|E>>>14;m[0]=Pe>>>0&255,m[1]=Pe>>>8&255,m[2]=Pe>>>16&255,m[3]=Pe>>>24&255,m[4]=ve>>>0&255,m[5]=ve>>>8&255,m[6]=ve>>>16&255,m[7]=ve>>>24&255,m[8]=X>>>0&255,m[9]=X>>>8&255,m[10]=X>>>16&255,m[11]=X>>>24&255,m[12]=gt>>>0&255,m[13]=gt>>>8&255,m[14]=gt>>>16&255,m[15]=gt>>>24&255,m[16]=U>>>0&255,m[17]=U>>>8&255,m[18]=U>>>16&255,m[19]=U>>>24&255,m[20]=j>>>0&255,m[21]=j>>>8&255,m[22]=j>>>16&255,m[23]=j>>>24&255,m[24]=re>>>0&255,m[25]=re>>>8&255,m[26]=re>>>16&255,m[27]=re>>>24&255,m[28]=W>>>0&255,m[29]=W>>>8&255,m[30]=W>>>16&255,m[31]=W>>>24&255}function z(m,b,x,l){O(m,b,x,l)}function Q(m,b,x,l){K(m,b,x,l)}var oe=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function te(m,b,x,l,w,k,N){var G=new Uint8Array(16),ue=new Uint8Array(64),Le,Se;for(Se=0;Se<16;Se++)G[Se]=0;for(Se=0;Se<8;Se++)G[Se]=k[Se];for(;w>=64;){for(z(ue,G,N,oe),Se=0;Se<64;Se++)m[b+Se]=x[l+Se]^ue[Se];for(Le=1,Se=8;Se<16;Se++)Le=Le+(G[Se]&255)|0,G[Se]=Le&255,Le>>>=8;w-=64,b+=64,l+=64}if(w>0)for(z(ue,G,N,oe),Se=0;Se<w;Se++)m[b+Se]=x[l+Se]^ue[Se];return 0}function Ee(m,b,x,l,w){var k=new Uint8Array(16),N=new Uint8Array(64),G,ue;for(ue=0;ue<16;ue++)k[ue]=0;for(ue=0;ue<8;ue++)k[ue]=l[ue];for(;x>=64;){for(z(N,k,w,oe),ue=0;ue<64;ue++)m[b+ue]=N[ue];for(G=1,ue=8;ue<16;ue++)G=G+(k[ue]&255)|0,k[ue]=G&255,G>>>=8;x-=64,b+=64}if(x>0)for(z(N,k,w,oe),ue=0;ue<x;ue++)m[b+ue]=N[ue];return 0}function ge(m,b,x,l,w){var k=new Uint8Array(32);Q(k,l,w,oe);for(var N=new Uint8Array(8),G=0;G<8;G++)N[G]=l[G+16];return Ee(m,b,x,N,k)}function Y(m,b,x,l,w,k,N){var G=new Uint8Array(32);Q(G,k,N,oe);for(var ue=new Uint8Array(8),Le=0;Le<8;Le++)ue[Le]=k[Le+16];return te(m,b,x,l,w,ue,G)}var Ze=function(m){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var b,x,l,w,k,N,G,ue;b=m[0]&255|(m[1]&255)<<8,this.r[0]=b&8191,x=m[2]&255|(m[3]&255)<<8,this.r[1]=(b>>>13|x<<3)&8191,l=m[4]&255|(m[5]&255)<<8,this.r[2]=(x>>>10|l<<6)&7939,w=m[6]&255|(m[7]&255)<<8,this.r[3]=(l>>>7|w<<9)&8191,k=m[8]&255|(m[9]&255)<<8,this.r[4]=(w>>>4|k<<12)&255,this.r[5]=k>>>1&8190,N=m[10]&255|(m[11]&255)<<8,this.r[6]=(k>>>14|N<<2)&8191,G=m[12]&255|(m[13]&255)<<8,this.r[7]=(N>>>11|G<<5)&8065,ue=m[14]&255|(m[15]&255)<<8,this.r[8]=(G>>>8|ue<<8)&8191,this.r[9]=ue>>>5&127,this.pad[0]=m[16]&255|(m[17]&255)<<8,this.pad[1]=m[18]&255|(m[19]&255)<<8,this.pad[2]=m[20]&255|(m[21]&255)<<8,this.pad[3]=m[22]&255|(m[23]&255)<<8,this.pad[4]=m[24]&255|(m[25]&255)<<8,this.pad[5]=m[26]&255|(m[27]&255)<<8,this.pad[6]=m[28]&255|(m[29]&255)<<8,this.pad[7]=m[30]&255|(m[31]&255)<<8};Ze.prototype.blocks=function(m,b,x){for(var l=this.fin?0:2048,w,k,N,G,ue,Le,Se,Pt,Re,rt,nt,pt,lt,it,dt,ot,Pe,qe,_e,Be=this.h[0],Oe=this.h[1],ve=this.h[2],U=this.h[3],j=this.h[4],re=this.h[5],W=this.h[6],X=this.h[7],ae=this.h[8],Xe=this.h[9],mt=this.r[0],yt=this.r[1],gt=this.r[2],E=this.r[3],wt=this.r[4],Bt=this.r[5],Nt=this.r[6],bt=this.r[7],At=this.r[8],It=this.r[9];x>=16;)w=m[b+0]&255|(m[b+1]&255)<<8,Be+=w&8191,k=m[b+2]&255|(m[b+3]&255)<<8,Oe+=(w>>>13|k<<3)&8191,N=m[b+4]&255|(m[b+5]&255)<<8,ve+=(k>>>10|N<<6)&8191,G=m[b+6]&255|(m[b+7]&255)<<8,U+=(N>>>7|G<<9)&8191,ue=m[b+8]&255|(m[b+9]&255)<<8,j+=(G>>>4|ue<<12)&8191,re+=ue>>>1&8191,Le=m[b+10]&255|(m[b+11]&255)<<8,W+=(ue>>>14|Le<<2)&8191,Se=m[b+12]&255|(m[b+13]&255)<<8,X+=(Le>>>11|Se<<5)&8191,Pt=m[b+14]&255|(m[b+15]&255)<<8,ae+=(Se>>>8|Pt<<8)&8191,Xe+=Pt>>>5|l,Re=0,rt=Re,rt+=Be*mt,rt+=Oe*(5*It),rt+=ve*(5*At),rt+=U*(5*bt),rt+=j*(5*Nt),Re=rt>>>13,rt&=8191,rt+=re*(5*Bt),rt+=W*(5*wt),rt+=X*(5*E),rt+=ae*(5*gt),rt+=Xe*(5*yt),Re+=rt>>>13,rt&=8191,nt=Re,nt+=Be*yt,nt+=Oe*mt,nt+=ve*(5*It),nt+=U*(5*At),nt+=j*(5*bt),Re=nt>>>13,nt&=8191,nt+=re*(5*Nt),nt+=W*(5*Bt),nt+=X*(5*wt),nt+=ae*(5*E),nt+=Xe*(5*gt),Re+=nt>>>13,nt&=8191,pt=Re,pt+=Be*gt,pt+=Oe*yt,pt+=ve*mt,pt+=U*(5*It),pt+=j*(5*At),Re=pt>>>13,pt&=8191,pt+=re*(5*bt),pt+=W*(5*Nt),pt+=X*(5*Bt),pt+=ae*(5*wt),pt+=Xe*(5*E),Re+=pt>>>13,pt&=8191,lt=Re,lt+=Be*E,lt+=Oe*gt,lt+=ve*yt,lt+=U*mt,lt+=j*(5*It),Re=lt>>>13,lt&=8191,lt+=re*(5*At),lt+=W*(5*bt),lt+=X*(5*Nt),lt+=ae*(5*Bt),lt+=Xe*(5*wt),Re+=lt>>>13,lt&=8191,it=Re,it+=Be*wt,it+=Oe*E,it+=ve*gt,it+=U*yt,it+=j*mt,Re=it>>>13,it&=8191,it+=re*(5*It),it+=W*(5*At),it+=X*(5*bt),it+=ae*(5*Nt),it+=Xe*(5*Bt),Re+=it>>>13,it&=8191,dt=Re,dt+=Be*Bt,dt+=Oe*wt,dt+=ve*E,dt+=U*gt,dt+=j*yt,Re=dt>>>13,dt&=8191,dt+=re*mt,dt+=W*(5*It),dt+=X*(5*At),dt+=ae*(5*bt),dt+=Xe*(5*Nt),Re+=dt>>>13,dt&=8191,ot=Re,ot+=Be*Nt,ot+=Oe*Bt,ot+=ve*wt,ot+=U*E,ot+=j*gt,Re=ot>>>13,ot&=8191,ot+=re*yt,ot+=W*mt,ot+=X*(5*It),ot+=ae*(5*At),ot+=Xe*(5*bt),Re+=ot>>>13,ot&=8191,Pe=Re,Pe+=Be*bt,Pe+=Oe*Nt,Pe+=ve*Bt,Pe+=U*wt,Pe+=j*E,Re=Pe>>>13,Pe&=8191,Pe+=re*gt,Pe+=W*yt,Pe+=X*mt,Pe+=ae*(5*It),Pe+=Xe*(5*At),Re+=Pe>>>13,Pe&=8191,qe=Re,qe+=Be*At,qe+=Oe*bt,qe+=ve*Nt,qe+=U*Bt,qe+=j*wt,Re=qe>>>13,qe&=8191,qe+=re*E,qe+=W*gt,qe+=X*yt,qe+=ae*mt,qe+=Xe*(5*It),Re+=qe>>>13,qe&=8191,_e=Re,_e+=Be*It,_e+=Oe*At,_e+=ve*bt,_e+=U*Nt,_e+=j*Bt,Re=_e>>>13,_e&=8191,_e+=re*wt,_e+=W*E,_e+=X*gt,_e+=ae*yt,_e+=Xe*mt,Re+=_e>>>13,_e&=8191,Re=(Re<<2)+Re|0,Re=Re+rt|0,rt=Re&8191,Re=Re>>>13,nt+=Re,Be=rt,Oe=nt,ve=pt,U=lt,j=it,re=dt,W=ot,X=Pe,ae=qe,Xe=_e,b+=16,x-=16;this.h[0]=Be,this.h[1]=Oe,this.h[2]=ve,this.h[3]=U,this.h[4]=j,this.h[5]=re,this.h[6]=W,this.h[7]=X,this.h[8]=ae,this.h[9]=Xe},Ze.prototype.finish=function(m,b){var x=new Uint16Array(10),l,w,k,N;if(this.leftover){for(N=this.leftover,this.buffer[N++]=1;N<16;N++)this.buffer[N]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(l=this.h[1]>>>13,this.h[1]&=8191,N=2;N<10;N++)this.h[N]+=l,l=this.h[N]>>>13,this.h[N]&=8191;for(this.h[0]+=l*5,l=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=l,l=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=l,x[0]=this.h[0]+5,l=x[0]>>>13,x[0]&=8191,N=1;N<10;N++)x[N]=this.h[N]+l,l=x[N]>>>13,x[N]&=8191;for(x[9]-=8192,w=(l^1)-1,N=0;N<10;N++)x[N]&=w;for(w=~w,N=0;N<10;N++)this.h[N]=this.h[N]&w|x[N];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,k=this.h[0]+this.pad[0],this.h[0]=k&65535,N=1;N<8;N++)k=(this.h[N]+this.pad[N]|0)+(k>>>16)|0,this.h[N]=k&65535;m[b+0]=this.h[0]>>>0&255,m[b+1]=this.h[0]>>>8&255,m[b+2]=this.h[1]>>>0&255,m[b+3]=this.h[1]>>>8&255,m[b+4]=this.h[2]>>>0&255,m[b+5]=this.h[2]>>>8&255,m[b+6]=this.h[3]>>>0&255,m[b+7]=this.h[3]>>>8&255,m[b+8]=this.h[4]>>>0&255,m[b+9]=this.h[4]>>>8&255,m[b+10]=this.h[5]>>>0&255,m[b+11]=this.h[5]>>>8&255,m[b+12]=this.h[6]>>>0&255,m[b+13]=this.h[6]>>>8&255,m[b+14]=this.h[7]>>>0&255,m[b+15]=this.h[7]>>>8&255},Ze.prototype.update=function(m,b,x){var l,w;if(this.leftover){for(w=16-this.leftover,w>x&&(w=x),l=0;l<w;l++)this.buffer[this.leftover+l]=m[b+l];if(x-=w,b+=w,this.leftover+=w,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(x>=16&&(w=x-x%16,this.blocks(m,b,w),b+=w,x-=w),x){for(l=0;l<x;l++)this.buffer[this.leftover+l]=m[b+l];this.leftover+=x}};function vt(m,b,x,l,w,k){var N=new Ze(k);return N.update(x,l,w),N.finish(m,b),0}function Fe(m,b,x,l,w,k){var N=new Uint8Array(16);return vt(N,0,x,l,w,k),S(m,b,N,0)}function $(m,b,x,l,w){var k;if(x<32)return-1;for(Y(m,0,b,0,x,l,w),vt(m,16,m,32,x-32,m),k=0;k<16;k++)m[k]=0;return 0}function V(m,b,x,l,w){var k,N=new Uint8Array(32);if(x<32||(ge(N,0,32,l,w),Fe(b,16,b,32,x-32,N)!==0))return-1;for(Y(m,0,b,0,x,l,w),k=0;k<32;k++)m[k]=0;return 0}function H(m,b){var x;for(x=0;x<16;x++)m[x]=b[x]|0}function me(m){var b,x,l=1;for(b=0;b<16;b++)x=m[b]+l+65535,l=Math.floor(x/65536),m[b]=x-l*65536;m[0]+=l-1+37*(l-1)}function Te(m,b,x){for(var l,w=~(x-1),k=0;k<16;k++)l=w&(m[k]^b[k]),m[k]^=l,b[k]^=l}function ne(m,b){var x,l,w,k=e(),N=e();for(x=0;x<16;x++)N[x]=b[x];for(me(N),me(N),me(N),l=0;l<2;l++){for(k[0]=N[0]-65517,x=1;x<15;x++)k[x]=N[x]-65535-(k[x-1]>>16&1),k[x-1]&=65535;k[15]=N[15]-32767-(k[14]>>16&1),w=k[15]>>16&1,k[14]&=65535,Te(N,k,1-w)}for(x=0;x<16;x++)m[2*x]=N[x]&255,m[2*x+1]=N[x]>>8}function T(m,b){var x=new Uint8Array(32),l=new Uint8Array(32);return ne(x,m),ne(l,b),C(x,0,l,0)}function R(m){var b=new Uint8Array(32);return ne(b,m),b[0]&1}function F(m,b){var x;for(x=0;x<16;x++)m[x]=b[2*x]+(b[2*x+1]<<8);m[15]&=32767}function I(m,b,x){for(var l=0;l<16;l++)m[l]=b[l]+x[l]}function L(m,b,x){for(var l=0;l<16;l++)m[l]=b[l]-x[l]}function ce(m,b,x){var l,w,k=0,N=0,G=0,ue=0,Le=0,Se=0,Pt=0,Re=0,rt=0,nt=0,pt=0,lt=0,it=0,dt=0,ot=0,Pe=0,qe=0,_e=0,Be=0,Oe=0,ve=0,U=0,j=0,re=0,W=0,X=0,ae=0,Xe=0,mt=0,yt=0,gt=0,E=x[0],wt=x[1],Bt=x[2],Nt=x[3],bt=x[4],At=x[5],It=x[6],cr=x[7],Mt=x[8],rr=x[9],sr=x[10],nr=x[11],gr=x[12],jr=x[13],Hr=x[14],Fr=x[15];l=b[0],k+=l*E,N+=l*wt,G+=l*Bt,ue+=l*Nt,Le+=l*bt,Se+=l*At,Pt+=l*It,Re+=l*cr,rt+=l*Mt,nt+=l*rr,pt+=l*sr,lt+=l*nr,it+=l*gr,dt+=l*jr,ot+=l*Hr,Pe+=l*Fr,l=b[1],N+=l*E,G+=l*wt,ue+=l*Bt,Le+=l*Nt,Se+=l*bt,Pt+=l*At,Re+=l*It,rt+=l*cr,nt+=l*Mt,pt+=l*rr,lt+=l*sr,it+=l*nr,dt+=l*gr,ot+=l*jr,Pe+=l*Hr,qe+=l*Fr,l=b[2],G+=l*E,ue+=l*wt,Le+=l*Bt,Se+=l*Nt,Pt+=l*bt,Re+=l*At,rt+=l*It,nt+=l*cr,pt+=l*Mt,lt+=l*rr,it+=l*sr,dt+=l*nr,ot+=l*gr,Pe+=l*jr,qe+=l*Hr,_e+=l*Fr,l=b[3],ue+=l*E,Le+=l*wt,Se+=l*Bt,Pt+=l*Nt,Re+=l*bt,rt+=l*At,nt+=l*It,pt+=l*cr,lt+=l*Mt,it+=l*rr,dt+=l*sr,ot+=l*nr,Pe+=l*gr,qe+=l*jr,_e+=l*Hr,Be+=l*Fr,l=b[4],Le+=l*E,Se+=l*wt,Pt+=l*Bt,Re+=l*Nt,rt+=l*bt,nt+=l*At,pt+=l*It,lt+=l*cr,it+=l*Mt,dt+=l*rr,ot+=l*sr,Pe+=l*nr,qe+=l*gr,_e+=l*jr,Be+=l*Hr,Oe+=l*Fr,l=b[5],Se+=l*E,Pt+=l*wt,Re+=l*Bt,rt+=l*Nt,nt+=l*bt,pt+=l*At,lt+=l*It,it+=l*cr,dt+=l*Mt,ot+=l*rr,Pe+=l*sr,qe+=l*nr,_e+=l*gr,Be+=l*jr,Oe+=l*Hr,ve+=l*Fr,l=b[6],Pt+=l*E,Re+=l*wt,rt+=l*Bt,nt+=l*Nt,pt+=l*bt,lt+=l*At,it+=l*It,dt+=l*cr,ot+=l*Mt,Pe+=l*rr,qe+=l*sr,_e+=l*nr,Be+=l*gr,Oe+=l*jr,ve+=l*Hr,U+=l*Fr,l=b[7],Re+=l*E,rt+=l*wt,nt+=l*Bt,pt+=l*Nt,lt+=l*bt,it+=l*At,dt+=l*It,ot+=l*cr,Pe+=l*Mt,qe+=l*rr,_e+=l*sr,Be+=l*nr,Oe+=l*gr,ve+=l*jr,U+=l*Hr,j+=l*Fr,l=b[8],rt+=l*E,nt+=l*wt,pt+=l*Bt,lt+=l*Nt,it+=l*bt,dt+=l*At,ot+=l*It,Pe+=l*cr,qe+=l*Mt,_e+=l*rr,Be+=l*sr,Oe+=l*nr,ve+=l*gr,U+=l*jr,j+=l*Hr,re+=l*Fr,l=b[9],nt+=l*E,pt+=l*wt,lt+=l*Bt,it+=l*Nt,dt+=l*bt,ot+=l*At,Pe+=l*It,qe+=l*cr,_e+=l*Mt,Be+=l*rr,Oe+=l*sr,ve+=l*nr,U+=l*gr,j+=l*jr,re+=l*Hr,W+=l*Fr,l=b[10],pt+=l*E,lt+=l*wt,it+=l*Bt,dt+=l*Nt,ot+=l*bt,Pe+=l*At,qe+=l*It,_e+=l*cr,Be+=l*Mt,Oe+=l*rr,ve+=l*sr,U+=l*nr,j+=l*gr,re+=l*jr,W+=l*Hr,X+=l*Fr,l=b[11],lt+=l*E,it+=l*wt,dt+=l*Bt,ot+=l*Nt,Pe+=l*bt,qe+=l*At,_e+=l*It,Be+=l*cr,Oe+=l*Mt,ve+=l*rr,U+=l*sr,j+=l*nr,re+=l*gr,W+=l*jr,X+=l*Hr,ae+=l*Fr,l=b[12],it+=l*E,dt+=l*wt,ot+=l*Bt,Pe+=l*Nt,qe+=l*bt,_e+=l*At,Be+=l*It,Oe+=l*cr,ve+=l*Mt,U+=l*rr,j+=l*sr,re+=l*nr,W+=l*gr,X+=l*jr,ae+=l*Hr,Xe+=l*Fr,l=b[13],dt+=l*E,ot+=l*wt,Pe+=l*Bt,qe+=l*Nt,_e+=l*bt,Be+=l*At,Oe+=l*It,ve+=l*cr,U+=l*Mt,j+=l*rr,re+=l*sr,W+=l*nr,X+=l*gr,ae+=l*jr,Xe+=l*Hr,mt+=l*Fr,l=b[14],ot+=l*E,Pe+=l*wt,qe+=l*Bt,_e+=l*Nt,Be+=l*bt,Oe+=l*At,ve+=l*It,U+=l*cr,j+=l*Mt,re+=l*rr,W+=l*sr,X+=l*nr,ae+=l*gr,Xe+=l*jr,mt+=l*Hr,yt+=l*Fr,l=b[15],Pe+=l*E,qe+=l*wt,_e+=l*Bt,Be+=l*Nt,Oe+=l*bt,ve+=l*At,U+=l*It,j+=l*cr,re+=l*Mt,W+=l*rr,X+=l*sr,ae+=l*nr,Xe+=l*gr,mt+=l*jr,yt+=l*Hr,gt+=l*Fr,k+=38*qe,N+=38*_e,G+=38*Be,ue+=38*Oe,Le+=38*ve,Se+=38*U,Pt+=38*j,Re+=38*re,rt+=38*W,nt+=38*X,pt+=38*ae,lt+=38*Xe,it+=38*mt,dt+=38*yt,ot+=38*gt,w=1,l=k+w+65535,w=Math.floor(l/65536),k=l-w*65536,l=N+w+65535,w=Math.floor(l/65536),N=l-w*65536,l=G+w+65535,w=Math.floor(l/65536),G=l-w*65536,l=ue+w+65535,w=Math.floor(l/65536),ue=l-w*65536,l=Le+w+65535,w=Math.floor(l/65536),Le=l-w*65536,l=Se+w+65535,w=Math.floor(l/65536),Se=l-w*65536,l=Pt+w+65535,w=Math.floor(l/65536),Pt=l-w*65536,l=Re+w+65535,w=Math.floor(l/65536),Re=l-w*65536,l=rt+w+65535,w=Math.floor(l/65536),rt=l-w*65536,l=nt+w+65535,w=Math.floor(l/65536),nt=l-w*65536,l=pt+w+65535,w=Math.floor(l/65536),pt=l-w*65536,l=lt+w+65535,w=Math.floor(l/65536),lt=l-w*65536,l=it+w+65535,w=Math.floor(l/65536),it=l-w*65536,l=dt+w+65535,w=Math.floor(l/65536),dt=l-w*65536,l=ot+w+65535,w=Math.floor(l/65536),ot=l-w*65536,l=Pe+w+65535,w=Math.floor(l/65536),Pe=l-w*65536,k+=w-1+37*(w-1),w=1,l=k+w+65535,w=Math.floor(l/65536),k=l-w*65536,l=N+w+65535,w=Math.floor(l/65536),N=l-w*65536,l=G+w+65535,w=Math.floor(l/65536),G=l-w*65536,l=ue+w+65535,w=Math.floor(l/65536),ue=l-w*65536,l=Le+w+65535,w=Math.floor(l/65536),Le=l-w*65536,l=Se+w+65535,w=Math.floor(l/65536),Se=l-w*65536,l=Pt+w+65535,w=Math.floor(l/65536),Pt=l-w*65536,l=Re+w+65535,w=Math.floor(l/65536),Re=l-w*65536,l=rt+w+65535,w=Math.floor(l/65536),rt=l-w*65536,l=nt+w+65535,w=Math.floor(l/65536),nt=l-w*65536,l=pt+w+65535,w=Math.floor(l/65536),pt=l-w*65536,l=lt+w+65535,w=Math.floor(l/65536),lt=l-w*65536,l=it+w+65535,w=Math.floor(l/65536),it=l-w*65536,l=dt+w+65535,w=Math.floor(l/65536),dt=l-w*65536,l=ot+w+65535,w=Math.floor(l/65536),ot=l-w*65536,l=Pe+w+65535,w=Math.floor(l/65536),Pe=l-w*65536,k+=w-1+37*(w-1),m[0]=k,m[1]=N,m[2]=G,m[3]=ue,m[4]=Le,m[5]=Se,m[6]=Pt,m[7]=Re,m[8]=rt,m[9]=nt,m[10]=pt,m[11]=lt,m[12]=it,m[13]=dt,m[14]=ot,m[15]=Pe}function he(m,b){ce(m,b,b)}function ct(m,b){var x=e(),l;for(l=0;l<16;l++)x[l]=b[l];for(l=253;l>=0;l--)he(x,x),l!==2&&l!==4&&ce(x,x,b);for(l=0;l<16;l++)m[l]=x[l]}function xt(m,b){var x=e(),l;for(l=0;l<16;l++)x[l]=b[l];for(l=250;l>=0;l--)he(x,x),l!==1&&ce(x,x,b);for(l=0;l<16;l++)m[l]=x[l]}function Ot(m,b,x){var l=new Uint8Array(32),w=new Float64Array(80),k,N,G=e(),ue=e(),Le=e(),Se=e(),Pt=e(),Re=e();for(N=0;N<31;N++)l[N]=b[N];for(l[31]=b[31]&127|64,l[0]&=248,F(w,x),N=0;N<16;N++)ue[N]=w[N],Se[N]=G[N]=Le[N]=0;for(G[0]=Se[0]=1,N=254;N>=0;--N)k=l[N>>>3]>>>(N&7)&1,Te(G,ue,k),Te(Le,Se,k),I(Pt,G,Le),L(G,G,Le),I(Le,ue,Se),L(ue,ue,Se),he(Se,Pt),he(Re,G),ce(G,Le,G),ce(Le,ue,Pt),I(Pt,G,Le),L(G,G,Le),he(ue,G),L(Le,Se,Re),ce(G,Le,a),I(G,G,Se),ce(Le,Le,G),ce(G,Se,Re),ce(Se,ue,w),he(ue,Pt),Te(G,ue,k),Te(Le,Se,k);for(N=0;N<16;N++)w[N+16]=G[N],w[N+32]=Le[N],w[N+48]=ue[N],w[N+64]=Se[N];var rt=w.subarray(32),nt=w.subarray(16);return ct(rt,rt),ce(nt,nt,rt),ne(m,nt),0}function _t(m,b){return Ot(m,b,n)}function Dt(m,b){return t(b,32),_t(m,b)}function Bs(m,b,x){var l=new Uint8Array(32);return Ot(l,x,b),Q(m,s,l,oe)}var Ns=$,Ca=V;function Rx(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ns(m,b,x,l,N)}function bf(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ca(m,b,x,l,N)}var vf=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function wf(m,b,x,l){for(var w=new Int32Array(16),k=new Int32Array(16),N,G,ue,Le,Se,Pt,Re,rt,nt,pt,lt,it,dt,ot,Pe,qe,_e,Be,Oe,ve,U,j,re,W,X,ae,Xe=m[0],mt=m[1],yt=m[2],gt=m[3],E=m[4],wt=m[5],Bt=m[6],Nt=m[7],bt=b[0],At=b[1],It=b[2],cr=b[3],Mt=b[4],rr=b[5],sr=b[6],nr=b[7],gr=0;l>=128;){for(Oe=0;Oe<16;Oe++)ve=8*Oe+gr,w[Oe]=x[ve+0]<<24|x[ve+1]<<16|x[ve+2]<<8|x[ve+3],k[Oe]=x[ve+4]<<24|x[ve+5]<<16|x[ve+6]<<8|x[ve+7];for(Oe=0;Oe<80;Oe++)if(N=Xe,G=mt,ue=yt,Le=gt,Se=E,Pt=wt,Re=Bt,rt=Nt,nt=bt,pt=At,lt=It,it=cr,dt=Mt,ot=rr,Pe=sr,qe=nr,U=Nt,j=nr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=(E>>>14|Mt<<18)^(E>>>18|Mt<<14)^(Mt>>>9|E<<23),j=(Mt>>>14|E<<18)^(Mt>>>18|E<<14)^(E>>>9|Mt<<23),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=E&wt^~E&Bt,j=Mt&rr^~Mt&sr,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=vf[Oe*2],j=vf[Oe*2+1],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=w[Oe%16],j=k[Oe%16],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,_e=X&65535|ae<<16,Be=re&65535|W<<16,U=_e,j=Be,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=(Xe>>>28|bt<<4)^(bt>>>2|Xe<<30)^(bt>>>7|Xe<<25),j=(bt>>>28|Xe<<4)^(Xe>>>2|bt<<30)^(Xe>>>7|bt<<25),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=Xe&mt^Xe&yt^mt&yt,j=bt&At^bt&It^At&It,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,rt=X&65535|ae<<16,qe=re&65535|W<<16,U=Le,j=it,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=_e,j=Be,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,Le=X&65535|ae<<16,it=re&65535|W<<16,mt=N,yt=G,gt=ue,E=Le,wt=Se,Bt=Pt,Nt=Re,Xe=rt,At=nt,It=pt,cr=lt,Mt=it,rr=dt,sr=ot,nr=Pe,bt=qe,Oe%16===15)for(ve=0;ve<16;ve++)U=w[ve],j=k[ve],re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=w[(ve+9)%16],j=k[(ve+9)%16],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,_e=w[(ve+1)%16],Be=k[(ve+1)%16],U=(_e>>>1|Be<<31)^(_e>>>8|Be<<24)^_e>>>7,j=(Be>>>1|_e<<31)^(Be>>>8|_e<<24)^(Be>>>7|_e<<25),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,_e=w[(ve+14)%16],Be=k[(ve+14)%16],U=(_e>>>19|Be<<13)^(Be>>>29|_e<<3)^_e>>>6,j=(Be>>>19|_e<<13)^(_e>>>29|Be<<3)^(Be>>>6|_e<<26),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,w[ve]=X&65535|ae<<16,k[ve]=re&65535|W<<16;U=Xe,j=bt,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[0],j=b[0],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[0]=Xe=X&65535|ae<<16,b[0]=bt=re&65535|W<<16,U=mt,j=At,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[1],j=b[1],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[1]=mt=X&65535|ae<<16,b[1]=At=re&65535|W<<16,U=yt,j=It,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[2],j=b[2],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[2]=yt=X&65535|ae<<16,b[2]=It=re&65535|W<<16,U=gt,j=cr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[3],j=b[3],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[3]=gt=X&65535|ae<<16,b[3]=cr=re&65535|W<<16,U=E,j=Mt,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[4],j=b[4],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[4]=E=X&65535|ae<<16,b[4]=Mt=re&65535|W<<16,U=wt,j=rr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[5],j=b[5],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[5]=wt=X&65535|ae<<16,b[5]=rr=re&65535|W<<16,U=Bt,j=sr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[6],j=b[6],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[6]=Bt=X&65535|ae<<16,b[6]=sr=re&65535|W<<16,U=Nt,j=nr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[7],j=b[7],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[7]=Nt=X&65535|ae<<16,b[7]=nr=re&65535|W<<16,gr+=128,l-=128}return l}function Rn(m,b,x){var l=new Int32Array(8),w=new Int32Array(8),k=new Uint8Array(256),N,G=x;for(l[0]=1779033703,l[1]=3144134277,l[2]=1013904242,l[3]=2773480762,l[4]=1359893119,l[5]=2600822924,l[6]=528734635,l[7]=1541459225,w[0]=4089235720,w[1]=2227873595,w[2]=4271175723,w[3]=1595750129,w[4]=2917565137,w[5]=725511199,w[6]=4215389547,w[7]=327033209,wf(l,w,b,x),x%=128,N=0;N<x;N++)k[N]=b[G-x+N];for(k[x]=128,x=256-128*(x<112?1:0),k[x-9]=0,y(k,x-8,G/536870912|0,G<<3),wf(l,w,k,x),N=0;N<8;N++)y(m,8*N,l[N],w[N]);return 0}function Ta(m,b){var x=e(),l=e(),w=e(),k=e(),N=e(),G=e(),ue=e(),Le=e(),Se=e();L(x,m[1],m[0]),L(Se,b[1],b[0]),ce(x,x,Se),I(l,m[0],m[1]),I(Se,b[0],b[1]),ce(l,l,Se),ce(w,m[3],b[3]),ce(w,w,d),ce(k,m[2],b[2]),I(k,k,k),L(N,l,x),L(G,k,w),I(ue,k,w),I(Le,l,x),ce(m[0],N,G),ce(m[1],Le,ue),ce(m[2],ue,G),ce(m[3],N,Le)}function Sf(m,b,x){var l;for(l=0;l<4;l++)Te(m[l],b[l],x)}function Aa(m,b){var x=e(),l=e(),w=e();ct(w,b[2]),ce(x,b[0],w),ce(l,b[1],w),ne(m,l),m[31]^=R(x)<<7}function _f(m,b,x){var l,w;for(H(m[0],i),H(m[1],o),H(m[2],o),H(m[3],i),w=255;w>=0;--w)l=x[w/8|0]>>(w&7)&1,Sf(m,b,l),Ta(b,m),Ta(m,m),Sf(m,b,l)}function ud(m,b){var x=[e(),e(),e(),e()];H(x[0],u),H(x[1],f),H(x[2],o),ce(x[3],u,f),_f(m,x,b)}function Ef(m,b,x){var l=new Uint8Array(64),w=[e(),e(),e(),e()],k;for(x||t(b,32),Rn(l,b,32),l[0]&=248,l[31]&=127,l[31]|=64,ud(w,l),Aa(m,w),k=0;k<32;k++)b[k+32]=m[k];return 0}var fd=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function xi(m,b){var x,l,w,k;for(l=63;l>=32;--l){for(x=0,w=l-32,k=l-12;w<k;++w)b[w]+=x-16*b[l]*fd[w-(l-32)],x=Math.floor((b[w]+128)/256),b[w]-=x*256;b[w]+=x,b[l]=0}for(x=0,w=0;w<32;w++)b[w]+=x-(b[31]>>4)*fd[w],x=b[w]>>8,b[w]&=255;for(w=0;w<32;w++)b[w]-=x*fd[w];for(l=0;l<32;l++)b[l+1]+=b[l]>>8,m[l]=b[l]&255}function Cf(m){var b=new Float64Array(64),x;for(x=0;x<64;x++)b[x]=m[x];for(x=0;x<64;x++)m[x]=0;xi(m,b)}function n0(m,b,x,l){var w=new Uint8Array(64),k=new Uint8Array(64),N=new Uint8Array(64),G,ue,Le=new Float64Array(64),Se=[e(),e(),e(),e()];Rn(w,l,32),w[0]&=248,w[31]&=127,w[31]|=64;var Pt=x+64;for(G=0;G<x;G++)m[64+G]=b[G];for(G=0;G<32;G++)m[32+G]=w[32+G];for(Rn(N,m.subarray(32),x+32),Cf(N),ud(Se,N),Aa(m,Se),G=32;G<64;G++)m[G]=l[G];for(Rn(k,m,x+64),Cf(k),G=0;G<64;G++)Le[G]=0;for(G=0;G<32;G++)Le[G]=N[G];for(G=0;G<32;G++)for(ue=0;ue<32;ue++)Le[G+ue]+=k[G]*w[ue];return xi(m.subarray(32),Le),Pt}function kx(m,b){var x=e(),l=e(),w=e(),k=e(),N=e(),G=e(),ue=e();return H(m[2],o),F(m[1],b),he(w,m[1]),ce(k,w,c),L(w,w,m[2]),I(k,m[2],k),he(N,k),he(G,N),ce(ue,G,N),ce(x,ue,w),ce(x,x,k),xt(x,x),ce(x,x,w),ce(x,x,k),ce(x,x,k),ce(m[0],x,k),he(l,m[0]),ce(l,l,k),T(l,w)&&ce(m[0],m[0],h),he(l,m[0]),ce(l,l,k),T(l,w)?-1:(R(m[0])===b[31]>>7&&L(m[0],i,m[0]),ce(m[3],m[0],m[1]),0)}function Ia(m,b,x,l){var w,k=new Uint8Array(32),N=new Uint8Array(64),G=[e(),e(),e(),e()],ue=[e(),e(),e(),e()];if(x<64||kx(ue,l))return-1;for(w=0;w<x;w++)m[w]=b[w];for(w=0;w<32;w++)m[w+32]=l[w];if(Rn(N,m,x),Cf(N),_f(G,ue,N),ud(ue,b.subarray(32)),Ta(G,ue),Aa(k,G),x-=64,C(b,0,k,0)){for(w=0;w<x;w++)m[w]=0;return-1}for(w=0;w<x;w++)m[w]=b[w+64];return x}var P=32,D=24,q=32,de=16,Me=32,$t=32,Wt=32,ft=32,ye=32,Ce=D,ke=q,Ne=de,st=64,kt=32,jt=64,Xr=32,ld=64;r.lowlevel={crypto_core_hsalsa20:Q,crypto_stream_xor:Y,crypto_stream:ge,crypto_stream_salsa20_xor:te,crypto_stream_salsa20:Ee,crypto_onetimeauth:vt,crypto_onetimeauth_verify:Fe,crypto_verify_16:S,crypto_verify_32:C,crypto_secretbox:$,crypto_secretbox_open:V,crypto_scalarmult:Ot,crypto_scalarmult_base:_t,crypto_box_beforenm:Bs,crypto_box_afternm:Ns,crypto_box:Rx,crypto_box_open:bf,crypto_box_keypair:Dt,crypto_hash:Rn,crypto_sign:n0,crypto_sign_keypair:Ef,crypto_sign_open:Ia,crypto_secretbox_KEYBYTES:P,crypto_secretbox_NONCEBYTES:D,crypto_secretbox_ZEROBYTES:q,crypto_secretbox_BOXZEROBYTES:de,crypto_scalarmult_BYTES:Me,crypto_scalarmult_SCALARBYTES:$t,crypto_box_PUBLICKEYBYTES:Wt,crypto_box_SECRETKEYBYTES:ft,crypto_box_BEFORENMBYTES:ye,crypto_box_NONCEBYTES:Ce,crypto_box_ZEROBYTES:ke,crypto_box_BOXZEROBYTES:Ne,crypto_sign_BYTES:st,crypto_sign_PUBLICKEYBYTES:kt,crypto_sign_SECRETKEYBYTES:jt,crypto_sign_SEEDBYTES:Xr,crypto_hash_BYTES:ld,gf:e,D:c,L:fd,pack25519:ne,unpack25519:F,M:ce,A:I,S:he,Z:L,pow2523:xt,add:Ta,set25519:H,modL:xi,scalarmult:_f,scalarbase:ud};function i0(m,b){if(m.length!==P)throw new Error("bad key size");if(b.length!==D)throw new Error("bad nonce size")}function Px(m,b){if(m.length!==Wt)throw new Error("bad public key size");if(b.length!==ft)throw new Error("bad secret key size")}function ws(){for(var m=0;m<arguments.length;m++)if(!(arguments[m]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function SE(m){for(var b=0;b<m.length;b++)m[b]=0}r.randomBytes=function(m){var b=new Uint8Array(m);return t(b,m),b},r.secretbox=function(m,b,x){ws(m,b,x),i0(x,b);for(var l=new Uint8Array(q+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+q]=m[k];return $(w,l,l.length,b,x),w.subarray(de)},r.secretbox.open=function(m,b,x){ws(m,b,x),i0(x,b);for(var l=new Uint8Array(de+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+de]=m[k];return l.length<32||V(w,l,l.length,b,x)!==0?null:w.subarray(q)},r.secretbox.keyLength=P,r.secretbox.nonceLength=D,r.secretbox.overheadLength=de,r.scalarMult=function(m,b){if(ws(m,b),m.length!==$t)throw new Error("bad n size");if(b.length!==Me)throw new Error("bad p size");var x=new Uint8Array(Me);return Ot(x,m,b),x},r.scalarMult.base=function(m){if(ws(m),m.length!==$t)throw new Error("bad n size");var b=new Uint8Array(Me);return _t(b,m),b},r.scalarMult.scalarLength=$t,r.scalarMult.groupElementLength=Me,r.box=function(m,b,x,l){var w=r.box.before(x,l);return r.secretbox(m,b,w)},r.box.before=function(m,b){ws(m,b),Px(m,b);var x=new Uint8Array(ye);return Bs(x,m,b),x},r.box.after=r.secretbox,r.box.open=function(m,b,x,l){var w=r.box.before(x,l);return r.secretbox.open(m,b,w)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var m=new Uint8Array(Wt),b=new Uint8Array(ft);return Dt(m,b),{publicKey:m,secretKey:b}},r.box.keyPair.fromSecretKey=function(m){if(ws(m),m.length!==ft)throw new Error("bad secret key size");var b=new Uint8Array(Wt);return _t(b,m),{publicKey:b,secretKey:new Uint8Array(m)}},r.box.publicKeyLength=Wt,r.box.secretKeyLength=ft,r.box.sharedKeyLength=ye,r.box.nonceLength=Ce,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(m,b){if(ws(m,b),b.length!==jt)throw new Error("bad secret key size");var x=new Uint8Array(st+m.length);return n0(x,m,m.length,b),x},r.sign.open=function(m,b){if(ws(m,b),b.length!==kt)throw new Error("bad public key size");var x=new Uint8Array(m.length),l=Ia(x,m,m.length,b);if(l<0)return null;for(var w=new Uint8Array(l),k=0;k<w.length;k++)w[k]=x[k];return w},r.sign.detached=function(m,b){for(var x=r.sign(m,b),l=new Uint8Array(st),w=0;w<l.length;w++)l[w]=x[w];return l},r.sign.detached.verify=function(m,b,x){if(ws(m,b,x),b.length!==st)throw new Error("bad signature size");if(x.length!==kt)throw new Error("bad public key size");var l=new Uint8Array(st+m.length),w=new Uint8Array(st+m.length),k;for(k=0;k<st;k++)l[k]=b[k];for(k=0;k<m.length;k++)l[k+st]=m[k];return Ia(w,l,l.length,x)>=0},r.sign.keyPair=function(){var m=new Uint8Array(kt),b=new Uint8Array(jt);return Ef(m,b),{publicKey:m,secretKey:b}},r.sign.keyPair.fromSecretKey=function(m){if(ws(m),m.length!==jt)throw new Error("bad secret key size");for(var b=new Uint8Array(kt),x=0;x<b.length;x++)b[x]=m[32+x];return{publicKey:b,secretKey:new Uint8Array(m)}},r.sign.keyPair.fromSeed=function(m){if(ws(m),m.length!==Xr)throw new Error("bad seed size");for(var b=new Uint8Array(kt),x=new Uint8Array(jt),l=0;l<32;l++)x[l]=m[l];return Ef(b,x,!0),{publicKey:b,secretKey:x}},r.sign.publicKeyLength=kt,r.sign.secretKeyLength=jt,r.sign.seedLength=Xr,r.sign.signatureLength=st,r.hash=function(m){ws(m);var b=new Uint8Array(ld);return Rn(b,m,m.length),b},r.hash.hashLength=ld,r.verify=function(m,b){return ws(m,b),m.length===0||b.length===0||m.length!==b.length?!1:v(m,0,b,0,m.length)===0},r.setPRNG=function(m){t=m},(function(){var m=typeof self<"u"?self.crypto||self.msCrypto:null;if(m&&m.getRandomValues){var b=65536;r.setPRNG(function(x,l){var w,k=new Uint8Array(l);for(w=0;w<l;w+=b)m.getRandomValues(k.subarray(w,w+Math.min(l-w,b)));for(w=0;w<l;w++)x[w]=k[w];SE(k)})}else typeof require<"u"&&(m=require("crypto"),m&&m.randomBytes&&r.setPRNG(function(x,l){var w,k=m.randomBytes(l);for(w=0;w<l;w++)x[w]=k[w];SE(k)}))})()})(typeof Q0<"u"&&Q0.exports?Q0.exports:self.nacl=self.nacl||{})});var jb=se(Ub=>{"use strict";Object.defineProperty(Ub,"__esModule",{value:!0});var Mb=class{constructor(e,t=0,s=0){this.start=t,this.end=s>t?s:t,this.buf=e}get length(){return this.buf.length}reset(e=0,t=0){return this.start=e,t>=this.start?this.end=t:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,t="Too few bytes to parse."){let s=this.end+e;if(s>this.buf.length){let n=new Error(t);throw n.available=this.buf.length,n.requested=s,n}return this.walk(0),this}mustWalk(e,t){return this.mustHas(e,t),this.walk(e),this}};Ub.BufferVisitor=Mb});var x6=se(zb=>{"use strict";Object.defineProperty(zb,"__esModule",{value:!0});var g6=require("util"),y6=64,Fb="-----BEGIN ",qb="-----END ",$f="-----",Hb="Proc-Type",em=class{static parse(e){let t=[],s=e.toString("utf8").split(`
12
- `).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#"));for(;s.length>0;)t.push(zD(s));if(t.length===0)throw new Error("PEM: no block");return t}constructor(e,t){this.type=e,this.body=t,this.headers=Object.create(null)}get procType(){return this.getHeader(Hb)}getHeader(e){let t=this.headers[e];return t??""}setHeader(e,t){if(e.includes(":"))throw new Error("pem: cannot encode a header key that contains a colon");if(e===""||t==="")throw new Error("pem: invalid header key or value");this.headers[e]=t}toString(){let e=Fb+this.type+$f+`
13
- `,t=Object.keys(this.headers);if(t.length>0){let i=this.procType;i!==""&&(e+=`${Hb}: ${i}
14
- `),t.sort();for(let o of t)o!==Hb&&(e+=`${o}: ${this.headers[o]}
15
- `);e+=`
16
- `}let s=this.body.toString("base64"),n=0;for(;n<s.length;)e+=s.slice(n,n+y6)+`
17
- `,n+=y6;return e+=qb+this.type+$f+`
18
- `,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[g6.inspect.custom](e,t){return`<${this.constructor.name} ${g6.inspect(this.toJSON(),t)}>`}};zb.PEM=em;function zD(r){let e=r.shift();if(e==null||!e.startsWith(Fb)||!e.endsWith($f))throw new Error("pem: invalid BEGIN line");let t=e.slice(Fb.length,e.length-$f.length);if(t==="")throw new Error("pem: invalid type");let s=[];for(e=r.shift();e!=null&&e.includes(": ");){let o=e.split(": ");if(o.length!==2||o[0]===""||o[1]==="")throw new Error("pem: invalid Header line");s.push(o),e=r.shift()}let n="";for(;e!=null&&!e.startsWith(qb);)n+=e,e=r.shift();if(e==null||e!==`${qb}${t}${$f}`)throw new Error("pem: invalid END line");let i=new em(t,Buffer.from(n,"base64"));if(n===""||i.body.toString("base64")!==n)throw new Error("pem: invalid base64 body");for(let o of s)i.setHeader(o[0],o[1]);return i}});var S6=se(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var b6=require("util"),tm=jb(),ir;(function(r){r[r.UNIVERSAL=0]="UNIVERSAL",r[r.APPLICATION=64]="APPLICATION",r[r.CONTEXT_SPECIFIC=128]="CONTEXT_SPECIFIC",r[r.PRIVATE=192]="PRIVATE"})(ir=_o.Class||(_o.Class={}));var Et;(function(r){r[r.NONE=0]="NONE",r[r.BOOLEAN=1]="BOOLEAN",r[r.INTEGER=2]="INTEGER",r[r.BITSTRING=3]="BITSTRING",r[r.OCTETSTRING=4]="OCTETSTRING",r[r.NULL=5]="NULL",r[r.OID=6]="OID",r[r.ENUMERATED=10]="ENUMERATED",r[r.UTF8=12]="UTF8",r[r.SEQUENCE=16]="SEQUENCE",r[r.SET=17]="SET",r[r.NUMERICSTRING=18]="NUMERICSTRING",r[r.PRINTABLESTRING=19]="PRINTABLESTRING",r[r.T61STRING=20]="T61STRING",r[r.IA5STRING=22]="IA5STRING",r[r.UTCTIME=23]="UTCTIME",r[r.GENERALIZEDTIME=24]="GENERALIZEDTIME",r[r.GENERALSTRING=27]="GENERALSTRING"})(Et=_o.Tag||(_o.Tag={}));var Vf=class{constructor(e,t){this.buf=e,this.bitLen=t}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let t=Math.floor(e/8),s=7-e%8;return this.buf[t]>>s&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let t=Buffer.alloc(this.buf.length);t[0]=this.buf[0]>>e;for(let s=1;s<this.buf.length;s++)t[s]=this.buf[s-1]<<8-e,t[s]|=this.buf[s]>>e;return t}};_o.BitString=Vf;var $b=class r{static Bool(e){let t=new r(ir.UNIVERSAL,Et.BOOLEAN,Buffer.from([e?255:0]));return t._value=e,t}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error("ASN1 syntax error: invalid boolean");switch(e[0]){case 0:return!1;case 255:return!0;default:throw new Error("ASN1 syntax error: invalid boolean")}}static Integer(e){if(e instanceof Buffer){let n=new r(ir.UNIVERSAL,Et.INTEGER,e);return n._value=e.toString("hex"),n}if(!Number.isSafeInteger(e))throw new Error("ASN1 syntax error: invalid integer");let t;if(e>=-128&&e<128)t=Buffer.alloc(1),t.writeInt8(e,0);else if(e>=-32768&&e<32768)t=Buffer.alloc(2),t.writeIntBE(e,0,2);else if(e>=-8388608&&e<8388608)t=Buffer.alloc(3),t.writeIntBE(e,0,3);else if(e>=-2147483648&&e<2147483648)t=Buffer.alloc(4),t.writeIntBE(e,0,4);else if(e>=-549755813888&&e<549755813888)t=Buffer.alloc(5),t.writeIntBE(e,0,5);else if(e>=-0x800000000000&&e<0x800000000000)t=Buffer.alloc(6),t.writeIntBE(e,0,6);else throw new Error("ASN1 syntax error: invalid Integer");let s=new r(ir.UNIVERSAL,Et.INTEGER,t);return s._value=e,s}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Integer");return e.length>6?e.toString("hex"):e.readIntBE(0,e.length)}static parseIntegerNum(e){let t=r.parseInteger(e);if(typeof t!="number")throw new Error("ASN1 syntax error: invalid Integer number");return t}static parseIntegerStr(e){let t=r.parseInteger(e);return typeof t=="number"?t.toString(16):t}static BitString(e){e instanceof Buffer&&(e=new Vf(e,e.length*8));let t=e.buf.length*8-e.bitLen,s=Buffer.alloc(e.buf.length+1);return s.writeInt8(t,0),e.buf.copy(s,1),new r(ir.UNIVERSAL,Et.BITSTRING,s)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid BitString");let t=e[0];if(t>7||e.length===1&&t>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");return new Vf(e.slice(1),(e.length-1)*8-t)}static Null(){let e=new r(ir.UNIVERSAL,Et.NULL,Buffer.alloc(0));return e._value=null,e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error("ASN1 syntax error: invalid null");return null}static OID(e){let t=e.split(".");if(t.length===0)throw new Error("ASN1 syntax error: invalid Object Identifier");let s=[];s.push(40*xr(t[0])+xr(t[1]));let n=[];for(let o=2;o<t.length;++o){let a=xr(t[o]);for(n.length=0,n.push(a&127);a>127;)a=a>>>7,n.unshift(a&127|128);s.push(...n)}let i=new r(ir.UNIVERSAL,Et.OID,Buffer.from(s));return i._value=e,i}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid OID");let t=Math.floor(e[0]/40)+"."+e[0]%40,s=0;for(let n=1;n<e.length;n++)e[n]>=128?(s+=e[n]&127,s=s<<7):(t+="."+(s+e[n]),s=0);return t}static UTF8(e){let t=new r(ir.UNIVERSAL,Et.UTF8,Buffer.from(e,"utf8"));return t._value=e,t}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static NumericString(e){if(!v6(e))throw new Error("ASN1 syntax error: invalid NumericString");let t=new r(ir.UNIVERSAL,Et.NUMERICSTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let t=e.toString("utf8");if(!v6(t))throw new Error("ASN1 syntax error: invalid NumericString");return t}static PrintableString(e){let t=new r(ir.UNIVERSAL,Et.PRINTABLESTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static IA5String(e){if(!w6(e))throw new Error("ASN1 syntax error: invalid IA5String");let t=new r(ir.UNIVERSAL,Et.IA5STRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let t=e.toString("utf8");if(!w6(t))throw new Error("ASN1 syntax error: invalid IA5String");return t}static T61String(e){let t=new r(ir.UNIVERSAL,Et.T61STRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseT61String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static GeneralString(e){let t=new r(ir.UNIVERSAL,Et.GENERALSTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static UTCTime(e){let t="",s=[];s.push((""+e.getUTCFullYear()).substr(2)),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(t+="0"),t+=i;t+="Z";let n=new r(ir.UNIVERSAL,Et.UTCTIME,Buffer.from(t,"utf8"));return n._value=e,n}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid UTC Time");let t=e.toString("utf8"),s=new Date,n=xr(t.substr(0,2));n=n>=50?1900+n:2e3+n;let i=xr(t.substr(2,2))-1,o=xr(t.substr(4,2)),a=xr(t.substr(6,2)),c=xr(t.substr(8,2)),d=0,u=0,f="";if(t.length>11&&(u=10,f=t.charAt(u),f!=="+"&&f!=="-"&&(d=xr(t.substr(10,2)),u+=2)),s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,0),u>0&&(f=t.charAt(u),f==="+"||f==="-")){let h=xr(t.substr(u+1,2)),y=xr(t.substr(u+4,2)),v=h*60+y;v*=6e4,f==="+"?s.setTime(+s-v):s.setTime(+s+v)}return s}static GeneralizedTime(e){let t="",s=[];s.push(""+e.getUTCFullYear()),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(t+="0"),t+=i;t+="Z";let n=new r(ir.UNIVERSAL,Et.GENERALIZEDTIME,Buffer.from(t,"utf8"));return n._value=e,n}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");let t=e.toString("utf8"),s=new Date,n=xr(t.substr(0,4)),i=xr(t.substr(4,2))-1,o=xr(t.substr(6,2)),a=xr(t.substr(8,2)),c=xr(t.substr(10,2)),d=xr(t.substr(12,2)),u=0,f=0,h=!1;t.charAt(t.length-1)==="Z"&&(h=!0);let y=t.length-5,v=t.charAt(y);if(v==="+"||v==="-"){let S=xr(t.substr(y+1,2)),C=xr(t.substr(y+4,2));f=S*60+C,f*=6e4,v==="+"&&(f*=-1),h=!0}return t.charAt(14)==="."&&(u=parseFloat(t.substr(14))*1e3),h?(s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,u),s.setTime(+s+f)):(s.setFullYear(n,i,o),s.setHours(a,c,d,u)),s}static parseTime(e,t){switch(e){case Et.UTCTIME:return r.parseUTCTime(t);case Et.GENERALIZEDTIME:return r.parseGeneralizedTime(t);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let t=new r(ir.UNIVERSAL,Et.SET,Buffer.concat(e.map(s=>s.toDER())));return t._value=e,t}static Seq(e){let t=new r(ir.UNIVERSAL,Et.SEQUENCE,Buffer.concat(e.map(s=>s.toDER())));return t._value=e,t}static Spec(e,t,s=!0){let n=Array.isArray(t)?Buffer.concat(t.map(o=>o.toDER())):t.toDER();Array.isArray(t)&&(s=!0);let i=new r(ir.CONTEXT_SPECIFIC,e,n,s);return i._value=t,i}static fromDER(e,t=!1){return r._fromDER(new tm.BufferVisitor(e),t)}static parseDER(e,t,s){let n=r._fromDER(new tm.BufferVisitor(e),!1);if(n.class!==t&&n.tag!==s)throw new Error(`invalid ASN.1 DER for class ${t} and tag ${s}`);return n}static parseDERWithTemplate(e,t){let s=r._fromDER(new tm.BufferVisitor(e),!0),n={},i=s.validate(t,n);if(i!=null)throw i.data=s,i;return n}static _parseCompound(e,t){let s=[],n=e.length,i=new tm.BufferVisitor(e),o=0;for(;o<n;){let a=i.end;s.push(r._fromDER(i,t)),o+=i.end-a}return s}static _fromDER(e,t){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");e.mustWalk(1,"Too few bytes to read ASN.1 tag.");let s=e.start,n=e.buf[s],i=n&192,o=n&31,a=$D(e);if(e.mustHas(a),a!==0&&o===Et.NULL)throw new Error("invalid value length or NULL tag.");e.mustWalk(a);let c=(n&32)===32,d=new r(i,o,e.buf.slice(e.start,e.end),c);return c&&t&&(d._value=r._parseCompound(d.bytes,t)),d._der=e.buf.slice(s,e.end),d}constructor(e,t,s,n=!1){this.class=e,this.tag=t,this.bytes=s,this.isCompound=n||t===Et.SEQUENCE||t===Et.SET,this._value=void 0,this._der=null}get value(){return this._value===void 0&&(this._value=this.valueOf()),this._value}get DER(){return this._der==null&&(this._der=this.toDER()),this._der}mustCompound(e="asn1 object value is not compound"){if(!this.isCompound||!Array.isArray(this.value)){let t=new Error(e);throw t.data=this.toJSON(),t}return this.value}equals(e){return!(!(e instanceof r)||this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound||!this.bytes.equals(e.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let t=VD(this.bytes.length),s=Buffer.allocUnsafe(2+t+this.bytes.length);return s.writeInt8(e,0),t===0?(s.writeUInt8(this.bytes.length,1),this.bytes.copy(s,2)):(s.writeUInt8(t|128,1),s.writeUIntBE(this.bytes.length,2,t),this.bytes.copy(s,2+t)),s}valueOf(){if(this.isCompound)return r._parseCompound(this.bytes,!1);if(this.class!==ir.UNIVERSAL)return this.bytes;switch(this.tag){case Et.BOOLEAN:return r.parseBool(this.bytes);case Et.INTEGER:return r.parseInteger(this.bytes);case Et.BITSTRING:return r.parseBitString(this.bytes);case Et.NULL:return r.parseNull(this.bytes);case Et.OID:return r.parseOID(this.bytes);case Et.UTF8:return r.parseUTF8(this.bytes);case Et.NUMERICSTRING:return r.parseNumericString(this.bytes);case Et.PRINTABLESTRING:return r.parsePrintableString(this.bytes);case Et.T61STRING:return r.parseT61String(this.bytes);case Et.IA5STRING:return r.parseIA5String(this.bytes);case Et.GENERALSTRING:return r.parseGeneralString(this.bytes);case Et.UTCTIME:return r.parseUTCTime(this.bytes);case Et.GENERALIZEDTIME:return r.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,t={}){if(this.class!==e.class)return new Error(`ASN.1 object validate failure for ${e.name} : error class ${ir[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return new Error(`ASN.1 object validate failure for ${e.name}: error tag ${Et[this.tag]}`);if(e.capture!=null&&(t[e.capture]=this),Array.isArray(e.value)){let n=this.mustCompound(`${e.name} need compound ASN1 value`);for(let i=0,o=0;i<e.value.length;i++)if(n[o]!=null){let a=n[o].validate(e.value[i],t);if(a==null)o++;else if(e.value[i].optional!==!0)return a}else if(e.value[i].optional!==!0)return new Error(`ASN.1 object validate failure for ${e.value[i].name}: not exists`)}else if(e.value!=null){let n=this.tag===Et.BITSTRING?this.bytes.slice(1):this.bytes;return r.fromDER(n).validate(e.value,t)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(t=>t.toJSON())),{class:ir[this.class],tag:this.class===ir.UNIVERSAL?Et[this.tag]:this.tag,value:e}}[b6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${b6.inspect(this.toJSON(),t)}>`}};_o.ASN1=$b;function $D(r){r.mustWalk(1,"Too few bytes to read ASN.1 value length.");let e=r.buf[r.start];if((e&128)===0)return e;let t=e&127;return r.mustWalk(t,"Too few bytes to read ASN.1 value length."),r.buf.readUIntBE(r.start,t)}function VD(r){if(r<=127)return 0;if(r<=255)return 1;if(r<=65535)return 2;if(r<=16777215)return 3;if(r<=4294967295)return 4;if(r<=0xffffffffff)return 5;if(r<=0xffffffffffff)return 6;throw new Error("invalid value length")}function v6(r){for(let e of r){let t=e.charCodeAt(0);if(t!==32&&(t<48||t>57))return!1}return!0}function w6(r){for(let e of r)if(e.charCodeAt(0)>=128)return!1;return!0}function xr(r,e=10){let t=parseInt(r,e);if(Number.isNaN(t))throw new Error(`Invalid numeric string "${r}" in radix ${e}.`);return t}});var Vb=se(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var KD=jb();Eo.BufferVisitor=KD.BufferVisitor;var WD=x6();Eo.PEM=WD.PEM;var rm=S6();Eo.ASN1=rm.ASN1;Eo.Class=rm.Class;Eo.Tag=rm.Tag;Eo.BitString=rm.BitString});var Xb=se(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});var To=require("util"),Kf=require("crypto"),Gb=Z0(),le=Vb(),zr=J0();Ln.publicKeyValidator={name:"PublicKeyInfo",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:le.Class.UNIVERSAL,tag:le.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:le.Class.UNIVERSAL,tag:le.Tag.BITSTRING,capture:"publicKey"}]};Ln.privateKeyValidator={name:"PrivateKeyInfo",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:le.Class.UNIVERSAL,tag:le.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:le.Class.UNIVERSAL,tag:le.Tag.OCTETSTRING,capture:"privateKey"}]};var GD={name:"RSAPublicKey",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"publicKeyExponent"}]},XD={name:"RSAPrivateKey",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyCoefficient"}]},YD=[zr.getOID("X25519"),zr.getOID("X448"),zr.getOID("Ed25519"),zr.getOID("Ed448")],jd=class r{constructor(e){let t={},s=e.validate(Ln.publicKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 public key: "+s.message);this.oid=le.ASN1.parseOID(t.publicKeyOID.bytes),this.algo=zr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=le.ASN1.parseBitString(t.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let t=le.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let s=le.ASN1.fromDER(t.body,!0);switch(t.type){case"PUBLIC KEY":return new r(s);case"RSA PUBLIC KEY":let n=le.ASN1.Seq([le.ASN1.Seq([le.ASN1.OID(zr.getOID("rsaEncryption")),le.ASN1.Null()]),le.ASN1.BitString(s.DER)]);return new r(n);default:throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM")}}static addVerifier(e,t){if(e=zr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(r._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);r._verifiers[e]=t}get keyRaw(){return this._finalKey}verify(e,t,s){let n=r._verifiers[this.oid];if(n!=null){let o=Kf.createHash(s).update(e).digest();return n.call(this,o,t)}let i=Kf.createVerify(s);return i.update(e),i.verify(this.toPEM(),t)}getFingerprint(e,t="PublicKey"){let s;switch(t){case"PublicKeyInfo":s=this._pkcs8.DER;break;case"PublicKey":s=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${t}".`)}let n=Kf.createHash(e);return n.update(s),n.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("PUBLIC KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};jd._verifiers=Object.create(null);Ln.PublicKey=jd;var Hd=class r{constructor(e){let t=Object.create(null),s=e.validate(Ln.privateKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 private key: "+s.message);if(this.version=le.ASN1.parseIntegerNum(t.privateKeyVersion.bytes)+1,this.oid=le.ASN1.parseOID(t.privateKeyOID.bytes),this.algo=zr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=t.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM="",YD.includes(this.oid)){if(this._finalKey=this._keyRaw=le.ASN1.parseDER(this._keyRaw,le.Class.UNIVERSAL,le.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let n=Gb.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(n.publicKey),this._finalKey=Buffer.from(n.secretKey)}else if(this.version===2)for(let n of e.mustCompound())n.class===le.Class.CONTEXT_SPECIFIC&&n.tag===1&&(this._publicKeyRaw=le.ASN1.parseBitString(n.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let t=le.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let s=le.ASN1.fromDER(t.body,!0);switch(t.type){case"PRIVATE KEY":return new r(s);case"RSA PRIVATE KEY":return s=le.ASN1.Seq([s.value[0],le.ASN1.Seq([le.ASN1.OID(zr.getOID("rsaEncryption")),le.ASN1.Null()]),new le.ASN1(le.Class.UNIVERSAL,le.Tag.OCTETSTRING,s.DER)]),new r(s);default:throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM")}}static addSigner(e,t){if(e=zr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(r._signers[e]!=null)throw new Error(`Signer ${e} exists`);r._signers[e]=t}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,t){let s=r._signers[this.oid];if(s!=null){let i=Kf.createHash(t).update(e).digest();return s.call(this,i)}let n=Kf.createSign(t);return n.update(e),n.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("PRIVATE KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,privateKey:this._keyRaw,publicKey:this._publicKeyRaw}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};Hd._signers=Object.create(null);Ln.PrivateKey=Hd;var Kb=class r extends jd{static fromPublicKey(e){return new r(e.toASN1())}constructor(e){if(super(e),zr.getOID(this.oid)!==zr.getOID("rsaEncryption"))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=le.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(GD,t);if(s!=null)throw new Error("Cannot read RSA public key: "+s.message);this.modulus=le.ASN1.parseIntegerStr(t.publicKeyModulus.bytes),this.exponent=le.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new le.PEM("PUBLIC KEY",this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:Co(this.modulus),exponent:this.exponent}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};Ln.RSAPublicKey=Kb;var Wb=class r extends Hd{static fromPrivateKey(e){return new r(e.toASN1())}constructor(e){if(super(e),zr.getOID(this.oid)!==zr.getOID("rsaEncryption"))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=le.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(XD,t);if(s!=null)throw new Error("Cannot read RSA private key: "+s.message);this.publicExponent=le.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes),this.privateExponent=le.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes),this.modulus=le.ASN1.parseIntegerStr(t.privateKeyModulus.bytes),this.prime1=le.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes),this.prime2=le.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes),this.exponent1=le.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes),this.exponent2=le.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes),this.coefficient=le.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new le.PEM("PRIVATE KEY",this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:Co(this.privateExponent),modulus:Co(this.modulus),prime1:Co(this.prime1),prime2:Co(this.prime2),exponent1:Co(this.exponent1),exponent2:Co(this.exponent2),coefficient:Co(this.coefficient)}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};Ln.RSAPrivateKey=Wb;function Co(r){return r.length%8!==0&&r.startsWith("00")?r.slice(2):r}jd.addVerifier(zr.getOID("Ed25519"),function(r,e){return Gb.sign.detached.verify(r,e,this.keyRaw)});Hd.addSigner(zr.getOID("Ed25519"),function(r){let e=this.keyRaw;if(e.length!==64)throw new Error("Invalid signing key.");return Buffer.from(Gb.sign.detached(r,e))})});var I6=se(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var _6=require("util"),JD=require("crypto"),ie=Vb(),$r=J0(),A6=Xb(),br=Object.create(null);br.CN=$r.getOID("commonName");br.commonName="CN";br.C=$r.getOID("countryName");br.countryName="C";br.L=$r.getOID("localityName");br.localityName="L";br.ST=$r.getOID("stateOrProvinceName");br.stateOrProvinceName="ST";br.O=$r.getOID("organizationName");br.organizationName="O";br.OU=$r.getOID("organizationalUnitName");br.organizationalUnitName="OU";br.E=$r.getOID("emailAddress");br.emailAddress="E";function QD(r){return br[r]==null?"":br[r]}var ZD={name:"Certificate",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:ie.Class.UNIVERSAL,tag:ie.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:ie.Class.UNIVERSAL,tag:ie.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:ie.Class.UNIVERSAL,tag:[ie.Tag.UTCTIME,ie.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:ie.Class.UNIVERSAL,tag:[ie.Tag.UTCTIME,ie.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"certSubject"},A6.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certSignature"}]},Wf=class{constructor(){this.attributes=[],this.uniqueId=null}get commonName(){return this.getFieldValue("commonName")}get organizationName(){return this.getFieldValue("organizationName")}get organizationalUnitName(){return this.getFieldValue("organizationalUnitName")}get countryName(){return this.getFieldValue("countryName")}get localityName(){return this.getFieldValue("localityName")}get serialName(){return this.getFieldValue("serialName")}getHash(){let e=JD.createHash("sha1");for(let t of this.attributes)e.update(t.oid),e.update(t.value);return e.digest()}getField(e){for(let t of this.attributes)if(e===t.oid||e===t.name||e===t.shortName)return t;return null}addField(e){C6([e]),this.attributes.push(e)}setAttrs(e){C6(e),this.attributes=e}toJSON(){let e={};for(let t of this.attributes){let s=t.shortName;typeof s=="string"&&s!==""&&(e[s]=t.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let t=this.getField(e);return t!=null?t.value:""}};sm.DistinguishedName=Wf;var Yb=class r{static fromPEMs(e){let t=[],s=ie.PEM.parse(e);for(let n of s){if(n.type!=="CERTIFICATE"&&n.type!=="X509 CERTIFICATE"&&n.type!=="TRUSTED CERTIFICATE")throw new Error("Could not convert certificate from PEM: invalid type");if(n.procType.includes("ENCRYPTED"))throw new Error("Could not convert certificate from PEM: PEM is encrypted.");let i=ie.ASN1.fromDER(n.body);t.push(new r(i))}if(t.length===0)throw new Error("No Certificate");return t}static fromPEM(e){return r.fromPEMs(e)[0]}constructor(e){let t=Object.create(null),s=e.validate(ZD,t);if(s!=null)throw new Error("Cannot read X.509 certificate: "+s.message);if(this.raw=e.DER,this.version=t.certVersion==null?0:ie.ASN1.parseIntegerNum(t.certVersion.bytes)+1,this.serialNumber=ie.ASN1.parseIntegerStr(t.certSerialNumber.bytes),this.signatureOID=ie.ASN1.parseOID(t.certSignatureOID.bytes),this.signatureAlgorithm=$r.getOIDName(this.signatureOID),this.infoSignatureOID=ie.ASN1.parseOID(t.certinfoSignatureOID.bytes),this.signature=ie.ASN1.parseBitString(t.certSignature.bytes).buf,this.validFrom=ie.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes),this.validTo=ie.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes),this.issuer=new Wf,this.issuer.setAttrs(T6(t.certIssuer)),t.certIssuerUniqueId!=null&&(this.issuer.uniqueId=ie.ASN1.parseBitString(t.certIssuerUniqueId.bytes)),this.subject=new Wf,this.subject.setAttrs(T6(t.certSubject)),t.certSubjectUniqueId!=null&&(this.subject.uniqueId=ie.ASN1.parseBitString(t.certSubjectUniqueId.bytes)),this.extensions=[],this.subjectKeyIdentifier="",this.authorityKeyIdentifier="",this.ocspServer="",this.issuingCertificateURL="",this.isCA=!1,this.maxPathLen=-1,this.basicConstraintsValid=!1,this.keyUsage=0,this.dnsNames=[],this.emailAddresses=[],this.ipAddresses=[],this.uris=[],t.certExtensions!=null){this.extensions=eM(t.certExtensions);for(let n of this.extensions)if(typeof n.subjectKeyIdentifier=="string"&&(this.subjectKeyIdentifier=n.subjectKeyIdentifier),typeof n.authorityKeyIdentifier=="string"&&(this.authorityKeyIdentifier=n.authorityKeyIdentifier),typeof n.authorityInfoAccessOcsp=="string"&&(this.ocspServer=n.authorityInfoAccessOcsp),typeof n.authorityInfoAccessIssuers=="string"&&(this.issuingCertificateURL=n.authorityInfoAccessIssuers),typeof n.basicConstraintsValid=="boolean"&&(this.isCA=n.isCA,this.maxPathLen=n.maxPathLen,this.basicConstraintsValid=n.basicConstraintsValid),typeof n.keyUsage=="number"&&(this.keyUsage=n.keyUsage),Array.isArray(n.altNames))for(let i of n.altNames)i.dnsName!=null&&this.dnsNames.push(i.dnsName),i.email!=null&&this.emailAddresses.push(i.email),i.ip!=null&&this.ipAddresses.push(i.ip),i.uri!=null&&this.uris.push(i.uri)}this.publicKey=new A6.PublicKey(t.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=t.tbsCertificate}getExtension(e,t=""){for(let s of this.extensions)if(e===s.oid||e===s.name)return t===""?s:s[t];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return new Error("The parent constraint violation error");if(this.getExtension("keyUsage","keyCertSign")!==!0)return new Error("The parent constraint violation error");if(!e.isIssuer(this))return new Error("The parent certificate did not issue the given child certificate");let t=lM(e.signatureOID);return t===""?new Error("Unknown child signature OID."):this.publicKey.verify(e.tbsCertificate.DER,e.signature,t)===!1?new Error("Child signature not matched"):null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint("sha1","PublicKey").toString("hex")===this.subjectKeyIdentifier}toJSON(){let e={};for(let t of Object.keys(this))e[t]=hM(this[t]);return delete e.tbsCertificate,e}[_6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${_6.inspect(this.toJSON(),t)}>`}};sm.Certificate=Yb;function eM(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound())e.push(tM(s));return e}function tM(r){let e={};switch(e.oid=ie.ASN1.parseOID(r.value[0].bytes),e.critical=!1,r.value[1].tag===ie.Tag.BOOLEAN?(e.critical=ie.ASN1.parseBool(r.value[1].bytes),e.value=r.value[2].bytes):e.value=r.value[1].bytes,e.name=$r.getOIDName(e.oid),e.name){case"keyUsage":rM(e);break;case"basicConstraints":sM(e);break;case"extKeyUsage":nM(e);break;case"nsCertType":iM(e);break;case"subjectAltName":E6(e);break;case"issuerAltName":E6(e);break;case"subjectKeyIdentifier":aM(e);break;case"authorityKeyIdentifier":dM(e);break;case"authorityInfoAccess":fM(e);break}return e}function rM(r){let e=ie.ASN1.parseBitString(ie.ASN1.fromDER(r.value).bytes),t=0,s=0;r.keyUsage=0;for(let n=0;n<9;n++)e.at(n)!==0&&(r.keyUsage|=1<<n);e.buf.length>0&&(t=e.buf[0],s=e.buf.length>1?e.buf[1]:0),r.digitalSignature=(t&128)===128,r.nonRepudiation=(t&64)===64,r.keyEncipherment=(t&32)===32,r.dataEncipherment=(t&16)===16,r.keyAgreement=(t&8)===8,r.keyCertSign=(t&4)===4,r.cRLSign=(t&2)===2,r.encipherOnly=(t&1)===1,r.decipherOnly=(s&128)===128}function sM(r){let t=ie.ASN1.fromDER(r.value).mustCompound();t.length>0&&t[0].tag===ie.Tag.BOOLEAN?r.isCA=ie.ASN1.parseBool(t[0].bytes):r.isCA=!1;let s=null;t.length>0&&t[0].tag===ie.Tag.INTEGER?s=t[0].bytes:t.length>1&&(s=t[1].bytes),s!==null?r.maxPathLen=ie.ASN1.parseInteger(s):r.maxPathLen=-1,r.basicConstraintsValid=!0}function nM(r){let t=ie.ASN1.fromDER(r.value).mustCompound();for(let s of t)r[$r.getOIDName(ie.ASN1.parseOID(s.bytes))]=!0}function iM(r){let e=ie.ASN1.parseBitString(ie.ASN1.fromDER(r.value).bytes),t=0;e.buf.length>0&&(t=e.buf[0]),r.client=(t&128)===128,r.server=(t&64)===64,r.email=(t&32)===32,r.objsign=(t&16)===16,r.reserved=(t&8)===8,r.sslCA=(t&4)===4,r.emailCA=(t&2)===2,r.objCA=(t&1)===1}function E6(r){r.altNames=[];let t=ie.ASN1.fromDER(r.value).mustCompound();for(let s of t){let n={tag:s.tag,value:s.bytes};switch(r.altNames.push(n),s.tag){case 1:n.email=s.bytes.toString();break;case 2:n.dnsName=s.bytes.toString();break;case 6:n.uri=s.bytes.toString();break;case 7:n.ip=$r.bytesToIP(s.bytes);break;case 8:n.oid=ie.ASN1.parseOID(s.bytes);break;default:}}}var oM={name:"subjectKeyIdentifier",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function aM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,oM);r.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var cM={name:"authorityKeyIdentifier",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.NONE,capture:"authorityKeyIdentifier"}]};function dM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,cM);r.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var uM={name:"authorityInfoAccess",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function fM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,uM);e.authorityInfoAccessOcsp!=null&&(r.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(r.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function C6(r){for(let e of r){if((e.name==null||e.name==="")&&(e.oid!=null&&(e.name=$r.getOIDName(e.oid)),e.name===""&&e.shortName!=null&&(e.name=$r.getOIDName(br[e.shortName]))),e.oid==null||e.oid==="")if(e.name!=="")e.oid=$r.getOID(e.name);else throw new Error("Attribute oid not specified.");if((e.shortName==null||e.shortName==="")&&(e.shortName=br[e.name]==null?"":br[e.name]),e.value==null)throw new Error("Attribute value not specified.")}}function lM(r){switch($r.getOIDName(r)){case"sha1WithRsaEncryption":return"sha1";case"md5WithRsaEncryption":return"md5";case"sha256WithRsaEncryption":return"sha256";case"sha384WithRsaEncryption":return"sha384";case"sha512WithRsaEncryption":return"sha512";case"RSASSA-PSS":return"sha256";case"ecdsaWithSha1":return"sha1";case"ecdsaWithSha256":return"sha256";case"ecdsaWithSha384":return"sha384";case"ecdsaWithSha512":return"sha512";case"dsaWithSha1":return"sha1";case"dsaWithSha256":return"sha256";default:return""}}function T6(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound()){let n=s.mustCompound(),i={};i.oid=ie.ASN1.parseOID(n[0].bytes),i.value=n[1].value,i.valueTag=n[1].tag,i.name=$r.getOIDName(i.oid),i.shortName=QD(i.name),e.push(i)}return e}function hM(r){return r!=null&&!(r instanceof Buffer)&&typeof r.toJSON=="function"?r.toJSON():r}});var Jb=se(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var nm=J0();js.bytesFromIP=nm.bytesFromIP;js.bytesToIP=nm.bytesToIP;js.getOID=nm.getOID;js.getOIDName=nm.getOIDName;var im=Xb();js.PublicKey=im.PublicKey;js.PrivateKey=im.PrivateKey;js.RSAPublicKey=im.RSAPublicKey;js.RSAPrivateKey=im.RSAPrivateKey;var R6=I6();js.Certificate=R6.Certificate;js.DistinguishedName=R6.DistinguishedName});var P6=se(()=>{"use strict";var k6;(function(r){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),s=n(r);typeof t.Reflect<"u"&&(s=n(t.Reflect,s)),e(s,t),typeof t.Reflect>"u"&&(t.Reflect=r);function n(c,d){return function(u,f){Object.defineProperty(c,u,{configurable:!0,writable:!0,value:f}),d&&d(u,f)}}function i(){try{return Function("return this;")()}catch{}}function o(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||o()}})(function(e,t){var s=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",o=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,d=!a&&!c,u={create:a?function(){return Ia(Object.create(null))}:c?function(){return Ia({__proto__:null})}:function(){return Ia({})},has:d?function(P,D){return s.call(P,D)}:function(P,D){return D in P},get:d?function(P,D){return s.call(P,D)?P[D]:void 0}:function(P,D){return P[D]}},f=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Cf(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:n0(),v=typeof WeakMap=="function"?WeakMap:kx(),S=n?Symbol.for("@reflect-metadata:registry"):void 0,C=ud(),O=Ef(C);function K(P,D,q,de){if(I(q)){if(!Bs(P))throw new TypeError;if(!Ca(D))throw new TypeError;return Fe(P,D)}else{if(!Bs(P))throw new TypeError;if(!he(D))throw new TypeError;if(!he(de)&&!I(de)&&!L(de))throw new TypeError;return L(de)&&(de=void 0),q=Dt(q),$(P,D,q,de)}}e("decorate",K);function z(P,D){function q(de,Me){if(!he(de))throw new TypeError;if(!I(Me)&&!Rx(Me))throw new TypeError;ne(P,D,de,Me)}return q}e("metadata",z);function Q(P,D,q,de){if(!he(q))throw new TypeError;return I(de)||(de=Dt(de)),ne(P,D,q,de)}e("defineMetadata",Q);function oe(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),V(P,D,q)}e("hasMetadata",oe);function te(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),H(P,D,q)}e("hasOwnMetadata",te);function Ee(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),me(P,D,q)}e("getMetadata",Ee);function ge(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),Te(P,D,q)}e("getOwnMetadata",ge);function Y(P,D){if(!he(P))throw new TypeError;return I(D)||(D=Dt(D)),T(P,D)}e("getMetadataKeys",Y);function Ze(P,D){if(!he(P))throw new TypeError;return I(D)||(D=Dt(D)),R(P,D)}e("getOwnMetadataKeys",Ze);function vt(P,D,q){if(!he(D))throw new TypeError;if(I(q)||(q=Dt(q)),!he(D))throw new TypeError;I(q)||(q=Dt(q));var de=xi(D,q,!1);return I(de)?!1:de.OrdinaryDeleteMetadata(P,D,q)}e("deleteMetadata",vt);function Fe(P,D){for(var q=P.length-1;q>=0;--q){var de=P[q],Me=de(D);if(!I(Me)&&!L(Me)){if(!Ca(Me))throw new TypeError;D=Me}}return D}function $(P,D,q,de){for(var Me=P.length-1;Me>=0;--Me){var $t=P[Me],Wt=$t(D,q,de);if(!I(Wt)&&!L(Wt)){if(!he(Wt))throw new TypeError;de=Wt}}return de}function V(P,D,q){var de=H(P,D,q);if(de)return!0;var Me=Aa(D);return L(Me)?!1:V(P,Me,q)}function H(P,D,q){var de=xi(D,q,!1);return I(de)?!1:Ot(de.OrdinaryHasOwnMetadata(P,D,q))}function me(P,D,q){var de=H(P,D,q);if(de)return Te(P,D,q);var Me=Aa(D);if(!L(Me))return me(P,Me,q)}function Te(P,D,q){var de=xi(D,q,!1);if(!I(de))return de.OrdinaryGetOwnMetadata(P,D,q)}function ne(P,D,q,de){var Me=xi(q,de,!0);Me.OrdinaryDefineOwnMetadata(P,D,q,de)}function T(P,D){var q=R(P,D),de=Aa(P);if(de===null)return q;var Me=T(de,D);if(Me.length<=0)return q;if(q.length<=0)return Me;for(var $t=new y,Wt=[],ft=0,ye=q;ft<ye.length;ft++){var Ce=ye[ft],ke=$t.has(Ce);ke||($t.add(Ce),Wt.push(Ce))}for(var Ne=0,st=Me;Ne<st.length;Ne++){var Ce=st[Ne],ke=$t.has(Ce);ke||($t.add(Ce),Wt.push(Ce))}return Wt}function R(P,D){var q=xi(P,D,!1);return q?q.OrdinaryOwnMetadataKeys(P,D):[]}function F(P){if(P===null)return 1;switch(typeof P){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return P===null?1:6;default:return 6}}function I(P){return P===void 0}function L(P){return P===null}function ce(P){return typeof P=="symbol"}function he(P){return typeof P=="object"?P!==null:typeof P=="function"}function ct(P,D){switch(F(P)){case 0:return P;case 1:return P;case 2:return P;case 3:return P;case 4:return P;case 5:return P}var q=D===3?"string":D===5?"number":"default",de=vf(P,i);if(de!==void 0){var Me=de.call(P,q);if(he(Me))throw new TypeError;return Me}return xt(P,q==="default"?"number":q)}function xt(P,D){if(D==="string"){var q=P.toString;if(Ns(q)){var de=q.call(P);if(!he(de))return de}var Me=P.valueOf;if(Ns(Me)){var de=Me.call(P);if(!he(de))return de}}else{var Me=P.valueOf;if(Ns(Me)){var de=Me.call(P);if(!he(de))return de}var $t=P.toString;if(Ns($t)){var de=$t.call(P);if(!he(de))return de}}throw new TypeError}function Ot(P){return!!P}function _t(P){return""+P}function Dt(P){var D=ct(P,3);return ce(D)?D:_t(D)}function Bs(P){return Array.isArray?Array.isArray(P):P instanceof Object?P instanceof Array:Object.prototype.toString.call(P)==="[object Array]"}function Ns(P){return typeof P=="function"}function Ca(P){return typeof P=="function"}function Rx(P){switch(F(P)){case 3:return!0;case 4:return!0;default:return!1}}function bf(P,D){return P===D||P!==P&&D!==D}function vf(P,D){var q=P[D];if(q!=null){if(!Ns(q))throw new TypeError;return q}}function wf(P){var D=vf(P,o);if(!Ns(D))throw new TypeError;var q=D.call(P);if(!he(q))throw new TypeError;return q}function Rn(P){return P.value}function Ta(P){var D=P.next();return D.done?!1:D}function Sf(P){var D=P.return;D&&D.call(P)}function Aa(P){var D=Object.getPrototypeOf(P);if(typeof P!="function"||P===f||D!==f)return D;var q=P.prototype,de=q&&Object.getPrototypeOf(q);if(de==null||de===Object.prototype)return D;var Me=de.constructor;return typeof Me!="function"||Me===P?D:Me}function _f(){var P;!I(S)&&typeof t.Reflect<"u"&&!(S in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(P=fd(t.Reflect));var D,q,de,Me=new v,$t={registerProvider:Wt,getProvider:ye,setProvider:ke};return $t;function Wt(Ne){if(!Object.isExtensible($t))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case P===Ne:break;case I(D):D=Ne;break;case D===Ne:break;case I(q):q=Ne;break;case q===Ne:break;default:de===void 0&&(de=new y),de.add(Ne);break}}function ft(Ne,st){if(!I(D)){if(D.isProviderFor(Ne,st))return D;if(!I(q)){if(q.isProviderFor(Ne,st))return D;if(!I(de))for(var kt=wf(de);;){var jt=Ta(kt);if(!jt)return;var Xr=Rn(jt);if(Xr.isProviderFor(Ne,st))return Sf(kt),Xr}}}if(!I(P)&&P.isProviderFor(Ne,st))return P}function ye(Ne,st){var kt=Me.get(Ne),jt;return I(kt)||(jt=kt.get(st)),I(jt)&&(jt=ft(Ne,st),I(jt)||(I(kt)&&(kt=new h,Me.set(Ne,kt)),kt.set(st,jt))),jt}function Ce(Ne){if(I(Ne))throw new TypeError;return D===Ne||q===Ne||!I(de)&&de.has(Ne)}function ke(Ne,st,kt){if(!Ce(kt))throw new Error("Metadata provider not registered.");var jt=ye(Ne,st);if(jt!==kt){if(!I(jt))return!1;var Xr=Me.get(Ne);I(Xr)&&(Xr=new h,Me.set(Ne,Xr)),Xr.set(st,kt)}return!0}}function ud(){var P;return!I(S)&&he(t.Reflect)&&Object.isExtensible(t.Reflect)&&(P=t.Reflect[S]),I(P)&&(P=_f()),!I(S)&&he(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:P}),P}function Ef(P){var D=new v,q={isProviderFor:function(Ce,ke){var Ne=D.get(Ce);return I(Ne)?!1:Ne.has(ke)},OrdinaryDefineOwnMetadata:Wt,OrdinaryHasOwnMetadata:Me,OrdinaryGetOwnMetadata:$t,OrdinaryOwnMetadataKeys:ft,OrdinaryDeleteMetadata:ye};return C.registerProvider(q),q;function de(Ce,ke,Ne){var st=D.get(Ce),kt=!1;if(I(st)){if(!Ne)return;st=new h,D.set(Ce,st),kt=!0}var jt=st.get(ke);if(I(jt)){if(!Ne)return;if(jt=new h,st.set(ke,jt),!P.setProvider(Ce,ke,q))throw st.delete(ke),kt&&D.delete(Ce),new Error("Wrong provider for target.")}return jt}function Me(Ce,ke,Ne){var st=de(ke,Ne,!1);return I(st)?!1:Ot(st.has(Ce))}function $t(Ce,ke,Ne){var st=de(ke,Ne,!1);if(!I(st))return st.get(Ce)}function Wt(Ce,ke,Ne,st){var kt=de(Ne,st,!0);kt.set(Ce,ke)}function ft(Ce,ke){var Ne=[],st=de(Ce,ke,!1);if(I(st))return Ne;for(var kt=st.keys(),jt=wf(kt),Xr=0;;){var ld=Ta(jt);if(!ld)return Ne.length=Xr,Ne;var i0=Rn(ld);try{Ne[Xr]=i0}catch(Px){try{Sf(jt)}finally{throw Px}}Xr++}}function ye(Ce,ke,Ne){var st=de(ke,Ne,!1);if(I(st)||!st.delete(Ce))return!1;if(st.size===0){var kt=D.get(ke);I(kt)||(kt.delete(Ne),kt.size===0&&D.delete(kt))}return!0}}function fd(P){var D=P.defineMetadata,q=P.hasOwnMetadata,de=P.getOwnMetadata,Me=P.getOwnMetadataKeys,$t=P.deleteMetadata,Wt=new v,ft={isProviderFor:function(ye,Ce){var ke=Wt.get(ye);return!I(ke)&&ke.has(Ce)?!0:Me(ye,Ce).length?(I(ke)&&(ke=new y,Wt.set(ye,ke)),ke.add(Ce),!0):!1},OrdinaryDefineOwnMetadata:D,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:de,OrdinaryOwnMetadataKeys:Me,OrdinaryDeleteMetadata:$t};return ft}function xi(P,D,q){var de=C.getProvider(P,D);if(!I(de))return de;if(q){if(C.setProvider(P,D,O))return O;throw new Error("Illegal state.")}}function Cf(){var P={},D=[],q=(function(){function ft(ye,Ce,ke){this._index=0,this._keys=ye,this._values=Ce,this._selector=ke}return ft.prototype["@@iterator"]=function(){return this},ft.prototype[o]=function(){return this},ft.prototype.next=function(){var ye=this._index;if(ye>=0&&ye<this._keys.length){var Ce=this._selector(this._keys[ye],this._values[ye]);return ye+1>=this._keys.length?(this._index=-1,this._keys=D,this._values=D):this._index++,{value:Ce,done:!1}}return{value:void 0,done:!0}},ft.prototype.throw=function(ye){throw this._index>=0&&(this._index=-1,this._keys=D,this._values=D),ye},ft.prototype.return=function(ye){return this._index>=0&&(this._index=-1,this._keys=D,this._values=D),{value:ye,done:!0}},ft})(),de=(function(){function ft(){this._keys=[],this._values=[],this._cacheKey=P,this._cacheIndex=-2}return Object.defineProperty(ft.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ft.prototype.has=function(ye){return this._find(ye,!1)>=0},ft.prototype.get=function(ye){var Ce=this._find(ye,!1);return Ce>=0?this._values[Ce]:void 0},ft.prototype.set=function(ye,Ce){var ke=this._find(ye,!0);return this._values[ke]=Ce,this},ft.prototype.delete=function(ye){var Ce=this._find(ye,!1);if(Ce>=0){for(var ke=this._keys.length,Ne=Ce+1;Ne<ke;Ne++)this._keys[Ne-1]=this._keys[Ne],this._values[Ne-1]=this._values[Ne];return this._keys.length--,this._values.length--,bf(ye,this._cacheKey)&&(this._cacheKey=P,this._cacheIndex=-2),!0}return!1},ft.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=P,this._cacheIndex=-2},ft.prototype.keys=function(){return new q(this._keys,this._values,Me)},ft.prototype.values=function(){return new q(this._keys,this._values,$t)},ft.prototype.entries=function(){return new q(this._keys,this._values,Wt)},ft.prototype["@@iterator"]=function(){return this.entries()},ft.prototype[o]=function(){return this.entries()},ft.prototype._find=function(ye,Ce){if(!bf(this._cacheKey,ye)){this._cacheIndex=-1;for(var ke=0;ke<this._keys.length;ke++)if(bf(this._keys[ke],ye)){this._cacheIndex=ke;break}}return this._cacheIndex<0&&Ce&&(this._cacheIndex=this._keys.length,this._keys.push(ye),this._values.push(void 0)),this._cacheIndex},ft})();return de;function Me(ft,ye){return ft}function $t(ft,ye){return ye}function Wt(ft,ye){return[ft,ye]}}function n0(){var P=(function(){function D(){this._map=new h}return Object.defineProperty(D.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),D.prototype.has=function(q){return this._map.has(q)},D.prototype.add=function(q){return this._map.set(q,q),this},D.prototype.delete=function(q){return this._map.delete(q)},D.prototype.clear=function(){this._map.clear()},D.prototype.keys=function(){return this._map.keys()},D.prototype.values=function(){return this._map.keys()},D.prototype.entries=function(){return this._map.entries()},D.prototype["@@iterator"]=function(){return this.keys()},D.prototype[o]=function(){return this.keys()},D})();return P}function kx(){var P=16,D=u.create(),q=de();return(function(){function ye(){this._key=de()}return ye.prototype.has=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?u.has(ke,this._key):!1},ye.prototype.get=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?u.get(ke,this._key):void 0},ye.prototype.set=function(Ce,ke){var Ne=Me(Ce,!0);return Ne[this._key]=ke,this},ye.prototype.delete=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?delete ke[this._key]:!1},ye.prototype.clear=function(){this._key=de()},ye})();function de(){var ye;do ye="@@WeakMap@@"+ft();while(u.has(D,ye));return D[ye]=!0,ye}function Me(ye,Ce){if(!s.call(ye,q)){if(!Ce)return;Object.defineProperty(ye,q,{value:u.create()})}return ye[q]}function $t(ye,Ce){for(var ke=0;ke<Ce;++ke)ye[ke]=Math.random()*255|0;return ye}function Wt(ye){if(typeof Uint8Array=="function"){var Ce=new Uint8Array(ye);return typeof crypto<"u"?crypto.getRandomValues(Ce):typeof msCrypto<"u"?msCrypto.getRandomValues(Ce):$t(Ce,ye),Ce}return $t(new Array(ye),ye)}function ft(){var ye=Wt(P);ye[6]=ye[6]&79|64,ye[8]=ye[8]&191|128;for(var Ce="",ke=0;ke<P;++ke){var Ne=ye[ke];(ke===4||ke===6||ke===8)&&(Ce+="-"),Ne<16&&(Ce+="0"),Ce+=Ne.toString(16).toLowerCase()}return Ce}}function Ia(P){return P.__=void 0,delete P.__,P}})})(k6||(k6={}))});function B6(...r){let e=r.map(n=>n.byteLength).reduce((n,i)=>n+i),t=new Uint8Array(e),s=0;return r.map(n=>new Uint8Array(n)).forEach(n=>{for(let i of n)t[s++]=i}),t.buffer}function N6(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<r.byteLength;n++)if(t[n]!==s[n])return!1;return!0}var pM,be,Qb,mM,gM,yM,om,Hs,Ue,Zb=A(()=>{"use strict";pM="[object ArrayBuffer]",be=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===pM}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let s=r.toUint8Array(e),n=r.toUint8Array(t);if(s.length!==n.byteLength)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let s=0;for(let o of t)s+=o.byteLength;let n=new Uint8Array(s),i=0;for(let o of t){let a=this.toUint8Array(o);n.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}},Qb="string",mM=/^[0-9a-f\s]+$/i,gM=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,yM=/^[a-zA-Z0-9-_]+$/,om=class{static fromString(e){let t=unescape(encodeURIComponent(e)),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s.buffer}static toString(e){let t=be.toUint8Array(e),s="";for(let i=0;i<t.length;i++)s+=String.fromCharCode(t[i]);return decodeURIComponent(escape(s))}},Hs=class{static toString(e,t=!1){let s=be.toArrayBuffer(e),n=new DataView(s),i="";for(let o=0;o<s.byteLength;o+=2){let a=n.getUint16(o,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let s=new ArrayBuffer(e.length*2),n=new DataView(s);for(let i=0;i<e.length;i++)n.setUint16(i*2,e.charCodeAt(i),t);return s}},Ue=class r{static isHex(e){return typeof e===Qb&&mM.test(e)}static isBase64(e){return typeof e===Qb&&gM.test(e)}static isBase64Url(e){return typeof e===Qb&&yM.test(e)}static ToString(e,t="utf8"){let s=be.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(s);case"binary":return this.ToBinary(s);case"hex":return this.ToHex(s);case"base64":return this.ToBase64(s);case"base64url":return this.ToBase64Url(s);case"utf16le":return Hs.toString(s,!0);case"utf16":case"utf16be":return Hs.toString(s);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Hs.fromString(e,!0);case"utf16":case"utf16be":return Hs.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=be.toUint8Array(e);if(typeof btoa<"u"){let s=this.ToString(t,"binary");return btoa(s)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return om.fromString(e);case"utf16":case"utf16be":return Hs.fromString(e);case"utf16le":case"usc2":return Hs.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return om.toString(e);case"utf16":case"utf16be":return Hs.toString(e);case"utf16le":case"usc2":return Hs.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);return s.buffer}static ToBinary(e){let t=be.toUint8Array(e),s="";for(let n=0;n<t.length;n++)s+=String.fromCharCode(t[n]);return s}static ToHex(e){let t=be.toUint8Array(e),s="",n=t.length;for(let i=0;i<n;i++){let o=t[i];o<16&&(s+="0"),s+=o.toString(16)}return s}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let s=new Uint8Array(t.length/2);for(let n=0;n<t.length;n=n+2){let i=t.slice(n,n+2);s[n/2]=parseInt(i,16)}return s.buffer}static ToUtf16String(e,t=!1){return Hs.toString(e,t)}static FromUtf16String(e,t=!1){return Hs.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let s=0;s<t;s++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ue.DEFAULT_UTF8_ENCODING="utf8"});function Ma(r,e){let t=0;if(r.length===1)return r[0];for(let s=r.length-1;s>=0;s--)t+=r[r.length-1-s]*Math.pow(2,e*s);return t}function Ao(r,e,t=-1){let s=t,n=r,i=0,o=Math.pow(2,e);for(let a=1;a<8;a++){if(r<o){let c;if(s<0)c=new ArrayBuffer(a),i=a;else{if(s<a)return new ArrayBuffer(0);c=new ArrayBuffer(s),i=s}let d=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);d[i-u-1]=Math.floor(n/f),n-=d[i-u-1]*f}return c}o*=Math.pow(2,e)}return new ArrayBuffer(0)}function am(...r){let e=0,t=0;for(let i of r)e+=i.length;let s=new ArrayBuffer(e),n=new Uint8Array(s);for(let i of r)n.set(i,t),t+=i.length;return n}function e1(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let s=Ma(t,8),n=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(n);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,Ma(i,8)-s}function O6(r){let e=r<0?r*-1:r,t=128;for(let s=1;s<8;s++){if(e<=t){if(r<0){let o=t-e,a=Ao(o,8,s),c=new Uint8Array(a);return c[0]|=128,a}let n=Ao(e,8,s),i=new Uint8Array(n);if(i[0]&128){let o=n.slice(0),a=new Uint8Array(o);n=new ArrayBuffer(n.byteLength+1),i=new Uint8Array(n);for(let c=0;c<o.byteLength;c++)i[c+1]=a[c];i[0]=0}return n}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function L6(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<t.length;n++)if(t[n]!==s[n])return!1;return!0}function cs(r,e){let t=r.toString(10);if(e<t.length)return"";let s=e-t.length,n=new Array(s);for(let o=0;o<s;o++)n[o]="0";return n.join("").concat(t)}var oW,D6=A(()=>{"use strict";oW=Math.log(2)});var Hn={};Tf(Hn,{Any:()=>Mn,BaseBlock:()=>ur,BaseStringBlock:()=>Jf,BitString:()=>an,BmpString:()=>Fa,Boolean:()=>Ua,CharacterString:()=>Ya,Choice:()=>qd,Constructed:()=>fr,DATE:()=>sl,DEFAULT_MAX_CONTENT_LENGTH:()=>K6,DEFAULT_MAX_DEPTH:()=>$6,DEFAULT_MAX_NODES:()=>V6,DateTime:()=>il,Duration:()=>ol,EndOfContent:()=>Qf,Enumerated:()=>ja,GeneralString:()=>Xa,GeneralizedTime:()=>Ja,GraphicString:()=>Ga,HexBlock:()=>jn,IA5String:()=>Wa,Integer:()=>Ai,Null:()=>nn,NumericString:()=>za,ObjectIdentifier:()=>Ha,OctetString:()=>on,Primitive:()=>Ti,PrintableString:()=>$a,RawData:()=>r1,RelativeObjectIdentifier:()=>rl,Repeated:()=>Qa,Sequence:()=>Vr,Set:()=>es,TIME:()=>al,TeletexString:()=>Va,TimeOfDay:()=>nl,UTCTime:()=>Ro,UniversalString:()=>qa,Utf8String:()=>Fs,ValueBlock:()=>Er,VideotexString:()=>Ka,ViewWriter:()=>Fd,VisibleString:()=>Io,compareSchema:()=>Ei,fromBER:()=>Ri,verifySchema:()=>UM});function cm(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function s1(r){let e=0,t=0;for(let n=0;n<r.length;n++){let i=r[n];e+=i.byteLength}let s=new Uint8Array(e);for(let n=0;n<r.length;n++){let i=r[n];s.set(new Uint8Array(i),t),t+=i.byteLength}return s.buffer}function Ii(r,e,t,s){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):s<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-s<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}function jn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(s){this.valueHexView=new Uint8Array(s)}constructor(...s){var n;super(...s);let i=s[0]||{};this.isHexOnly=(n=i.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=i.valueHex?be.toUint8Array(i.valueHex):_m}fromBER(s,n,i,o){let a=s instanceof ArrayBuffer?new Uint8Array(s):s;if(!Ii(this,a,n,i))return-1;let c=n+i;return this.valueHexView=a.subarray(n,c),this.valueHexView.length?(this.blockLength=i,c):(this.warnings.push("Zero buffer length"),n)}toBER(s=!1){return this.isHexOnly?s?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Un)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ue.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}function q6(r){var e;if(r instanceof Ae.Constructed)for(let t of r.valueBlock.value)q6(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}function cl(r={}){var e,t,s;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:$6,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:V6,maxContentLength:(s=r.maxContentLength)!==null&&s!==void 0?s:K6}}function PM(r){let e=new ur({},Er);return e.error=r,{offset:-1,result:e}}function BM(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return RM}function NM(r,e){if(r>e.maxContentLength)return kM}function n1(r,e,t,s){let n=s.depth+1;if(n>s.maxDepth)return PM(IM);s.depth=n;try{return Em(r,e,t,s)}finally{s.depth-=1}}function OM(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Em(r,e=0,t=r.length,s=cl()){let n=e,i=new ur({},Er),o=new Ci;if(!Ii(o,r,e,t))return i.error=o.error,{offset:-1,result:i};if(!r.subarray(e,e+t).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=BM(s);if(c)return i.error=c,{offset:-1,result:i};let d=i.idBlock.fromBER(r,e,t);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),d===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=d,t-=i.idBlock.blockLength,d=i.lenBlock.fromBER(r,e,t),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),d===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=d,t-=i.lenBlock.blockLength;let u=i.lenBlock.isIndefiniteForm?t:i.lenBlock.length,f=NM(u,s);if(f)return i.error=f,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let h=ur;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};h=Ae.EndOfContent;break;case 1:h=Ae.Boolean;break;case 2:h=Ae.Integer;break;case 3:h=Ae.BitString;break;case 4:h=Ae.OctetString;break;case 5:h=Ae.Null;break;case 6:h=Ae.ObjectIdentifier;break;case 10:h=Ae.Enumerated;break;case 12:h=Ae.Utf8String;break;case 13:h=Ae.RelativeObjectIdentifier;break;case 14:h=Ae.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:h=Ae.Sequence;break;case 17:h=Ae.Set;break;case 18:h=Ae.NumericString;break;case 19:h=Ae.PrintableString;break;case 20:h=Ae.TeletexString;break;case 21:h=Ae.VideotexString;break;case 22:h=Ae.IA5String;break;case 23:h=Ae.UTCTime;break;case 24:h=Ae.GeneralizedTime;break;case 25:h=Ae.GraphicString;break;case 26:h=Ae.VisibleString;break;case 27:h=Ae.GeneralString;break;case 28:h=Ae.UniversalString;break;case 29:h=Ae.CharacterString;break;case 30:h=Ae.BmpString;break;case 31:h=Ae.DATE;break;case 32:h=Ae.TimeOfDay;break;case 33:h=Ae.DateTime;break;case 34:h=Ae.Duration;break;default:{let y=i.idBlock.isConstructed?new Ae.Constructed:new Ae.Primitive;y.idBlock=i.idBlock,y.lenBlock=i.lenBlock,y.warnings=i.warnings,i=y}}break;default:h=i.idBlock.isConstructed?Ae.Constructed:Ae.Primitive}return i=OM(i,h),d=i.fromBER(r,e,u,s),i.valueBeforeDecodeView=r.subarray(n,n+i.blockLength),{offset:d,result:i}}function Ri(r,e={}){if(!r.byteLength){let t=new ur({},Er);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Em(be.toUint8Array(r).slice(),0,r.byteLength,cl(e))}function LM(r,e){return r?1:e}function DM(r,e){let t=new Uint8Array([0]),s=new Uint8Array(r),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d=0,u=c<o?o:c,f=0;for(let h=u;h>=0;h--,f++)!0===f<a.length?d=i[o-f]+a[c-f]+t[0]:d=i[o-f]+t[0],t[0]=d/10,!0===f>=i.length?i=am(new Uint8Array([d%10]),i):i[o-f]=d%10;return t[0]>0&&(i=am(t,i)),i}function j6(r){if(r>=Gf.length)for(let e=Gf.length;e<=r;e++){let t=new Uint8Array([0]),s=Gf[e-1].slice(0);for(let n=s.length-1;n>=0;n--){let i=new Uint8Array([(s[n]<<1)+t[0]]);t[0]=i[0]/10,s[n]=i[0]%10}t[0]>0&&(s=am(t,s)),Gf.push(s)}return Gf[r]}function MM(r,e){let t=0,s=new Uint8Array(r),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d,u=0;for(let f=c;f>=0;f--,u++)d=i[o-u]-a[c-u]-t,!0===d<0?(t=1,i[o-u]=d+10):(t=0,i[o-u]=d);if(t>0)for(let f=o-c+1;f>=0;f--,u++)if(d=i[o-u]-t,d<0)t=1,i[o-u]=d+10;else{t=0,i[o-u]=d;break}return i.slice()}function Ei(r,e,t){if(t instanceof qd){for(let i of t.value)if(Ei(r,e,i).verified)return{verified:!0,result:r};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(t1)&&(i.name=t.name),i}}if(t instanceof Mn)return t.hasOwnProperty(t1)&&(r[t.name]=e),{verified:!0,result:r};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(wM in t))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(CM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(TM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let s=t.idBlock.toBER(!1);if(s.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(t.idBlock.fromBER(s,0,s.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(t.idBlock.hasOwnProperty(SM)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(_M)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(EM)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:r};if(!(vM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:r};if(t.idBlock.isHexOnly){if(!(U6 in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=t.idBlock.valueHexView,o=e.idBlock.valueHexView;if(i.length!==o.length)return{verified:!1,result:r};for(let a=0;a<i.length;a++)if(i[a]!==o[1])return{verified:!1,result:r}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(r[t.name]=e)),t instanceof Ae.Constructed){let i=0,o={verified:!1,result:{error:"Unknown error"}},a=t.valueBlock.value.length;if(a>0&&t.valueBlock.value[0]instanceof Qa&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:r};if(e.valueBlock.value.length===0&&t.valueBlock.value.length!==0){let c=!0;for(let d=0;d<t.valueBlock.value.length;d++)c=c&&(t.valueBlock.value[d].optional||!1);return c?{verified:!0,result:r}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),r.error="Inconsistent object length",{verified:!1,result:r})}for(let c=0;c<a;c++)if(c-i>=e.valueBlock.value.length){if(t.valueBlock.value[c].optional===!1){let d={verified:!1,result:r};return r.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],d.name=t.name)),d}}else if(t.valueBlock.value[0]instanceof Qa){if(o=Ei(r,e.valueBlock.value[c],t.valueBlock.value[0].value),o.verified===!1)if(t.valueBlock.value[0].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),o;if(t1 in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let d={};AM in t.valueBlock.value[0]&&t.valueBlock.value[0].local?d=e:d=r,typeof d[t.valueBlock.value[0].name]>"u"&&(d[t.valueBlock.value[0].name]=[]),d[t.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(o=Ei(r,e.valueBlock.value[c-i],t.valueBlock.value[c]),o.verified===!1)if(t.valueBlock.value[c].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),o;if(o.verified===!1){let c={verified:!1,result:r};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],c.name=t.name)),c}return{verified:!0,result:r}}if(t.primitiveSchema&&U6 in e.valueBlock){let i=Em(e.valueBlock.valueHexView);if(i.offset===-1){let o={verified:!1,result:i.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],o.name=t.name)),o}return Ei(r,i.result,t.primitiveSchema)}return{verified:!0,result:r}}function UM(r,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let t=Em(be.toUint8Array(r));return t.offset===-1?{verified:!1,result:t.result}:Ei(t.result,t.result,e)}var Fd,Gf,M6,t1,U6,vM,wM,SM,_M,EM,CM,TM,AM,ds,Un,_m,Yf,H6,F6,Ci,Er,dm,um,Ae,ur,Jf,fm,z6,Ti,$6,V6,K6,IM,RM,kM,Dn,W6,fr,lm,G6,Qf,X6,nn,hm,Y6,Ua,pm,i1,on,mm,J6,an,Q6,Zf,Xf,Ai,Z6,ja,el,gm,e3,Ha,tl,ym,t3,rl,r3,Vr,s3,es,xm,bm,ts,vm,n3,Fs,wm,i3,Fa,Sm,o3,qa,a3,za,c3,$a,d3,Va,u3,Ka,f3,Wa,l3,Ga,h3,Io,p3,Xa,m3,Ya,g3,Ro,y3,Ja,x3,sl,b3,nl,v3,il,w3,ol,S3,al,Mn,qd,Qa,r1,ko=A(()=>{"use strict";Zb();D6();Fd=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return s1(this.items)}},Gf=[new Uint8Array([1])],M6="0123456789",t1="name",U6="valueHexView",vM="isHexOnly",wM="idBlock",SM="tagClass",_M="tagNumber",EM="isConstructed",CM="fromBER",TM="toBER",AM="local",ds="",Un=new ArrayBuffer(0),_m=new Uint8Array(0),Yf="EndOfContent",H6="OCTET STRING",F6="BIT STRING";Ci=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=ds,warnings:s=[],valueBeforeDecode:n=_m}={}){this.blockLength=e,this.error=t,this.warnings=s,this.valueBeforeDecodeView=be.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ue.ToHex(this.valueBeforeDecodeView)}}};Ci.NAME="baseBlock";Er=class extends Ci{fromBER(e,t,s,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Er.NAME="valueBlock";dm=class extends jn(Ci){constructor({idBlock:e={}}={}){var t,s,n,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?be.toUint8Array(e.valueHex):_m,this.tagClass=(s=e.tagClass)!==null&&s!==void 0?s:-1,this.tagNumber=(n=e.tagNumber)!==null&&n!==void 0?n:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Un}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=Ao(this.tagNumber,7),i=new Uint8Array(n),o=n.byteLength,a=new Uint8Array(o+1);if(a[0]=t|31,!e){for(let c=0;c<o-1;c++)a[c+1]=i[c]|128;a[o]=i[o-1]}return a.buffer}let s=new Uint8Array(this.valueHexView.byteLength+1);if(s[0]=t|31,!e){let n=this.valueHexView;for(let i=0;i<n.length-1;i++)s[i+1]=n[i]|128;s[this.valueHexView.byteLength]=n[n.length-1]}return s.buffer}fromBER(e,t,s){let n=be.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[u]&128)===0)break}this.blockLength=c+1;let d=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)d[u]=i[u+1]&127;this.blockLength<=9?this.tagNumber=Ma(d,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};dm.NAME="identificationBlock";um=class extends Ci{constructor({lenBlock:e={}}={}){var t,s,n;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(s=e.longFormUsed)!==null&&s!==void 0?s:!1,this.length=(n=e.length)!==null&&n!==void 0?n:0}fromBER(e,t,s){let n=be.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let o=i[0]&127;if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=n.subarray(a,a+o);return c[o-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ma(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(e=!1){let t,s;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(t),s[0]=128),t;if(this.longFormUsed){let n=Ao(this.length,8);if(n.byteLength>127)return this.error="Too big length",Un;if(t=new ArrayBuffer(n.byteLength+1),e)return t;let i=new Uint8Array(n);s=new Uint8Array(t),s[0]=n.byteLength|128;for(let o=0;o<n.byteLength;o++)s[o+1]=i[o];return t}return t=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(t),s[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};um.NAME="lengthBlock";Ae={},ur=class extends Ci{constructor({name:e=ds,optional:t=!1,primitiveSchema:s,...n}={},i){super(n),this.name=e,this.optional=t,s&&(this.primitiveSchema=s),this.idBlock=new dm(n),this.lenBlock=new um(n),this.valueBlock=i?new i(n):new Er(n)}fromBER(e,t,s,n){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(e,t){let s=t||new Fd;t||q6(this);let n=this.idBlock.toBER(e);if(s.write(n),this.lenBlock.isIndefiniteForm)s.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,s),s.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let o=this.lenBlock.toBER(e);s.write(o),s.write(i)}return t?Un:s.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():Ue.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=Ue.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),s=e.toBER();return L6(t,s)}};ur.NAME="BaseBlock";Jf=class extends ur{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ds,...t}={},s){super(t,s),e&&this.fromString(e)}fromBER(e,t,s){let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return n===-1?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Jf.NAME="BaseStringBlock";fm=class extends jn(Er){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};fm.NAME="PrimitiveValueBlock";Ti=class extends ur{constructor(e={}){super(e,fm),this.idBlock.isConstructed=!1}};z6=Ti;Ae.Primitive=z6;Ti.NAME="PRIMITIVE";$6=100,V6=1e4,K6=16*1024*1024,IM="Maximum ASN.1 nesting depth exceeded",RM="Maximum ASN.1 node count exceeded",kM="Maximum ASN.1 content length exceeded";Dn=class extends Er{constructor({value:e=[],isIndefiniteForm:t=!1,...s}={}){super(s),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,s,n){let i=be.toUint8Array(e),o=n??cl();if(!Ii(this,i,t,s))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+s),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;LM(this.isIndefiniteForm,s)>0;){let c=n1(i,a,s,o);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,s-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Yf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let s=t||new Fd;for(let n=0;n<this.value.length;n++)this.value[n].toBER(e,s);return t?Un:s.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Dn.NAME="ConstructedValueBlock";fr=class extends ur{constructor(e={}){super(e,Dn),this.idBlock.isConstructed=!0}fromBER(e,t,s,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){let e=[];for(let s of this.valueBlock.value)e.push(s.toString("ascii").split(`
19
- `).map(n=>` ${n}`).join(`
20
- `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
21
- ${e.join(`
22
- `)}`:`${t} :`}};W6=fr;Ae.Constructed=W6;fr.NAME="CONSTRUCTED";lm=class extends Er{fromBER(e,t,s){return t}toBER(e){return Un}};lm.override="EndOfContentValueBlock";Qf=class extends ur{constructor(e={}){super(e,lm),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};G6=Qf;Ae.EndOfContent=G6;Qf.NAME=Yf;nn=class extends ur{constructor(e={}){super(e,Er),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,s){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=s,t+s>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+s}toBER(e,t){let s=new ArrayBuffer(2);if(!e){let n=new Uint8Array(s);n[0]=5,n[1]=0}return t&&t.write(s),s}onAsciiEncoding(){return`${this.constructor.NAME}`}};X6=nn;Ae.Null=X6;nn.NAME="NULL";hm=class extends jn(Er){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=be.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,s){let n=be.toUint8Array(e);return Ii(this,n,t,s)?(this.valueHexView=n.subarray(t,t+s),s>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,e1.call(this),this.blockLength=s,t+s):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};hm.NAME="BooleanValueBlock";Ua=class extends ur{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,hm),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Y6=Ua;Ae.Boolean=Y6;Ua.NAME="BOOLEAN";pm=class extends jn(Dn){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,s,n){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=Dn.prototype.fromBER.call(this,e,t,s,n),i===-1)return i;for(let o=0;o<this.value.length;o++){let a=this.value[o].constructor.NAME;if(a===Yf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==H6)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,s),this.blockLength=s;return i}toBER(e,t){return this.isConstructed?Dn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};pm.NAME="OctetStringValueBlock";on=class extends ur{constructor({idBlock:e={},lenBlock:t={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},pm),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,s,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,s===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+s);try{if(o.byteLength){let a=n??cl(),c=n1(o,0,o.byteLength,a);c.offset!==-1&&c.offset===s&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fr.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=Ue.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof i1&&e.push(t.valueBlock.valueHexView);return be.concat(e)}};i1=on;Ae.OctetString=i1;on.NAME=H6;mm=class extends jn(Dn){constructor({unusedBits:e=0,isConstructed:t=!1,...s}={}){super(s),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,s,n){if(!s)return t;let i=-1;if(this.isConstructed){if(i=Dn.prototype.fromBER.call(this,e,t,s,n),i===-1)return i;for(let c of this.value){let d=c.constructor.NAME;if(d===Yf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(d!==F6)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return i}let o=be.toUint8Array(e);if(!Ii(this,o,t,s))return-1;let a=o.subarray(t,t+s);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let d=n??cl(),u=n1(c,0,c.byteLength,d);u.offset!==-1&&u.offset===s-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+s}toBER(e,t){if(this.isConstructed)return Dn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let n=new Uint8Array(1);return n[0]=0,n.buffer}let s=new Uint8Array(this.valueHexView.length+1);return s[0]=this.unusedBits,s.set(this.valueHexView,1),s.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};mm.NAME="BitStringValueBlock";an=class extends ur{constructor({idBlock:e={},lenBlock:t={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},mm),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,s,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let s=e.join(""),n=this.constructor.NAME,i=s.substring(0,s.length-this.valueBlock.unusedBits);return`${n} : ${i}`}}};J6=an;Ae.BitString=J6;an.NAME=F6;Zf=class extends jn(Er){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=e1.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(O6(e))}get valueDec(){return this._valueDec}fromDER(e,t,s,n=0){let i=this.fromBER(e,t,s);if(i===-1)return i;let o=this.valueHexView;return o[0]===0&&(o[1]&128)!==0?this.valueHexView=o.subarray(1):n!==0&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let s=new Uint8Array(this.valueHexView.length+1);s[0]=0,s.set(t,1),this.valueHexView=s}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,s){let n=super.fromBER(e,t,s);return n===-1||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),s=0,n,i=this.valueHexView,o="",a=!1;for(let c=i.byteLength-1;c>=0;c--){n=i[c];for(let d=0;d<8;d++)(n&1)===1&&(s===e?(t=MM(j6(s),t),o="-"):t=DM(t,j6(s))),s++,n>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(o+=M6.charAt(t[c]));return a===!1&&(o+=M6.charAt(0)),o}};Q6=Zf;Zf.NAME="IntegerValueBlock";Object.defineProperty(Q6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});Ai=class extends ur{constructor(e={}){super(e,Zf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return cm(),BigInt(this.valueBlock.toString())}static fromBigInt(e){cm();let t=BigInt(e),s=new Fd,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(Ue.FromHex(n));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let d=BigInt(`0x${Ue.ToHex(a)}`)+t,u=be.toUint8Array(Ue.FromHex(d.toString(16)));u[0]|=128,s.write(u)}else i[0]&128&&s.write(new Uint8Array([0])),s.write(i);return new Xf({valueHex:s.final()})}convertToDER(){let e=new Xf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Xf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Xf=Ai;Ae.Integer=Xf;Ai.NAME="INTEGER";ja=class extends Ai{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Z6=ja;Ae.Enumerated=Z6;ja.NAME="ENUMERATED";el=class extends jn(Er){constructor({valueDec:e=-1,isFirstSid:t=!1,...s}={}){super(s),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,s){if(!s)return t;let n=be.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ma(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){cm();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let s=new Uint8Array(t.length/7);for(let n=0;n<s.length;n++)s[n]=parseInt(t.slice(n*7,n*7+7),2)+(n+1<s.length?128:0);this.fromBER(s.buffer,0,s.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Un;let s=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s}toString(){let e="";if(this.isHexOnly)e=Ue.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};el.NAME="sidBlock";gm=class extends Er{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let n=t;for(;s>0;){let i=new el;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e){let t=[];for(let s=0;s<this.value.length;s++){let n=this.value[s].toBER(e);if(n.byteLength===0)return this.error=this.value[s].error,Un;t.push(n)}return s1(t)}fromString(e){this.value=[];let t=0,s=0,n="",i=!1;do if(s=e.indexOf(".",t),s===-1?n=e.substring(t):n=e.substring(t,s),t=s+1,i){let o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(n,10);if(isNaN(c))return;o.valueDec=c+a,i=!1}else{let o=new el;if(n>Number.MAX_SAFE_INTEGER){cm();let a=BigInt(n);o.valueBigInt=a}else if(o.valueDec=parseInt(n,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(s!==-1)}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),t?(n=`{${n}}`,this.value[s].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};gm.NAME="ObjectIdentifierValueBlock";Ha=class extends ur{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,gm),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};e3=Ha;Ae.ObjectIdentifier=e3;Ha.NAME="OBJECT IDENTIFIER";tl=class extends jn(Ci){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,s){if(s===0)return t;let n=be.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ma(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Un;let s=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s.buffer}toString(){let e="";return this.isHexOnly?e=Ue.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};tl.NAME="relativeSidBlock";ym=class extends Er{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let n=t;for(;s>0;){let i=new tl;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e,t){let s=[];for(let n=0;n<this.value.length;n++){let i=this.value[n].toBER(e);if(i.byteLength===0)return this.error=this.value[n].error,Un;s.push(i)}return s1(s)}fromString(e){this.value=[];let t=0,s=0,n="";do{s=e.indexOf(".",t),s===-1?n=e.substring(t):n=e.substring(t,s),t=s+1;let i=new tl;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(s!==-1);return!0}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),t&&(n=`{${n}}`),e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ym.NAME="RelativeObjectIdentifierValueBlock";rl=class extends ur{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ym),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};t3=rl;Ae.RelativeObjectIdentifier=t3;rl.NAME="RelativeObjectIdentifier";Vr=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};r3=Vr;Ae.Sequence=r3;Vr.NAME="SEQUENCE";es=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};s3=es;Ae.Set=s3;es.NAME="SET";xm=class extends jn(Er){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ds}toJSON(){return{...super.toJSON(),value:this.value}}};xm.NAME="StringValueBlock";bm=class extends xm{};bm.NAME="SimpleStringValueBlock";ts=class extends Jf{constructor({...e}={}){super(e,bm)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,be.toUint8Array(e))}fromString(e){let t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);this.valueBlock.value=e}};ts.NAME="SIMPLE STRING";vm=class extends ts{fromBuffer(e){this.valueBlock.valueHexView=be.toUint8Array(e);try{this.valueBlock.value=Ue.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Ue.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ue.FromUtf8String(e)),this.valueBlock.value=e}};vm.NAME="Utf8StringValueBlock";Fs=class extends vm{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};n3=Fs;Ae.Utf8String=n3;Fs.NAME="UTF8String";wm=class extends ts{fromBuffer(e){this.valueBlock.value=Ue.ToUtf16String(e),this.valueBlock.valueHexView=be.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ue.FromUtf16String(e))}};wm.NAME="BmpStringValueBlock";Fa=class extends wm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};i3=Fa;Ae.BmpString=i3;Fa.NAME="BMPString";Sm=class extends ts{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),s=new Uint8Array(t);for(let n=0;n<s.length;n+=4)s[n]=s[n+3],s[n+1]=s[n+2],s[n+2]=0,s[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let n=0;n<t;n++){let i=Ao(e.charCodeAt(n),8),o=new Uint8Array(i);if(o.length>4)continue;let a=4-o.length;for(let c=o.length-1;c>=0;c--)s[n*4+c+a]=o[c]}this.valueBlock.value=e}};Sm.NAME="UniversalStringValueBlock";qa=class extends Sm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};o3=qa;Ae.UniversalString=o3;qa.NAME="UniversalString";za=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};a3=za;Ae.NumericString=a3;za.NAME="NumericString";$a=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};c3=$a;Ae.PrintableString=c3;$a.NAME="PrintableString";Va=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};d3=Va;Ae.TeletexString=d3;Va.NAME="TeletexString";Ka=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};u3=Ka;Ae.VideotexString=u3;Ka.NAME="VideotexString";Wa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};f3=Wa;Ae.IA5String=f3;Wa.NAME="IA5String";Ga=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};l3=Ga;Ae.GraphicString=l3;Ga.NAME="GraphicString";Io=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};h3=Io;Ae.VisibleString=h3;Io.NAME="VisibleString";Xa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};p3=Xa;Ae.GeneralString=p3;Xa.NAME="GeneralString";Ya=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};m3=Ya;Ae.CharacterString=m3;Ya.NAME="CharacterString";Ro=class extends Io{constructor({value:e,valueDate:t,...s}={}){if(super(s),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let n=0;n<e.length;n++)this.valueBlock.valueHexView[n]=e.charCodeAt(n)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,be.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),s=new Uint8Array(t);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let s=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(s===null){this.error="Wrong input string for conversion";return}let n=parseInt(s[1],10);n>=50?this.year=1900+n:this.year=2e3+n,this.month=parseInt(s[2],10),this.day=parseInt(s[3],10),this.hour=parseInt(s[4],10),this.minute=parseInt(s[5],10),this.second=parseInt(s[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=cs(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=cs(this.month,2),t[2]=cs(this.day,2),t[3]=cs(this.hour,2),t[4]=cs(this.minute,2),t[5]=cs(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};g3=Ro;Ae.UTCTime=g3;Ro.NAME="UTCTime";Ja=class extends Ro{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,s="",n="",i=0,o,a=0,c=0;if(e[e.length-1]==="Z")s=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(t){if(s.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(s.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,h=s.indexOf("+"),y="";if(h===-1&&(h=s.indexOf("-"),f=-1),h!==-1){if(y=s.substring(h+1),s=s.substring(0,h),y.length!==2&&y.length!==4)throw new Error("Wrong input string for conversion");let v=parseInt(y.substring(0,2),10);if(isNaN(v.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*v,y.length===4){if(v=parseInt(y.substring(2,4),10),isNaN(v.valueOf()))throw new Error("Wrong input string for conversion");c=f*v}}}let d=s.indexOf(".");if(d===-1&&(d=s.indexOf(",")),d!==-1){let f=new Number(`0${s.substring(d)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),n=s.substring(0,d)}else n=s;switch(!0){case n.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,d!==-1)throw new Error("Wrong input string for conversion");break;case n.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case n.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case n.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=o.exec(n);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(cs(this.year,4)),t.push(cs(this.month,2)),t.push(cs(this.day,2)),t.push(cs(this.hour,2)),t.push(cs(this.minute,2)),t.push(cs(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(cs(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};y3=Ja;Ae.GeneralizedTime=y3;Ja.NAME="GeneralizedTime";sl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};x3=sl;Ae.DATE=x3;sl.NAME="DATE";nl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};b3=nl;Ae.TimeOfDay=b3;nl.NAME="TimeOfDay";il=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};v3=il;Ae.DateTime=v3;il.NAME="DateTime";ol=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};w3=ol;Ae.Duration=w3;ol.NAME="Duration";al=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};S3=al;Ae.TIME=S3;al.NAME="TIME";Mn=class{constructor({name:e=ds,optional:t=!1}={}){this.name=e,this.optional=t}},qd=class extends Mn{constructor({value:e=[],...t}={}){super(t),this.value=e}},Qa=class extends Mn{constructor({value:e=new Mn,local:t=!1,...s}={}){super(s),this.value=e,this.local=t}},r1=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=be.toUint8Array(e)}constructor({data:e=_m}={}){this.dataView=be.toUint8Array(e)}fromBER(e,t,s){let n=t+s;return this.dataView=be.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}}});function _3(r){return Object.prototype.toString.call(r)}function FM(r){if(ArrayBuffer.isView(r))return!0;if(!r||typeof r!="object")return!1;let e=r;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&Cm(e.buffer)}function o1(r){return _3(r)===jM}function E3(r){return typeof SharedArrayBuffer<"u"&&_3(r)===HM}function Cm(r){return o1(r)||E3(r)}function C3(r){return FM(r)}function ki(r){return Cm(r)||C3(r)}function a1(r){if(!ki(r))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function qs(r){return a1(r),Cm(r)?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function vr(r){if(a1(r),o1(r))return r;let e=new ArrayBuffer(r.byteLength);return new Uint8Array(e).set(qs(r)),e}var jM,HM,dl=A(()=>{"use strict";jM="[object ArrayBuffer]",HM="[object SharedArrayBuffer]"});var T3=A(()=>{"use strict";dl()});function c1(r,e,t={}){let s=qs(r),n=qs(e);if(!t.constantTime&&s.byteLength!==n.byteLength)return!1;let i=Math.max(s.byteLength,n.byteLength),o=s.byteLength^n.byteLength;for(let a=0;a<i;a++)o|=(s[a]??0)^(n[a]??0);return o===0}var A3=A(()=>{"use strict";dl()});var I3=A(()=>{"use strict";dl()});var Cs=A(()=>{"use strict";dl();T3();A3();I3()});var B,_,Za=A(()=>{"use strict";(function(r){r[r.Sequence=0]="Sequence",r[r.Set=1]="Set",r[r.Choice=2]="Choice"})(B||(B={}));(function(r){r[r.Any=1]="Any",r[r.Boolean=2]="Boolean",r[r.OctetString=3]="OctetString",r[r.BitString=4]="BitString",r[r.Integer=5]="Integer",r[r.Enumerated=6]="Enumerated",r[r.ObjectIdentifier=7]="ObjectIdentifier",r[r.Utf8String=8]="Utf8String",r[r.BmpString=9]="BmpString",r[r.UniversalString=10]="UniversalString",r[r.NumericString=11]="NumericString",r[r.PrintableString=12]="PrintableString",r[r.TeletexString=13]="TeletexString",r[r.VideotexString=14]="VideotexString",r[r.IA5String=15]="IA5String",r[r.GraphicString=16]="GraphicString",r[r.VisibleString=17]="VisibleString",r[r.GeneralString=18]="GeneralString",r[r.CharacterString=19]="CharacterString",r[r.UTCTime=20]="UTCTime",r[r.GeneralizedTime=21]="GeneralizedTime",r[r.DATE=22]="DATE",r[r.TimeOfDay=23]="TimeOfDay",r[r.DateTime=24]="DateTime",r[r.Duration=25]="Duration",r[r.TIME=26]="TIME",r[r.Null=27]="Null"})(_||(_={}))});var Fn,R3=A(()=>{"use strict";ko();Cs();Fn=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(ki(e))this.unusedBits=t,this.value=vr(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof an))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=vr(e.valueBlock.valueHex),this}toASN(){return new an({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new an({name:e})}toNumber(){let e="",t=new Uint8Array(this.value);for(let s of t)e+=s.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2),s=t.length+7>>3;this.unusedBits=(s<<3)-t.length;let n=new Uint8Array(s);t=t.padStart(s<<3,"0").split("").reverse().join("");let i=0;for(;i<s;)n[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=n.buffer}}});var ze,k3=A(()=>{"use strict";ko();Cs();ze=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):ki(e)?this.buffer=vr(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof on))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=vr(e.valueBlock.valueHex),this}toASN(){return new on({valueHex:this.buffer})}toSchema(e){return new on({name:e})}}});var d1=A(()=>{"use strict";R3();k3()});function zs(r){return{fromASN:e=>e.valueBlock.value,toASN:e=>new r({value:e})}}function Po(r){switch(r){case _.Any:return $M;case _.BitString:return WM;case _.BmpString:return YM;case _.Boolean:return XM;case _.CharacterString:return oU;case _.Enumerated:return KM;case _.GeneralString:return iU;case _.GeneralizedTime:return cU;case _.GraphicString:return sU;case _.IA5String:return rU;case _.Integer:return VM;case _.Null:return dU;case _.NumericString:return QM;case _.ObjectIdentifier:return GM;case _.OctetString:return zd;case _.PrintableString:return ZM;case _.TeletexString:return eU;case _.UTCTime:return aU;case _.UniversalString:return JM;case _.Utf8String:return u1;case _.VideotexString:return tU;case _.VisibleString:return nU;default:return null}}var $M,VM,KM,Ct,WM,GM,XM,zd,P3,u1,YM,JM,QM,ZM,eU,tU,rU,sU,nU,iU,oU,aU,cU,dU,ul=A(()=>{"use strict";ko();Cs();Za();d1();$M={fromASN:r=>r instanceof nn?null:vr(r.valueBeforeDecodeView),toASN:r=>{if(r===null)return new nn;let e=Ri(r);if(e.result.error)throw new Error(e.result.error);return e.result}},VM={fromASN:r=>r.valueBlock.valueHexView.byteLength>=4?r.valueBlock.toString():r.valueBlock.valueDec,toASN:r=>new Ai({value:+r})},KM={fromASN:r=>r.valueBlock.valueDec,toASN:r=>new ja({value:r})},Ct={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new Ai({valueHex:r})},WM={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new an({valueHex:r})},GM={fromASN:r=>r.valueBlock.toString(),toASN:r=>new Ha({value:r})},XM={fromASN:r=>r.valueBlock.value,toASN:r=>new Ua({value:r})},zd={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new on({valueHex:r})},P3={fromASN:r=>new ze(r.getValue()),toASN:r=>r.toASN()};u1=zs(Fs),YM=zs(Fa),JM=zs(qa),QM=zs(za),ZM=zs($a),eU=zs(Va),tU=zs(Ka),rU=zs(Wa),sU=zs(Ga),nU=zs(Io),iU=zs(Xa),oU=zs(Ya),aU={fromASN:r=>r.toDate(),toASN:r=>new Ro({valueDate:r})},cU={fromASN:r=>r.toDate(),toASN:r=>new Ja({valueDate:r})},dU={fromASN:()=>null,toASN:()=>new nn}});function $s(r){return typeof r=="function"&&r.prototype?r.prototype.toASN&&r.prototype.fromASN?!0:$s(r.prototype):!!(r&&typeof r=="object"&&"toASN"in r&&"fromASN"in r)}function l1(r){if(r){let e=Object.getPrototypeOf(r);return e?.prototype?.constructor===Array?!0:l1(e)}return!1}function B3(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<r.byteLength;n++)if(t[n]!==s[n])return!1;return!0}var Tm=A(()=>{"use strict"});var Am,N3=A(()=>{"use strict";ko();Za();Tm();Am=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let s=this.items.get(e);if(!s)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!s.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return s}cache(e){let t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){let t={type:B.Sequence,items:{}},s=this.findParentSchema(e);return s&&(Object.assign(t,s),t.items=Object.assign({},t.items,s.items)),t}create(e,t){let s=this.items.get(e)||this.createDefault(e),n=[];for(let i in s.items){let o=s.items[i],a=t?i:"",c;if(typeof o.type=="number"){let u=_[o.type],f=Hn[u];if(!f)throw new Error(`Cannot get ASN1 class by name '${u}'`);c=new f({name:a})}else $s(o.type)?c=new o.type().toSchema(a):o.optional?this.get(o.type).type===B.Choice?c=new Mn({name:a}):(c=this.create(o.type,!1),c.name=a):c=new Mn({name:a});let d=!!o.optional||o.defaultValue!==void 0;if(o.repeated){c.name="";let u=o.repeated==="set"?es:Vr;c=new u({name:"",value:[new Qa({name:a,value:c})]})}if(o.context!==null&&o.context!==void 0)if(o.implicit)if(typeof o.type=="number"||$s(o.type)){let u=o.repeated?fr:Ti;n.push(new u({name:a,optional:d,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);let u=!!o.repeated,f=u?c:this.get(o.type,!0).schema;f="valueBlock"in f?f.valueBlock.value:f.value,n.push(new fr({name:u?"":a,optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:f}))}else n.push(new fr({optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}));else c.optional=d,n.push(c)}switch(s.type){case B.Sequence:return new Vr({value:n,name:""});case B.Set:return new es({value:n,name:""});case B.Choice:return new qd({value:n,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}}});var lr,Im=A(()=>{"use strict";N3();lr=new Am});var M,g,O3=A(()=>{"use strict";ul();Za();Im();M=r=>e=>{let t;lr.has(e)?t=lr.get(e):(t=lr.createDefault(e),lr.set(e,t)),Object.assign(t,r)},g=r=>(e,t)=>{let s;lr.has(e.constructor)?s=lr.get(e.constructor):(s=lr.createDefault(e.constructor),lr.set(e.constructor,s));let n=Object.assign({},r);if(typeof n.type=="number"&&!n.converter){let i=Po(r.type);if(!i)throw new Error(`Cannot get default converter for property '${t}' of ${e.constructor.name}`);n.converter=i}n.raw=r.raw,s.items[t]=n}});var Bo,L3=A(()=>{"use strict";Bo=class extends Error{schemas=[]}});var h1=A(()=>{"use strict";L3()});var fl,p1=A(()=>{"use strict";ko();Cs();Za();ul();h1();Tm();Im();fl=class{static parse(e,t,s){let n=Ri(vr(e),s?.berOptions);if(n.result.error)throw new Error(n.result.error);return this.fromASN(n.result,t,s)}static fromASN(e,t,s){try{if($s(t))return new t().fromASN(e);let n=lr.get(t);lr.cache(t);let i=n.schema,o=this.handleChoiceTypes(e,n,t,i,s);if(o?.result)return o.result;o?.targetSchema&&(i=o.targetSchema);let a=this.handleSequenceTypes(e,n,t,i),c=new t;return l1(t)?this.handleArrayTypes(e,n,t,s):(this.processSchemaItems(n,a,c,s),c)}catch(n){throw n instanceof Bo&&n.schemas.push(t.name),n}}static handleChoiceTypes(e,t,s,n,i){if(e.constructor===fr&&t.type===B.Choice&&e.idBlock.tagClass===3)for(let o in t.items){let a=t.items[o];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&lr.has(a.type)){let c=lr.get(a.type);if(c&&c.type===B.Sequence){let d=new Vr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in d.valueBlock){d.valueBlock.value=e.valueBlock.value;let u=this.fromASN(d,a.type,i),f=new s;return f[o]=u,{result:f}}}}}else if(e.constructor===fr&&t.type!==B.Choice){let o=new fr({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let a in t.items)delete e[a];return{targetSchema:o}}return null}static handleSequenceTypes(e,t,s,n){if(t.type===B.Sequence){let i=Ei({},e,n);if(!i.verified)throw new Bo(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}else{let i=Ei({},e,n);if(!i.verified)throw new Bo(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}}static processRepeatedField(e,t,s){let n=e.slice(t);if(n.length===1&&n[0].constructor.name==="Sequence"){let i=n[0];i.valueBlock&&i.valueBlock.value&&Array.isArray(i.valueBlock.value)&&(n=i.valueBlock.value)}if(typeof s.type=="number"){let i=Po(s.type);if(!i)throw new Error(`No converter for ASN.1 type ${s.type}`);return n.filter(o=>o&&o.valueBlock).map(o=>{try{return i.fromASN(o)}catch{return}}).filter(o=>o!==void 0)}else return n.filter(i=>i&&i.valueBlock).map(i=>{try{return this.fromASN(i,s.type)}catch{return}}).filter(i=>i!==void 0)}static processPrimitiveField(e,t){let s=Po(t.type);if(!s)throw new Error(`No converter for ASN.1 type ${t.type}`);return s.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&lr.has(e.type)&&lr.get(e.type).type===B.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(s){if(s instanceof Bo&&/Wrong values for Choice type/.test(s.message))return{processed:!1};throw s}}static handleArrayTypes(e,t,s,n){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let i=t.itemType;if(typeof i=="number"){let o=Po(i);if(!o)throw new Error(`Cannot get default converter for array item of ${s.name} ASN1 schema`);return s.from(e.valueBlock.value,a=>o.fromASN(a))}else return s.from(e.valueBlock.value,o=>this.fromASN(o,i,n))}static processSchemaItems(e,t,s,n){for(let i in e.items){let o=t.result[i];if(!o)continue;let a=e.items[i],c=a.type,d;typeof c=="number"||$s(c)?d=this.processPrimitiveSchemaItem(o,a,c,n):d=this.processComplexSchemaItem(o,a,c,n),d&&typeof d=="object"&&"value"in d&&"raw"in d?(s[i]=d.value,s[`${i}Raw`]=d.raw):s[i]=d}}static processPrimitiveSchemaItem(e,t,s,n){let i=t.converter??($s(s)?new s:null);if(!i)throw new Error("Converter is empty");return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,n):this.processSinglePrimitiveItem(e,t,s,i,n)}static processRepeatedPrimitiveItem(e,t,s,n){if(t.implicit){let i=t.repeated==="sequence"?Vr:es,o=new i;o.valueBlock=e.valueBlock;let a=Ri(o.toBER(!1),n?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=a.result.valueBlock.value;return Array.from(c,d=>s.fromASN(d))}else return Array.from(e,i=>s.fromASN(i))}static processSinglePrimitiveItem(e,t,s,n,i){let o=e;if(t.implicit){let a;if($s(s))a=new s().toSchema("");else{let c=_[s],d=Hn[c];if(!d)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new d}a.valueBlock=o.valueBlock,o=Ri(a.toBER(!1),i?.berOptions).result}return n.fromASN(o)}static processComplexSchemaItem(e,t,s,n){if(t.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,s,n))}else{let i=this.handleImplicitTagging(e,t,s);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,s,n)}catch(o){if(o instanceof Bo&&/Wrong values for Choice type/.test(o.message))return;throw o}else{let o=this.fromASN(i,s,n);return t.raw?{value:o,raw:e.valueBeforeDecodeView}:o}}}static handleImplicitTagging(e,t,s){if(t.implicit&&typeof t.context=="number"){let n=lr.get(s);if(n.type===B.Sequence){let i=new Vr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}else if(n.type===B.Set){let i=new es;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}}return e}}});var ll,m1=A(()=>{"use strict";ko();Cs();ul();Za();Tm();Im();ll=class r{static serialize(e){return e instanceof ur?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&$s(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let t=e.constructor,s=lr.get(t);lr.cache(t);let n=[];if(s.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof s.itemType=="number"){let o=Po(s.itemType);if(!o)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);n=e.map(a=>o.toASN(a))}else n=e.map(o=>this.toAsnItem({type:s.itemType},"[]",t,o))}else for(let o in s.items){let a=s.items[o],c=e[o];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&B3(this.serialize(a.defaultValue),this.serialize(c)))continue;let d=r.toAsnItem(a,o,t,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||$s(a.type))){let u={};u.valueHex=d instanceof nn?vr(d.valueBeforeDecodeView):d.valueBlock.toBER(),n.push(new Ti({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...u}))}else n.push(new fr({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:d.valueBlock.value}));else n.push(new fr({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[d]}));else a.repeated?n=n.concat(d):n.push(d)}let i;switch(s.type){case B.Sequence:i=new Vr({value:n});break;case B.Set:i=new es({value:n});break;case B.Choice:if(!n[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);i=n[0];break}return i}static toAsnItem(e,t,s,n){let i;if(typeof e.type=="number"){let o=e.converter;if(!o)throw new Error(`Property '${t}' doesn't have converter for type ${_[e.type]} in schema '${s.name}'`);if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(n,d=>o.toASN(d)),c=e.repeated==="sequence"?Vr:es;i=new c({value:a})}else i=o.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let o=Array.from(n,c=>this.toASN(c)),a=e.repeated==="sequence"?Vr:es;i=new a({value:o})}else i=this.toASN(n);return i}}});var je,D3=A(()=>{"use strict";je=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let t of e)this.push(t)}}}});var pe,M3=A(()=>{"use strict";ko();Cs();p1();m1();pe=class r{static serialize(e){return ll.serialize(e)}static parse(e,t,s){return fl.parse(e,t,s)}static toString(e,t){let s=ki(e)?vr(e):r.serialize(e),n=Ri(s,t?.berOptions);if(n.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}}});var J=A(()=>{"use strict";ul();d1();O3();Za();p1();m1();h1();D3();M3()});function p(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,s);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i);return n>3&&i&&Object.defineProperty(e,t,i),i}function ht(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}function Gt(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t}var ee=A(()=>{"use strict"});var g1=A(()=>{"use strict";Cs()});var $d={};Tf($d,{decode:()=>x1,encode:()=>y1,format:()=>q3,formats:()=>z3,hex:()=>wU,is:()=>H3,normalize:()=>hl,parse:()=>F3});function hU(r){return r.separators==="none"?[]:!r.separators||r.separators==="common"?lU:r.separators}function pU(r){if(!r)throw new TypeError("Hex separators must be non-empty strings")}function mU(r,e,t){for(let s of t)if(r.startsWith(s,e))return s}function gU(r){let e=/[A-F]/.test(r),t=/[a-f]/.test(r);return e&&!t?"upper":"lower"}function yU(r){let e=/\r\n|\n/.exec(r);if(e)return e[0]===`\r
23
- `?`\r
24
- `:`
25
- `}function U3(r){return r.replace(/[^0-9a-f]/gi,"")}function xU(r){let e=r.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let t=e.filter((o,a)=>a%2===0),s=e.filter((o,a)=>a%2===1),n=s[0];if(!n||s.some(o=>o!==n)||t.some(o=>o.length===0||o.length%2!==0))return;let i=t[0]?.length??0;if(i&&!t.slice(0,-1).some(o=>o.length!==i)&&!((t[t.length-1]?.length??0)>i))return{size:i/2,separator:n}}function bU(r){let e=r.trim(),t=/^0x/i.test(e)?"0x":"",s=t?e.slice(2):e,n=yU(s),i=s.split(/\r\n|\n/).filter(d=>d.length>0),o=i[0]?.trim()??"",a=xU(o),c={case:gU(e),prefix:t};if(a&&(c.group=a),n&&i.length>1){let d=U3(i[0]??"").length/2;d>0&&i.slice(0,-1).every(u=>U3(u).length/2===d)&&(c.line={bytesPerLine:d,separator:n})}return c}function vU(r,e){let t=e.allowPrefix??!0,s=[...hU(e)].sort((a,c)=>c.length-a.length);for(let a of s)pU(a);let n=r.trim();if(/^0x/i.test(n)){if(!t)throw new TypeError("Hexadecimal text must not include a 0x prefix");n=n.slice(2)}let i="",o=!1;for(let a=0;a<n.length;){let c=n[a]??"";if(fU.test(c)){i+=c,o=!1,a+=1;continue}let d=mU(n,a,s);if(!d)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(o||i.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");o=!0,a+=d.length}if(e.strict&&o&&i.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(i.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");i=`0${i}`}return i.toLowerCase()}function j3(r,e){if(!e)return r.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let t=[];for(let s=0;s<r.length;s+=e.size)t.push(r.slice(s,s+e.size).join(""));return t.join(e.separator)}function hl(r,e={}){return vU(r,e)}function H3(r,e={}){if(typeof r!="string")return!1;try{return hl(r,e),!0}catch{return!1}}function y1(r,e={}){let t=qs(r),s=e.case??"lower",n=Array.from(t,o=>{let a=o.toString(16).padStart(2,"0");return s==="upper"?a.toUpperCase():a}),i="";if(e.line){let o=e.line.bytesPerLine;if(!Number.isInteger(o)||o<1)throw new RangeError("Hex bytesPerLine must be a positive integer");let a=e.line.separator??`
26
- `,c=[];for(let d=0;d<n.length;d+=o)c.push(j3(n.slice(d,d+o),e.group));i=c.join(a)}else i=j3(n,e.group);return`${e.prefix??""}${i}`}function x1(r,e={}){let t=hl(r,e),s=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)s[n/2]=Number.parseInt(t.slice(n,n+2),16);return s}function F3(r,e={}){let t=hl(r,e);return{bytes:x1(t),format:bU(r),normalized:t}}function q3(r,e){return y1(r,e)}var fU,lU,z3,wU,$3=A(()=>{"use strict";Cs();fU=/^[0-9a-f]$/i,lU=[" "," ",`
27
- `,"\r",":","-","."];z3={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})},wU={encode:y1,decode:x1,format:q3,formats:z3,is:H3,normalize:hl,parse:F3}});var V3=A(()=>{"use strict";Cs()});var K3=A(()=>{"use strict";Cs()});var b1=A(()=>{"use strict";Cs();g1()});var W3=A(()=>{"use strict";b1()});var v1=A(()=>{"use strict";g1();$3();V3();K3();b1();W3()});var pl,G3=A(()=>{"use strict";v1();pl=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(".");if(t.length!==4)throw new Error("Invalid IPv4 address");return t.map(s=>{let n=parseInt(s,10);if(isNaN(n)||n<0||n>255)throw new Error("Invalid IPv4 address part");return n})}static parseIPv6(e){let s=this.expandIPv6(e).split(":");if(s.length!==8)throw new Error("Invalid IPv6 address");return s.reduce((n,i)=>{let o=parseInt(i,16);if(isNaN(o)||o<0||o>65535)throw new Error("Invalid IPv6 address part");return n.push(o>>8&255),n.push(o&255),n},[])}static expandIPv6(e){if(!e.includes("::"))return e;let t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");let s=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=8-(s.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...s,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){let t=[];for(let s=0;s<16;s+=2)t.push((e[s]<<8|e[s+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){let t=e.split(":"),s=-1,n=0,i=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(i===-1&&(i=a),o++):(o>n&&(s=i,n=o),i=-1,o=0);if(o>n&&(s=i,n=o),n>1){let a=t.slice(0,s).join(":"),c=t.slice(s+n).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[t,s]=e.split("/"),n=parseInt(s,10);if(this.isIPv4(t)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),n]}else{if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let t=parseInt(e.slice(8),16).toString(2).split("").reduce((n,i)=>n+ +i,0),s=e.slice(0,8).replace(/(.{2})/g,n=>`${parseInt(n,16)}.`);return s=s.slice(0,-1),`${s}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(".");if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let s=t.length/2,n=t.slice(0,s),i=t.slice(s);if(t.every(c=>c===0))return t.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,d)=>c+(d.toString(2).match(/1/g)||[]).length,0);return t.length===8?`${Array.from(n).join(".")}/${a}`:`${this.formatIPv6(n)}/${a}`}return this.decodeIP($d.encode(e))}static fromString(e){if(e.includes("/")){let[s,n]=this.parseCIDR(e),i=new Uint8Array(s.length),o=n;for(let c=0;c<i.length;c++)o>=8?(i[c]=255,o-=8):o>0&&(i[c]=255<<8-o,o=0);let a=new Uint8Array(s.length*2);return a.set(s,0),a.set(i,s.length),a.buffer}let t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}});var w1,S1,_1,hr,Vd,ec,No,E1,Ft,Kd=A(()=>{"use strict";ee();J();v1();hr=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};p([g({type:_.TeletexString})],hr.prototype,"teletexString",void 0);p([g({type:_.PrintableString})],hr.prototype,"printableString",void 0);p([g({type:_.UniversalString})],hr.prototype,"universalString",void 0);p([g({type:_.Utf8String})],hr.prototype,"utf8String",void 0);p([g({type:_.BmpString})],hr.prototype,"bmpString",void 0);hr=p([M({type:B.Choice})],hr);Vd=class extends hr{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?$d.encode(this.anyValue):super.toString())}};p([g({type:_.IA5String})],Vd.prototype,"ia5String",void 0);p([g({type:_.Any})],Vd.prototype,"anyValue",void 0);Vd=p([M({type:B.Choice})],Vd);ec=class{type="";value=new Vd;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],ec.prototype,"type",void 0);p([g({type:Vd})],ec.prototype,"value",void 0);No=w1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,w1.prototype)}};No=w1=p([M({type:B.Set,itemType:ec})],No);E1=S1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,S1.prototype)}};E1=S1=p([M({type:B.Sequence,itemType:No})],E1);Ft=_1=class extends E1{constructor(e){super(e),Object.setPrototypeOf(this,_1.prototype)}};Ft=_1=p([M({type:B.Sequence})],Ft)});var TU,Oo,ml,We,tc=A(()=>{"use strict";ee();J();G3();Kd();TU={fromASN:r=>pl.toString(zd.fromASN(r)),toASN:r=>zd.toASN(pl.fromString(r))},Oo=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Oo.prototype,"typeId",void 0);p([g({type:_.Any,context:0})],Oo.prototype,"value",void 0);ml=class{nameAssigner;partyName=new hr;constructor(e={}){Object.assign(this,e)}};p([g({type:hr,optional:!0,context:0,implicit:!0})],ml.prototype,"nameAssigner",void 0);p([g({type:hr,context:1,implicit:!0})],ml.prototype,"partyName",void 0);We=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};p([g({type:Oo,context:0,implicit:!0})],We.prototype,"otherName",void 0);p([g({type:_.IA5String,context:1,implicit:!0})],We.prototype,"rfc822Name",void 0);p([g({type:_.IA5String,context:2,implicit:!0})],We.prototype,"dNSName",void 0);p([g({type:_.Any,context:3,implicit:!0})],We.prototype,"x400Address",void 0);p([g({type:Ft,context:4,implicit:!1})],We.prototype,"directoryName",void 0);p([g({type:ml,context:5})],We.prototype,"ediPartyName",void 0);p([g({type:_.IA5String,context:6,implicit:!0})],We.prototype,"uniformResourceIdentifier",void 0);p([g({type:_.OctetString,context:7,implicit:!0,converter:TU})],We.prototype,"iPAddress",void 0);p([g({type:_.ObjectIdentifier,context:8,implicit:!0})],We.prototype,"registeredID",void 0);We=p([M({type:B.Choice})],We)});var Lo,Do,X3,rc,Rm,oX,aX,C1,T1,A1,I1,at,Vt=A(()=>{"use strict";Lo="1.3.6.1.5.5.7",Do=`${Lo}.1`,X3=`${Lo}.2`,rc=`${Lo}.3`,Rm=`${Lo}.48`,oX=`${X3}.1`,aX=`${X3}.2`,C1=`${Rm}.1`,T1=`${Rm}.2`,A1=`${Rm}.3`,I1=`${Rm}.5`,at="2.5.29"});var R1,km,Pi,sc,k1=A(()=>{"use strict";ee();J();tc();Vt();km=`${Do}.1`,Pi=class{accessMethod="";accessLocation=new We;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Pi.prototype,"accessMethod",void 0);p([g({type:We})],Pi.prototype,"accessLocation",void 0);sc=R1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,R1.prototype)}};sc=R1=p([M({type:B.Sequence,itemType:Pi})],sc)});var Pm,nc,qn,P1=A(()=>{"use strict";ee();J();tc();Vt();Pm=`${at}.35`,nc=class extends ze{},qn=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};p([g({type:nc,context:0,optional:!0,implicit:!0})],qn.prototype,"keyIdentifier",void 0);p([g({type:We,context:1,optional:!0,implicit:!0,repeated:"sequence"})],qn.prototype,"authorityCertIssuer",void 0);p([g({type:_.Integer,context:2,optional:!0,implicit:!0,converter:Ct})],qn.prototype,"authorityCertSerialNumber",void 0)});var Bm,ic,Y3=A(()=>{"use strict";ee();J();Vt();Bm=`${at}.19`,ic=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Boolean,defaultValue:!1})],ic.prototype,"cA",void 0);p([g({type:_.Integer,optional:!0})],ic.prototype,"pathLenConstraint",void 0)});var B1,Xt,gl=A(()=>{"use strict";ee();J();tc();Xt=B1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,B1.prototype)}};Xt=B1=p([M({type:B.Sequence,itemType:We})],Xt)});var N1,AU,J3,Q3=A(()=>{"use strict";ee();J();gl();Vt();AU=`${at}.29`,J3=N1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,N1.prototype)}};J3=N1=p([M({type:B.Sequence})],J3)});var O1,Om,UX,Bi,yl,xl,Nm,bl,oc,vl,Z3=A(()=>{"use strict";ee();J();Vt();Om=`${at}.32`,UX=`${Om}.0`,Bi=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};p([g({type:_.IA5String})],Bi.prototype,"ia5String",void 0);p([g({type:_.VisibleString})],Bi.prototype,"visibleString",void 0);p([g({type:_.BmpString})],Bi.prototype,"bmpString",void 0);p([g({type:_.Utf8String})],Bi.prototype,"utf8String",void 0);Bi=p([M({type:B.Choice})],Bi);yl=class{organization=new Bi;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Bi})],yl.prototype,"organization",void 0);p([g({type:_.Integer,repeated:"sequence"})],yl.prototype,"noticeNumbers",void 0);xl=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};p([g({type:yl,optional:!0})],xl.prototype,"noticeRef",void 0);p([g({type:Bi,optional:!0})],xl.prototype,"explicitText",void 0);Nm=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};p([g({type:_.IA5String})],Nm.prototype,"cPSuri",void 0);p([g({type:xl})],Nm.prototype,"userNotice",void 0);Nm=p([M({type:B.Choice})],Nm);bl=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],bl.prototype,"policyQualifierId",void 0);p([g({type:_.Any})],bl.prototype,"qualifier",void 0);oc=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],oc.prototype,"policyIdentifier",void 0);p([g({type:bl,repeated:"sequence",optional:!0})],oc.prototype,"policyQualifiers",void 0);vl=O1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,O1.prototype)}};vl=O1=p([M({type:B.Sequence,itemType:oc})],vl)});var KX,wl,L1=A(()=>{"use strict";ee();J();Vt();KX=`${at}.20`,wl=class{value;constructor(e=0){this.value=e}};p([g({type:_.Integer})],wl.prototype,"value",void 0);wl=p([M({type:B.Choice})],wl)});var ZX,eT,tT=A(()=>{"use strict";ee();J();Vt();L1();ZX=`${at}.27`,eT=class extends wl{};eT=p([M({type:B.Choice})],eT)});var D1,Lm,cn,Sl,Ni,zn,Mo,Dm=A(()=>{"use strict";ee();J();Kd();tc();Vt();Lm=`${at}.31`;(function(r){r[r.unused=1]="unused",r[r.keyCompromise=2]="keyCompromise",r[r.cACompromise=4]="cACompromise",r[r.affiliationChanged=8]="affiliationChanged",r[r.superseded=16]="superseded",r[r.cessationOfOperation=32]="cessationOfOperation",r[r.certificateHold=64]="certificateHold",r[r.privilegeWithdrawn=128]="privilegeWithdrawn",r[r.aACompromise=256]="aACompromise"})(cn||(cn={}));Sl=class extends Fn{toJSON(){let e=[],t=this.toNumber();return t&cn.aACompromise&&e.push("aACompromise"),t&cn.affiliationChanged&&e.push("affiliationChanged"),t&cn.cACompromise&&e.push("cACompromise"),t&cn.certificateHold&&e.push("certificateHold"),t&cn.cessationOfOperation&&e.push("cessationOfOperation"),t&cn.keyCompromise&&e.push("keyCompromise"),t&cn.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&cn.superseded&&e.push("superseded"),t&cn.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Ni=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};p([g({type:We,context:0,repeated:"sequence",implicit:!0})],Ni.prototype,"fullName",void 0);p([g({type:No,context:1,implicit:!0})],Ni.prototype,"nameRelativeToCRLIssuer",void 0);Ni=p([M({type:B.Choice})],Ni);zn=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};p([g({type:Ni,context:0,optional:!0})],zn.prototype,"distributionPoint",void 0);p([g({type:Sl,context:1,optional:!0,implicit:!0})],zn.prototype,"reasons",void 0);p([g({type:We,context:2,optional:!0,repeated:"sequence",implicit:!0})],zn.prototype,"cRLIssuer",void 0);Mo=D1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,D1.prototype)}};Mo=D1=p([M({type:B.Sequence,itemType:zn})],Mo)});var M1,pY,rT,sT=A(()=>{"use strict";ee();J();Vt();Dm();pY=`${at}.46`,rT=M1=class extends Mo{constructor(e){super(e),Object.setPrototypeOf(this,M1.prototype)}};rT=M1=p([M({type:B.Sequence,itemType:zn})],rT)});var wY,Vs,nT=A(()=>{"use strict";ee();J();Vt();Dm();wY=`${at}.28`,Vs=class r{static ONLY=!1;distributionPoint;onlyContainsUserCerts=r.ONLY;onlyContainsCACerts=r.ONLY;onlySomeReasons;indirectCRL=r.ONLY;onlyContainsAttributeCerts=r.ONLY;constructor(e={}){Object.assign(this,e)}};p([g({type:Ni,context:0,optional:!0})],Vs.prototype,"distributionPoint",void 0);p([g({type:_.Boolean,context:1,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsUserCerts",void 0);p([g({type:_.Boolean,context:2,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsCACerts",void 0);p([g({type:Sl,context:3,optional:!0,implicit:!0})],Vs.prototype,"onlySomeReasons",void 0);p([g({type:_.Boolean,context:4,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"indirectCRL",void 0);p([g({type:_.Boolean,context:5,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsAttributeCerts",void 0)});var iT,_l,El,oT=A(()=>{"use strict";ee();J();Vt();iT=`${at}.21`;(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(_l||(_l={}));El=class{reason=_l.unspecified;constructor(e=_l.unspecified){this.reason=e}toJSON(){return _l[this.reason]}toString(){return this.toJSON()}};p([g({type:_.Enumerated})],El.prototype,"reason",void 0);El=p([M({type:B.Choice})],El)});var U1,Mm,Cl,BY,aT,cT,dT,uT,fT,lT,hT=A(()=>{"use strict";ee();J();Vt();Mm=`${at}.37`,Cl=U1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,U1.prototype)}};Cl=U1=p([M({type:B.Sequence,itemType:_.ObjectIdentifier})],Cl);BY=`${Mm}.0`,aT=`${rc}.1`,cT=`${rc}.2`,dT=`${rc}.3`,uT=`${rc}.4`,fT=`${rc}.8`,lT=`${rc}.9`});var MY,j1,pT=A(()=>{"use strict";ee();J();Vt();MY=`${at}.54`,j1=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};p([g({type:_.Integer,converter:Ct})],j1.prototype,"value",void 0);j1=p([M({type:B.Choice})],j1)});var mT,Tl,gT=A(()=>{"use strict";ee();J();Vt();mT=`${at}.24`,Tl=class{value=new Date;constructor(e){e&&(this.value=e)}};p([g({type:_.GeneralizedTime})],Tl.prototype,"value",void 0);Tl=p([M({type:B.Choice})],Tl)});var H1,F1,yT,xT=A(()=>{"use strict";ee();J();gl();Vt();F1=`${at}.18`,yT=H1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,H1.prototype)}};yT=H1=p([M({type:B.Sequence})],yT)});var Um,dn,Wd,bT=A(()=>{"use strict";J();Vt();Um=`${at}.15`;(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(dn||(dn={}));Wd=class extends Fn{toJSON(){let e=this.toNumber(),t=[];return e&dn.cRLSign&&t.push("crlSign"),e&dn.dataEncipherment&&t.push("dataEncipherment"),e&dn.decipherOnly&&t.push("decipherOnly"),e&dn.digitalSignature&&t.push("digitalSignature"),e&dn.encipherOnly&&t.push("encipherOnly"),e&dn.keyAgreement&&t.push("keyAgreement"),e&dn.keyCertSign&&t.push("keyCertSign"),e&dn.keyEncipherment&&t.push("keyEncipherment"),e&dn.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}});var q1,nJ,Gd,jm,Hm,vT=A(()=>{"use strict";ee();J();tc();Vt();nJ=`${at}.30`,Gd=class{base=new We;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Gd.prototype,"base",void 0);p([g({type:_.Integer,context:0,defaultValue:0,implicit:!0})],Gd.prototype,"minimum",void 0);p([g({type:_.Integer,context:1,optional:!0,implicit:!0})],Gd.prototype,"maximum",void 0);jm=q1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,q1.prototype)}};jm=q1=p([M({type:B.Sequence,itemType:Gd})],jm);Hm=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};p([g({type:jm,context:0,optional:!0,implicit:!0})],Hm.prototype,"permittedSubtrees",void 0);p([g({type:jm,context:1,optional:!0,implicit:!0})],Hm.prototype,"excludedSubtrees",void 0)});var uJ,Fm,wT=A(()=>{"use strict";ee();J();Vt();uJ=`${at}.36`,Fm=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,context:0,implicit:!0,optional:!0,converter:Ct})],Fm.prototype,"requireExplicitPolicy",void 0);p([g({type:_.Integer,context:1,implicit:!0,optional:!0,converter:Ct})],Fm.prototype,"inhibitPolicyMapping",void 0)});var z1,mJ,Al,ST,_T=A(()=>{"use strict";ee();J();Vt();mJ=`${at}.33`,Al=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Al.prototype,"issuerDomainPolicy",void 0);p([g({type:_.ObjectIdentifier})],Al.prototype,"subjectDomainPolicy",void 0);ST=z1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,z1.prototype)}};ST=z1=p([M({type:B.Sequence,itemType:Al})],ST)});var $1,V1,qm,ET=A(()=>{"use strict";ee();J();gl();Vt();V1=`${at}.17`,qm=$1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,$1.prototype)}};qm=$1=p([M({type:B.Sequence})],qm)});var Ir,K1=A(()=>{"use strict";ee();J();Ir=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ir.prototype,"type",void 0);p([g({type:_.Any,repeated:"set"})],Ir.prototype,"values",void 0)});var W1,PJ,CT,TT=A(()=>{"use strict";ee();J();K1();Vt();PJ=`${at}.9`,CT=W1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,W1.prototype)}};CT=W1=p([M({type:B.Sequence,itemType:Ir})],CT)});var G1,us,AT=A(()=>{"use strict";Vt();P1();G1=`${at}.14`,us=class extends nc{}});var HJ,zm,IT=A(()=>{"use strict";ee();J();Vt();HJ=`${at}.16`,zm=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralizedTime,context:0,implicit:!0,optional:!0})],zm.prototype,"notBefore",void 0);p([g({type:_.GeneralizedTime,context:1,implicit:!0,optional:!0})],zm.prototype,"notAfter",void 0)});var Il,$m,Vm,RT=A(()=>{"use strict";ee();J();(function(r){r[r.keyUpdateAllowed=1]="keyUpdateAllowed",r[r.newExtensions=2]="newExtensions",r[r.pKIXCertificate=4]="pKIXCertificate"})(Il||(Il={}));$m=class extends Fn{toJSON(){let e=[],t=this.toNumber();return t&Il.pKIXCertificate&&e.push("pKIXCertificate"),t&Il.newExtensions&&e.push("newExtensions"),t&Il.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Vm=class{entrustVers="";entrustInfoFlags=new $m;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralString})],Vm.prototype,"entrustVers",void 0);p([g({type:$m})],Vm.prototype,"entrustInfoFlags",void 0)});var X1,XJ,kT,PT=A(()=>{"use strict";ee();J();Vt();k1();XJ=`${Do}.11`,kT=X1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,X1.prototype)}};kT=X1=p([M({type:B.Sequence,itemType:Pi})],kT)});var BT=A(()=>{"use strict";k1();P1();Y3();Q3();Z3();tT();Dm();sT();nT();L1();oT();hT();pT();gT();xT();bT();vT();wT();_T();ET();TT();AT();IT();RT();PT()});var fe,ac=A(()=>{"use strict";ee();J();Cs();fe=class r{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof r&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&c1(e.parameters,this.parameters)||e.parameters===this.parameters)}};p([g({type:_.ObjectIdentifier})],fe.prototype,"algorithm",void 0);p([g({type:_.Any,optional:!0})],fe.prototype,"parameters",void 0)});var Rr,Y1=A(()=>{"use strict";ee();J();ac();Rr=class{algorithm=new fe;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Rr.prototype,"algorithm",void 0);p([g({type:_.BitString})],Rr.prototype,"subjectPublicKey",void 0)});var or,Km=A(()=>{"use strict";ee();J();or=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let t=new Date(e);t.setMilliseconds(0),t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};p([g({type:_.UTCTime})],or.prototype,"utcTime",void 0);p([g({type:_.GeneralizedTime})],or.prototype,"generalTime",void 0);or=p([M({type:B.Choice})],or)});var Oi,J1=A(()=>{"use strict";ee();J();Km();Oi=class{notBefore=new or(new Date);notAfter=new or(new Date);constructor(e){e&&(this.notBefore=new or(e.notBefore),this.notAfter=new or(e.notAfter))}};p([g({type:or})],Oi.prototype,"notBefore",void 0);p([g({type:or})],Oi.prototype,"notAfter",void 0)});var Q1,Kr,Ts,Wm=A(()=>{"use strict";ee();J();Kr=class r{static CRITICAL=!1;extnID="";critical=r.CRITICAL;extnValue=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Kr.prototype,"extnID",void 0);p([g({type:_.Boolean,defaultValue:Kr.CRITICAL})],Kr.prototype,"critical",void 0);p([g({type:ze})],Kr.prototype,"extnValue",void 0);Ts=Q1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Q1.prototype)}};Ts=Q1=p([M({type:B.Sequence,itemType:Kr})],Ts)});var $n,Z1=A(()=>{"use strict";(function(r){r[r.v1=0]="v1",r[r.v2=1]="v2",r[r.v3=2]="v3"})($n||($n={}))});var kr,ev=A(()=>{"use strict";ee();J();ac();Kd();Y1();J1();Wm();Z1();kr=class{version=$n.v1;serialNumber=new ArrayBuffer(0);signature=new fe;issuer=new Ft;validity=new Oi;subject=new Ft;subjectPublicKeyInfo=new Rr;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,context:0,defaultValue:$n.v1})],kr.prototype,"version",void 0);p([g({type:_.Integer,converter:Ct})],kr.prototype,"serialNumber",void 0);p([g({type:fe})],kr.prototype,"signature",void 0);p([g({type:Ft})],kr.prototype,"issuer",void 0);p([g({type:Oi})],kr.prototype,"validity",void 0);p([g({type:Ft})],kr.prototype,"subject",void 0);p([g({type:Rr})],kr.prototype,"subjectPublicKeyInfo",void 0);p([g({type:_.BitString,context:1,implicit:!0,optional:!0})],kr.prototype,"issuerUniqueID",void 0);p([g({type:_.BitString,context:2,implicit:!0,optional:!0})],kr.prototype,"subjectUniqueID",void 0);p([g({type:Ts,context:3,optional:!0})],kr.prototype,"extensions",void 0)});var Ks,NT=A(()=>{"use strict";ee();J();ac();ev();Ks=class{tbsCertificate=new kr;tbsCertificateRaw;signatureAlgorithm=new fe;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:kr,raw:!0})],Ks.prototype,"tbsCertificate",void 0);p([g({type:fe})],Ks.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Ks.prototype,"signatureValue",void 0)});var cc,As,tv=A(()=>{"use strict";ee();J();ac();Kd();Km();Wm();cc=class{userCertificate=new ArrayBuffer(0);revocationDate=new or;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Ct})],cc.prototype,"userCertificate",void 0);p([g({type:or})],cc.prototype,"revocationDate",void 0);p([g({type:Kr,optional:!0,repeated:"sequence"})],cc.prototype,"crlEntryExtensions",void 0);As=class{version;signature=new fe;issuer=new Ft;thisUpdate=new or;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,optional:!0})],As.prototype,"version",void 0);p([g({type:fe})],As.prototype,"signature",void 0);p([g({type:Ft})],As.prototype,"issuer",void 0);p([g({type:or})],As.prototype,"thisUpdate",void 0);p([g({type:or,optional:!0})],As.prototype,"nextUpdate",void 0);p([g({type:cc,repeated:"sequence",optional:!0})],As.prototype,"revokedCertificates",void 0);p([g({type:Kr,optional:!0,context:0,repeated:"sequence"})],As.prototype,"crlExtensions",void 0)});var dc,OT=A(()=>{"use strict";ee();J();ac();tv();dc=class{tbsCertList=new As;tbsCertListRaw;signatureAlgorithm=new fe;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:As,raw:!0})],dc.prototype,"tbsCertList",void 0);p([g({type:fe})],dc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],dc.prototype,"signature",void 0)});var Tt=A(()=>{"use strict";BT();ac();K1();NT();OT();Wm();tc();gl();Kd();Vt();Y1();tv();ev();Km();Z1();J1()});var un,Rl=A(()=>{"use strict";ee();J();Tt();un=class{issuer=new Ft;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Ft})],un.prototype,"issuer",void 0);p([g({type:_.Integer,converter:Ct})],un.prototype,"serialNumber",void 0)});var uc,rv=A(()=>{"use strict";ee();J();Tt();Rl();uc=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0})],uc.prototype,"subjectKeyIdentifier",void 0);p([g({type:un})],uc.prototype,"issuerAndSerialNumber",void 0);uc=p([M({type:B.Choice})],uc)});var Pr,fc,kl,fs,Pl,DT,Gm,Vn=A(()=>{"use strict";ee();Tt();J();(function(r){r[r.v0=0]="v0",r[r.v1=1]="v1",r[r.v2=2]="v2",r[r.v3=3]="v3",r[r.v4=4]="v4",r[r.v5=5]="v5"})(Pr||(Pr={}));fc=class extends fe{};fc=p([M({type:B.Sequence})],fc);kl=class extends fe{};kl=p([M({type:B.Sequence})],kl);fs=class extends fe{};fs=p([M({type:B.Sequence})],fs);Pl=class extends fe{};Pl=p([M({type:B.Sequence})],Pl);DT=class extends fe{};DT=p([M({type:B.Sequence})],DT);Gm=class extends fe{};Gm=p([M({type:B.Sequence})],Gm)});var fn,Xm=A(()=>{"use strict";ee();J();fn=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],fn.prototype,"attrType",void 0);p([g({type:_.Any,repeated:"set"})],fn.prototype,"attrValues",void 0)});var sv,ls,Bl,Ym=A(()=>{"use strict";ee();J();rv();Vn();Xm();ls=class{version=Pr.v0;sid=new uc;digestAlgorithm=new fc;signedAttrs;signedAttrsRaw;signatureAlgorithm=new kl;signature=new ze;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],ls.prototype,"version",void 0);p([g({type:uc})],ls.prototype,"sid",void 0);p([g({type:fc})],ls.prototype,"digestAlgorithm",void 0);p([g({type:fn,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],ls.prototype,"signedAttrs",void 0);p([g({type:kl})],ls.prototype,"signatureAlgorithm",void 0);p([g({type:ze})],ls.prototype,"signature",void 0);p([g({type:fn,repeated:"set",context:1,implicit:!0,optional:!0})],ls.prototype,"unsignedAttrs",void 0);Bl=sv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,sv.prototype)}};Bl=sv=p([M({type:B.Set,itemType:ls})],Bl)});var MT,UT=A(()=>{"use strict";ee();J();Ym();MT=class extends ls{};MT=p([M({type:B.Sequence})],MT)});var jT=A(()=>{"use strict";J()});var HT,FT=A(()=>{"use strict";ee();Tt();J();HT=class extends or{};HT=p([M({type:B.Choice})],HT)});var qT=A(()=>{"use strict";UT();jT();FT()});var Nl,zT=A(()=>{"use strict";ee();J();Tt();Nl=class{acIssuer=new We;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Nl.prototype,"acIssuer",void 0);p([g({type:_.Integer})],Nl.prototype,"acSerial",void 0);p([g({type:Ir,repeated:"sequence"})],Nl.prototype,"attrs",void 0)});var nv,Ol,iv=A(()=>{"use strict";ee();J();Ol=nv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,nv.prototype)}};Ol=nv=p([M({type:B.Sequence,itemType:_.ObjectIdentifier})],Ol)});var Xd,$T=A(()=>{"use strict";ee();J();iv();Xd=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,optional:!0})],Xd.prototype,"pathLenConstraint",void 0);p([g({type:Ol,implicit:!0,context:0,optional:!0})],Xd.prototype,"permittedAttrs",void 0);p([g({type:Ol,implicit:!0,context:1,optional:!0})],Xd.prototype,"excludedAttrs",void 0);p([g({type:_.Boolean,defaultValue:!0})],Xd.prototype,"permitUnSpecified",void 0)});var Ws,Ll=A(()=>{"use strict";ee();J();Tt();Ws=class{issuer=new Xt;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Xt})],Ws.prototype,"issuer",void 0);p([g({type:_.Integer,converter:Ct})],Ws.prototype,"serial",void 0);p([g({type:_.BitString,optional:!0})],Ws.prototype,"issuerUID",void 0)});var ov,Gs,Dl=A(()=>{"use strict";ee();J();Tt();(function(r){r[r.publicKey=0]="publicKey",r[r.publicKeyCert=1]="publicKeyCert",r[r.otherObjectTypes=2]="otherObjectTypes"})(ov||(ov={}));Gs=class{digestedObjectType=ov.publicKey;otherObjectTypeID;digestAlgorithm=new fe;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Enumerated})],Gs.prototype,"digestedObjectType",void 0);p([g({type:_.ObjectIdentifier,optional:!0})],Gs.prototype,"otherObjectTypeID",void 0);p([g({type:fe})],Gs.prototype,"digestAlgorithm",void 0);p([g({type:_.BitString})],Gs.prototype,"objectDigest",void 0)});var lc,av=A(()=>{"use strict";ee();J();Tt();Ll();Dl();lc=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,optional:!0})],lc.prototype,"issuerName",void 0);p([g({type:Ws,context:0,implicit:!0,optional:!0})],lc.prototype,"baseCertificateID",void 0);p([g({type:Gs,context:1,implicit:!0,optional:!0})],lc.prototype,"objectDigestInfo",void 0)});var hc,cv=A(()=>{"use strict";ee();J();Tt();av();hc=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};p([g({type:We,repeated:"sequence"})],hc.prototype,"v1Form",void 0);p([g({type:lc,context:0,implicit:!0})],hc.prototype,"v2Form",void 0);hc=p([M({type:B.Choice})],hc)});var pc,dv=A(()=>{"use strict";ee();J();pc=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralizedTime})],pc.prototype,"notBeforeTime",void 0);p([g({type:_.GeneralizedTime})],pc.prototype,"notAfterTime",void 0)});var Uo,uv=A(()=>{"use strict";ee();J();Tt();Ll();Dl();Uo=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Ws,implicit:!0,context:0,optional:!0})],Uo.prototype,"baseCertificateID",void 0);p([g({type:Xt,implicit:!0,context:1,optional:!0})],Uo.prototype,"entityName",void 0);p([g({type:Gs,implicit:!0,context:2,optional:!0})],Uo.prototype,"objectDigestInfo",void 0)});var fv,hs,lv=A(()=>{"use strict";ee();J();Tt();uv();cv();dv();(function(r){r[r.v2=1]="v2"})(fv||(fv={}));hs=class{version=fv.v2;holder=new Uo;issuer=new hc;signature=new fe;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new pc;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],hs.prototype,"version",void 0);p([g({type:Uo})],hs.prototype,"holder",void 0);p([g({type:hc})],hs.prototype,"issuer",void 0);p([g({type:fe})],hs.prototype,"signature",void 0);p([g({type:_.Integer,converter:Ct})],hs.prototype,"serialNumber",void 0);p([g({type:pc})],hs.prototype,"attrCertValidityPeriod",void 0);p([g({type:Ir,repeated:"sequence"})],hs.prototype,"attributes",void 0);p([g({type:_.BitString,optional:!0})],hs.prototype,"issuerUniqueID",void 0);p([g({type:Ts,optional:!0})],hs.prototype,"extensions",void 0)});var mc,VT=A(()=>{"use strict";ee();J();Tt();lv();mc=class{acinfo=new hs;signatureAlgorithm=new fe;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:hs})],mc.prototype,"acinfo",void 0);p([g({type:fe})],mc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],mc.prototype,"signatureValue",void 0)});var Ml,Yd,hv=A(()=>{"use strict";J();(function(r){r[r.unmarked=1]="unmarked",r[r.unclassified=2]="unclassified",r[r.restricted=4]="restricted",r[r.confidential=8]="confidential",r[r.secret=16]="secret",r[r.topSecret=32]="topSecret"})(Ml||(Ml={}));Yd=class extends Fn{}});var Jd,pv=A(()=>{"use strict";ee();J();Jd=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier,implicit:!0,context:0})],Jd.prototype,"type",void 0);p([g({type:_.Any,implicit:!0,context:1})],Jd.prototype,"value",void 0)});var Ul,KT=A(()=>{"use strict";ee();J();hv();pv();Ul=class{policyId="";classList=new Yd(Ml.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ul.prototype,"policyId",void 0);p([g({type:Yd,defaultValue:new Yd(Ml.unclassified)})],Ul.prototype,"classList",void 0);p([g({type:Jd,repeated:"set"})],Ul.prototype,"securityCategories",void 0)});var Qd,Jm,WT=A(()=>{"use strict";ee();J();Tt();Qd=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],Qd.prototype,"cotets",void 0);p([g({type:_.ObjectIdentifier})],Qd.prototype,"oid",void 0);p([g({type:_.Utf8String})],Qd.prototype,"string",void 0);Jm=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Jm.prototype,"policyAuthority",void 0);p([g({type:Qd,repeated:"sequence"})],Jm.prototype,"values",void 0)});var jte,Hte,Fte,qte,jl,zte,$te,Vte,Kte,Wte,mv,Gte,GT=A(()=>{"use strict";Tt();jte=`${Do}.4`,Hte=`${Do}.6`,Fte=`${Do}.10`,qte=`${at}.55`,jl=`${Lo}.10`,zte=`${jl}.1`,$te=`${jl}.2`,Vte=`${jl}.3`,Kte=`${jl}.4`,Wte=`${jl}.6`,mv="2.5.4",Gte=`${mv}.72`});var gv,Zd,eu,Qm,yv=A(()=>{"use strict";ee();J();Tt();Ll();Dl();Zd=class{targetCertificate=new Ws;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Ws})],Zd.prototype,"targetCertificate",void 0);p([g({type:We,optional:!0})],Zd.prototype,"targetName",void 0);p([g({type:Gs,optional:!0})],Zd.prototype,"certDigestInfo",void 0);eu=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};p([g({type:We,context:0,implicit:!0})],eu.prototype,"targetName",void 0);p([g({type:We,context:1,implicit:!0})],eu.prototype,"targetGroup",void 0);p([g({type:Zd,context:2,implicit:!0})],eu.prototype,"targetCert",void 0);eu=p([M({type:B.Choice})],eu);Qm=gv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,gv.prototype)}};Qm=gv=p([M({type:B.Sequence,itemType:eu})],Qm)});var xv,XT,YT=A(()=>{"use strict";ee();J();yv();XT=xv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,xv.prototype)}};XT=xv=p([M({type:B.Sequence,itemType:Qm})],XT)});var Zm,JT=A(()=>{"use strict";ee();J();Tt();Zm=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Zm.prototype,"roleAuthority",void 0);p([g({type:We,implicit:!0,context:1})],Zm.prototype,"roleName",void 0)});var Hl,QT=A(()=>{"use strict";ee();J();Tt();Hl=class{service=new We;ident=new We;authInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Hl.prototype,"service",void 0);p([g({type:We})],Hl.prototype,"ident",void 0);p([g({type:ze,optional:!0})],Hl.prototype,"authInfo",void 0)});var bv=A(()=>{"use strict";zT();$T();cv();dv();iv();VT();lv();hv();KT();uv();WT();Ll();Dl();GT();YT();JT();pv();QT();yv();av()});var vv,Fl,gc,yc,eg=A(()=>{"use strict";ee();J();Tt();bv();Fl=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Fl.prototype,"otherCertFormat",void 0);p([g({type:_.Any})],Fl.prototype,"otherCert",void 0);gc=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};p([g({type:Ks})],gc.prototype,"certificate",void 0);p([g({type:mc,context:2,implicit:!0})],gc.prototype,"v2AttrCert",void 0);p([g({type:Fl,context:3,implicit:!0})],gc.prototype,"other",void 0);gc=p([M({type:B.Choice})],gc);yc=vv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,vv.prototype)}};yc=vv=p([M({type:B.Set,itemType:gc})],yc)});var Xs,ZT=A(()=>{"use strict";ee();J();Xs=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Xs.prototype,"contentType",void 0);p([g({type:_.Any,context:0})],Xs.prototype,"content",void 0)});var tu,xc,wv=A(()=>{"use strict";ee();J();tu=class{single;any;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],tu.prototype,"single",void 0);p([g({type:_.Any})],tu.prototype,"any",void 0);tu=p([M({type:B.Choice})],tu);xc=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],xc.prototype,"eContentType",void 0);p([g({type:tu,context:0,optional:!0})],xc.prototype,"eContent",void 0)});var ql,jo,Sv=A(()=>{"use strict";ee();J();Vn();ql=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};p([g({type:ze,context:0,implicit:!0,optional:!0})],ql.prototype,"value",void 0);p([g({type:ze,converter:P3,context:0,implicit:!0,optional:!0,repeated:"sequence"})],ql.prototype,"constructedValue",void 0);ql=p([M({type:B.Choice})],ql);jo=class{contentType="";contentEncryptionAlgorithm=new Pl;encryptedContent;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],jo.prototype,"contentType",void 0);p([g({type:Pl})],jo.prototype,"contentEncryptionAlgorithm",void 0);p([g({type:ql,optional:!0})],jo.prototype,"encryptedContent",void 0)});var Ho,_v=A(()=>{"use strict";ee();J();Ho=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ho.prototype,"keyAttrId",void 0);p([g({type:_.Any,optional:!0})],Ho.prototype,"keyAttr",void 0)});var Ev,ru,su,zl,tg,$l,bc,Li,Cv=A(()=>{"use strict";ee();J();Tt();Vn();Rl();_v();ru=class{subjectKeyIdentifier=new us;date;other;constructor(e={}){Object.assign(this,e)}};p([g({type:us})],ru.prototype,"subjectKeyIdentifier",void 0);p([g({type:_.GeneralizedTime,optional:!0})],ru.prototype,"date",void 0);p([g({type:Ho,optional:!0})],ru.prototype,"other",void 0);su=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:ru,context:0,implicit:!0,optional:!0})],su.prototype,"rKeyId",void 0);p([g({type:un,optional:!0})],su.prototype,"issuerAndSerialNumber",void 0);su=p([M({type:B.Choice})],su);zl=class{rid=new su;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:su})],zl.prototype,"rid",void 0);p([g({type:ze})],zl.prototype,"encryptedKey",void 0);tg=Ev=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Ev.prototype)}};tg=Ev=p([M({type:B.Sequence,itemType:zl})],tg);$l=class{algorithm=new fe;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],$l.prototype,"algorithm",void 0);p([g({type:_.BitString})],$l.prototype,"publicKey",void 0);bc=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0,optional:!0})],bc.prototype,"subjectKeyIdentifier",void 0);p([g({type:$l,context:1,implicit:!0,optional:!0})],bc.prototype,"originatorKey",void 0);p([g({type:un,optional:!0})],bc.prototype,"issuerAndSerialNumber",void 0);bc=p([M({type:B.Choice})],bc);Li=class{version=Pr.v3;originator=new bc;ukm;keyEncryptionAlgorithm=new fs;recipientEncryptedKeys=new tg;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Li.prototype,"version",void 0);p([g({type:bc,context:0})],Li.prototype,"originator",void 0);p([g({type:ze,context:1,optional:!0})],Li.prototype,"ukm",void 0);p([g({type:fs})],Li.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:tg})],Li.prototype,"recipientEncryptedKeys",void 0)});var nu,Fo,Tv=A(()=>{"use strict";ee();J();Tt();Vn();Rl();nu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0})],nu.prototype,"subjectKeyIdentifier",void 0);p([g({type:un})],nu.prototype,"issuerAndSerialNumber",void 0);nu=p([M({type:B.Choice})],nu);Fo=class{version=Pr.v0;rid=new nu;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Fo.prototype,"version",void 0);p([g({type:nu})],Fo.prototype,"rid",void 0);p([g({type:fs})],Fo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],Fo.prototype,"encryptedKey",void 0)});var vc,qo,Av=A(()=>{"use strict";ee();J();_v();Vn();vc=class{keyIdentifier=new ze;date;other;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],vc.prototype,"keyIdentifier",void 0);p([g({type:_.GeneralizedTime,optional:!0})],vc.prototype,"date",void 0);p([g({type:Ho,optional:!0})],vc.prototype,"other",void 0);qo=class{version=Pr.v4;kekid=new vc;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],qo.prototype,"version",void 0);p([g({type:vc})],qo.prototype,"kekid",void 0);p([g({type:fs})],qo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],qo.prototype,"encryptedKey",void 0)});var zo,Iv=A(()=>{"use strict";ee();J();Vn();zo=class{version=Pr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],zo.prototype,"version",void 0);p([g({type:Gm,context:0,optional:!0})],zo.prototype,"keyDerivationAlgorithm",void 0);p([g({type:fs})],zo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],zo.prototype,"encryptedKey",void 0)});var Vl,Di,Rv=A(()=>{"use strict";ee();J();Cv();Tv();Av();Iv();Vl=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Vl.prototype,"oriType",void 0);p([g({type:_.Any})],Vl.prototype,"oriValue",void 0);Di=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};p([g({type:Fo,optional:!0})],Di.prototype,"ktri",void 0);p([g({type:Li,context:1,implicit:!0,optional:!0})],Di.prototype,"kari",void 0);p([g({type:qo,context:2,implicit:!0,optional:!0})],Di.prototype,"kekri",void 0);p([g({type:zo,context:3,implicit:!0,optional:!0})],Di.prototype,"pwri",void 0);p([g({type:Vl,context:4,implicit:!0,optional:!0})],Di.prototype,"ori",void 0);Di=p([M({type:B.Choice})],Di)});var kv,Kl,Pv=A(()=>{"use strict";ee();J();Rv();Kl=kv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,kv.prototype)}};Kl=kv=p([M({type:B.Set,itemType:Di})],Kl)});var Bv,e4,Wse,Gse,iu,rg,ou,sg=A(()=>{"use strict";ee();J();Tt();e4=`${Lo}.16`,Wse=`${e4}.2`,Gse=`${e4}.4`,iu=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],iu.prototype,"otherRevInfoFormat",void 0);p([g({type:_.Any})],iu.prototype,"otherRevInfo",void 0);rg=class{other=new iu;constructor(e={}){Object.assign(this,e)}};p([g({type:iu,context:1,implicit:!0})],rg.prototype,"other",void 0);rg=p([M({type:B.Choice})],rg);ou=Bv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Bv.prototype)}};ou=Bv=p([M({type:B.Set,itemType:rg})],ou)});var au,Nv=A(()=>{"use strict";ee();J();eg();sg();au=class{certs;crls;constructor(e={}){Object.assign(this,e)}};p([g({type:yc,context:0,implicit:!0,optional:!0})],au.prototype,"certs",void 0);p([g({type:ou,context:1,implicit:!0,optional:!0})],au.prototype,"crls",void 0)});var Ov,Lv,wc,t4=A(()=>{"use strict";ee();J();Vn();Xm();Pv();Nv();Sv();Lv=Ov=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Ov.prototype)}};Lv=Ov=p([M({type:B.Set,itemType:fn})],Lv);wc=class{version=Pr.v0;originatorInfo;recipientInfos=new Kl;encryptedContentInfo=new jo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],wc.prototype,"version",void 0);p([g({type:au,context:0,implicit:!0,optional:!0})],wc.prototype,"originatorInfo",void 0);p([g({type:Kl})],wc.prototype,"recipientInfos",void 0);p([g({type:jo})],wc.prototype,"encryptedContentInfo",void 0);p([g({type:Lv,context:1,implicit:!0,optional:!0})],wc.prototype,"unprotectedAttrs",void 0)});var r4,s4=A(()=>{"use strict";r4="1.2.840.113549.1.7.2"});var Dv,ng,Mi,n4=A(()=>{"use strict";ee();J();eg();Vn();wv();sg();Ym();ng=Dv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Dv.prototype)}};ng=Dv=p([M({type:B.Set,itemType:fc})],ng);Mi=class{version=Pr.v0;digestAlgorithms=new ng;encapContentInfo=new xc;certificates;crls;signerInfos=new Bl;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Mi.prototype,"version",void 0);p([g({type:ng})],Mi.prototype,"digestAlgorithms",void 0);p([g({type:xc})],Mi.prototype,"encapContentInfo",void 0);p([g({type:yc,context:0,implicit:!0,optional:!0})],Mi.prototype,"certificates",void 0);p([g({type:ou,context:1,implicit:!0,optional:!0})],Mi.prototype,"crls",void 0);p([g({type:Bl})],Mi.prototype,"signerInfos",void 0)});var Wl=A(()=>{"use strict";qT();Xm();eg();ZT();wv();Sv();t4();Rl();Av();Cv();Tv();s4();Nv();Iv();Rv();Pv();sg();n4();rv();Ym();Vn()});var Sc,Gl,ig,Xl,Yl,Jl,Mv,Uv,jv,Hv=A(()=>{"use strict";Sc="1.2.840.10045.2.1",Gl="1.2.840.10045.4.1",ig="1.2.840.10045.4.3.1",Xl="1.2.840.10045.4.3.2",Yl="1.2.840.10045.4.3.3",Jl="1.2.840.10045.4.3.4",Mv="1.2.840.10045.3.1.7",Uv="1.3.132.0.34",jv="1.3.132.0.35"});function Ql(r){return new fe({algorithm:r})}var o4,$ne,a4,c4,d4,u4=A(()=>{"use strict";Tt();Hv();o4=Ql(Gl),$ne=Ql(ig),a4=Ql(Xl),c4=Ql(Yl),d4=Ql(Jl)});var Zl,Fv,cu,qv,Kn,zv=A(()=>{"use strict";ee();J();Zl=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Zl.prototype,"fieldType",void 0);p([g({type:_.Any})],Zl.prototype,"parameters",void 0);Zl=p([M({type:B.Sequence})],Zl);Fv=class extends ze{},cu=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};p([g({type:_.OctetString})],cu.prototype,"a",void 0);p([g({type:_.OctetString})],cu.prototype,"b",void 0);p([g({type:_.BitString,optional:!0})],cu.prototype,"seed",void 0);cu=p([M({type:B.Sequence})],cu);(function(r){r[r.ecpVer1=1]="ecpVer1"})(qv||(qv={}));Kn=class{version=qv.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Kn.prototype,"version",void 0);p([g({type:Zl})],Kn.prototype,"fieldID",void 0);p([g({type:cu})],Kn.prototype,"curve",void 0);p([g({type:Fv})],Kn.prototype,"base",void 0);p([g({type:_.Integer,converter:Ct})],Kn.prototype,"order",void 0);p([g({type:_.Integer,optional:!0})],Kn.prototype,"cofactor",void 0);Kn=p([M({type:B.Sequence})],Kn)});var Wn,$v=A(()=>{"use strict";ee();J();zv();Wn=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Wn.prototype,"namedCurve",void 0);p([g({type:_.Null})],Wn.prototype,"implicitCurve",void 0);p([g({type:Kn})],Wn.prototype,"specifiedCurve",void 0);Wn=p([M({type:B.Choice})],Wn)});var du,f4=A(()=>{"use strict";ee();J();$v();du=class{version=1;privateKey=new ze;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],du.prototype,"version",void 0);p([g({type:ze})],du.prototype,"privateKey",void 0);p([g({type:Wn,context:0,optional:!0})],du.prototype,"parameters",void 0);p([g({type:_.BitString,context:1,optional:!0})],du.prototype,"publicKey",void 0)});var _c,l4=A(()=>{"use strict";ee();J();_c=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Ct})],_c.prototype,"r",void 0);p([g({type:_.Integer,converter:Ct})],_c.prototype,"s",void 0)});var Vv=A(()=>{"use strict";u4();$v();f4();l4();Hv();zv()});var ps,Gn,h4,p4,$o,m4,g4,uu,y4,og,fu,lu,Kv,Wv,Ec,ag,Cc,Tc,Ac,x4,b4,v4,w4,Vo,eh=A(()=>{"use strict";ps="1.2.840.113549.1.1",Gn=`${ps}.1`,h4=`${ps}.7`,p4=`${ps}.9`,$o=`${ps}.10`,m4=`${ps}.2`,g4=`${ps}.4`,uu=`${ps}.5`,y4=`${ps}.14`,og=`${ps}.11`,fu=`${ps}.12`,lu=`${ps}.13`,Kv=`${ps}.15`,Wv=`${ps}.16`,Ec="1.3.14.3.2.26",ag="2.16.840.1.101.3.4.2.4",Cc="2.16.840.1.101.3.4.2.1",Tc="2.16.840.1.101.3.4.2.2",Ac="2.16.840.1.101.3.4.2.3",x4="2.16.840.1.101.3.4.2.5",b4="2.16.840.1.101.3.4.2.6",v4="1.2.840.113549.2.2",w4="1.2.840.113549.2.5",Vo=`${ps}.8`});function wr(r){return new fe({algorithm:r,parameters:null})}var xie,bie,Ui,vie,wie,Sie,_ie,Eie,Cie,cg,Gv,Tie,Aie,Iie,Rie,kie,Pie,Bie,Nie,Oie,Lie,dg=A(()=>{"use strict";J();Tt();eh();xie=wr(v4),bie=wr(w4),Ui=wr(Ec),vie=wr(ag),wie=wr(Cc),Sie=wr(Tc),_ie=wr(Ac),Eie=wr(x4),Cie=wr(b4),cg=new fe({algorithm:Vo,parameters:pe.serialize(Ui)}),Gv=new fe({algorithm:p4,parameters:pe.serialize(zd.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),Tie=wr(Gn),Aie=wr(m4),Iie=wr(g4),Rie=wr(uu),kie=wr(Kv),Pie=wr(Wv),Bie=wr(fu),Nie=wr(lu),Oie=wr(Kv),Lie=wr(Wv)});var hu,qie,S4=A(()=>{"use strict";ee();J();Tt();eh();dg();hu=class{hashAlgorithm=new fe(Ui);maskGenAlgorithm=new fe({algorithm:Vo,parameters:pe.serialize(Ui)});pSourceAlgorithm=new fe(Gv);constructor(e={}){Object.assign(this,e)}};p([g({type:fe,context:0,defaultValue:Ui})],hu.prototype,"hashAlgorithm",void 0);p([g({type:fe,context:1,defaultValue:cg})],hu.prototype,"maskGenAlgorithm",void 0);p([g({type:fe,context:2,defaultValue:Gv})],hu.prototype,"pSourceAlgorithm",void 0);qie=new fe({algorithm:h4,parameters:pe.serialize(new hu)})});var Xn,Xie,_4=A(()=>{"use strict";ee();J();Tt();eh();dg();Xn=class{hashAlgorithm=new fe(Ui);maskGenAlgorithm=new fe({algorithm:Vo,parameters:pe.serialize(Ui)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};p([g({type:fe,context:0,defaultValue:Ui})],Xn.prototype,"hashAlgorithm",void 0);p([g({type:fe,context:1,defaultValue:cg})],Xn.prototype,"maskGenAlgorithm",void 0);p([g({type:_.Integer,context:2,defaultValue:20})],Xn.prototype,"saltLength",void 0);p([g({type:_.Integer,context:3,defaultValue:1})],Xn.prototype,"trailerField",void 0);Xie=new fe({algorithm:$o,parameters:pe.serialize(new Xn)})});var Ic,E4=A(()=>{"use strict";ee();Tt();J();Ic=class{digestAlgorithm=new fe;digest=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Ic.prototype,"digestAlgorithm",void 0);p([g({type:ze})],Ic.prototype,"digest",void 0)});var C4=A(()=>{"use strict";S4();_4();E4()});var Xv,pu,ug,Yv=A(()=>{"use strict";ee();J();pu=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Ct})],pu.prototype,"prime",void 0);p([g({type:_.Integer,converter:Ct})],pu.prototype,"exponent",void 0);p([g({type:_.Integer,converter:Ct})],pu.prototype,"coefficient",void 0);ug=Xv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Xv.prototype)}};ug=Xv=p([M({type:B.Sequence,itemType:pu})],ug)});var Ys,T4=A(()=>{"use strict";ee();J();Yv();Ys=class{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Ys.prototype,"version",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"publicExponent",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"privateExponent",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"prime1",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"prime2",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"exponent1",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"exponent2",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"coefficient",void 0);p([g({type:ug,optional:!0})],Ys.prototype,"otherPrimeInfos",void 0)});var mu,A4=A(()=>{"use strict";ee();J();mu=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Ct})],mu.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Ct})],mu.prototype,"publicExponent",void 0)});var fg=A(()=>{"use strict";C4();dg();eh();Yv();T4();A4()});var Jv,Br,Qv=A(()=>{"use strict";(function(r){r[r.Transient=0]="Transient",r[r.Singleton=1]="Singleton",r[r.ResolutionScoped=2]="ResolutionScoped",r[r.ContainerScoped=3]="ContainerScoped"})(Jv||(Jv={}));Br=Jv});var I4=A(()=>{"use strict";Qv()});function th(r,e){Zv(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function R4(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{d(s.next(u))}catch(f){o(f)}}function c(u){try{d(s.throw(u))}catch(f){o(f)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((s=s.apply(r,e||[])).next())})}function k4(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(d){return function(u){return c([d,u])}}function c(d){if(s)throw new TypeError("Generator is already executing.");for(;t;)try{if(s=1,n&&(i=d[0]&2?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[d[0]&2,i.value]),d[0]){case 0:case 1:i=d;break;case 4:return t.label++,{value:d[1],done:!1};case 5:t.label++,n=d[1],d=[0];continue;case 7:d=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){t.label=d[1];break}if(d[0]===6&&t.label<i[1]){t.label=i[1],i=d;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(d);break}i[2]&&t.ops.pop(),t.trys.pop();continue}d=e.call(r,t)}catch(u){d=[6,u],n=0}finally{s=i=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function rh(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gu(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return i}function Yn(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(gu(arguments[e]));return r}var Zv,yu=A(()=>{"use strict";Zv=function(r,e){return Zv=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,s){t.__proto__=s}||function(t,s){for(var n in s)s.hasOwnProperty(n)&&(t[n]=s[n])},Zv(r,e)}});function ew(r){var e=Reflect.getMetadata("design:paramtypes",r)||[],t=Reflect.getOwnMetadata(NU,r)||{};return Object.keys(t).forEach(function(s){e[+s]=t[s]}),e}var NU,Rc=A(()=>{"use strict";NU="injectionTokens"});function sh(r){return!!r.useClass}var tw=A(()=>{"use strict"});function xu(r){return!!r.useFactory}var rw=A(()=>{"use strict"});var lg,hg=A(()=>{"use strict";yu();lg=(function(){function r(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return r.prototype.createProxy=function(e){var t=this,s={},n=!1,i,o=function(){return n||(i=e(t.wrap()),n=!0),i};return new Proxy(s,this.createHandler(o))},r.prototype.createHandler=function(e){var t={},s=function(n){t[n]=function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];i[0]=e();var a=Reflect[n];return a.apply(void 0,Yn(i))}};return this.reflectMethods.forEach(s),t},r})()});function Ko(r){return typeof r=="string"||typeof r=="symbol"}function sw(r){return typeof r=="object"&&"token"in r&&"multiple"in r}function pg(r){return typeof r=="object"&&"token"in r&&"transform"in r}function P4(r){return typeof r=="function"||r instanceof lg}var mg=A(()=>{"use strict";hg()});function kc(r){return!!r.useToken}var nw=A(()=>{"use strict"});function Pc(r){return r.useValue!=null}var iw=A(()=>{"use strict"});var ow=A(()=>{"use strict";tw();rw();mg();nw();iw()});function B4(r){return sh(r)||Pc(r)||kc(r)||xu(r)}var N4=A(()=>{"use strict";tw();iw();nw();rw()});var OU,nh,aw=A(()=>{"use strict";OU=(function(){function r(){this._registryMap=new Map}return r.prototype.entries=function(){return this._registryMap.entries()},r.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},r.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},r.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},r.prototype.setAll=function(e,t){this._registryMap.set(e,t)},r.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},r.prototype.clear=function(){this._registryMap.clear()},r.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},r})(),nh=OU});var LU,O4,L4=A(()=>{"use strict";yu();aw();LU=(function(r){th(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(nh),O4=LU});var DU,ih,D4=A(()=>{"use strict";DU=(function(){function r(){this.scopedResolutions=new Map}return r})(),ih=DU});function MU(r,e){if(r===null)return"at position #"+e;var t=r.split(",")[e].trim();return'"'+t+'" at position #'+e}function UU(r,e,t){return t===void 0&&(t=" "),Yn([r],e.message.split(`
28
- `).map(function(s){return t+s})).join(`
29
- `)}function cw(r,e,t){var s=gu(r.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=MU(i,e);return UU("Cannot inject the dependency "+o+' of "'+r.name+'" constructor. Reason:',t)}var dw=A(()=>{"use strict";yu()});function M4(r){if(typeof r.dispose!="function")return!1;var e=r.dispose;return!(e.length>0)}var U4=A(()=>{"use strict"});var jU,HU,FU,j4,H4=A(()=>{"use strict";yu();aw();jU=(function(r){th(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(nh),HU=(function(r){th(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(nh),FU=(function(){function r(){this.preResolution=new jU,this.postResolution=new HU}return r})(),j4=FU});var uw,qU,Kt,Wo=A(()=>{"use strict";yu();ow();N4();mg();L4();Qv();D4();dw();hg();U4();H4();uw=new Map,qU=(function(){function r(e){this.parent=e,this._registry=new O4,this.interceptors=new j4,this.disposed=!1,this.disposables=new Set}return r.prototype.register=function(e,t,s){s===void 0&&(s={lifecycle:Br.Transient}),this.ensureNotDisposed();var n;if(B4(t)?n=t:n={useClass:t},kc(n))for(var i=[e],o=n;o!=null;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Yn(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&kc(c.provider)?o=c.provider:o=null}if((s.lifecycle===Br.Singleton||s.lifecycle==Br.ContainerScoped||s.lifecycle==Br.ResolutionScoped)&&(Pc(n)||xu(n)))throw new Error('Cannot use lifecycle "'+Br[s.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:s}),this},r.prototype.registerType=function(e,t){return this.ensureNotDisposed(),Ko(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},r.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},r.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),Ko(e)){if(Ko(t))return this.register(e,{useToken:t},{lifecycle:Br.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Br.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var s=e;return t&&!Ko(t)&&(s=t),this.register(e,{useClass:s},{lifecycle:Br.Singleton})},r.prototype.resolve=function(e,t,s){t===void 0&&(t=new ih),s===void 0&&(s=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&Ko(e)){if(s)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(P4(e)){var i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},r.prototype.executePreResolutionInterceptor=function(e,t){var s,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=rh(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;c.options.frequency!="Once"&&i.push(c),c.callback(e,t)}}catch(d){s={error:d}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}this.interceptors.preResolution.setAll(e,i)}},r.prototype.executePostResolutionInterceptor=function(e,t,s){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=rh(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var d=c.value;d.options.frequency!="Once"&&o.push(d),d.callback(e,t,s)}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},r.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===Br.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var s=e.options.lifecycle===Br.Singleton,n=e.options.lifecycle===Br.ContainerScoped,i=s||n,o;return Pc(e.provider)?o=e.provider.useValue:kc(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):sh(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):xu(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,t),e.options.lifecycle===Br.ResolutionScoped&&t.scopedResolutions.set(e,o),o},r.prototype.resolveAll=function(e,t,s){var n=this;t===void 0&&(t=new ih),s===void 0&&(s=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&Ko(e)){if(s)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map(function(c){return n.resolveRegistration(c,t)});return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},r.prototype.isRegistered=function(e,t){return t===void 0&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},r.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},r.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var s=rh(this._registry.entries()),n=s.next();!n.done;n=s.next()){var i=gu(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter(function(c){return!Pc(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}},r.prototype.createChildContainer=function(){var e,t;this.ensureNotDisposed();var s=new r(this);try{for(var n=rh(this._registry.entries()),i=n.next();!i.done;i=n.next()){var o=gu(i.value,2),a=o[0],c=o[1];c.some(function(d){var u=d.options;return u.lifecycle===Br.ContainerScoped})&&s._registry.setAll(a,c.map(function(d){return d.options.lifecycle===Br.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return s},r.prototype.beforeResolution=function(e,t,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:s})},r.prototype.afterResolution=function(e,t,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:s})},r.prototype.dispose=function(){return R4(this,void 0,void 0,function(){var e;return k4(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(s){var n=s.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},r.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},r.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},r.prototype.construct=function(e,t){var s=this;if(e instanceof lg)return e.createProxy(function(i){return s.resolve(i,t)});var n=(function(){var i=uw.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var o=i.map(s.resolveParams(t,e));return new(e.bind.apply(e,Yn([void 0],o)))})();return M4(n)&&this.disposables.add(n),n},r.prototype.resolveParams=function(e,t){var s=this;return function(n,i){var o,a,c;try{return sw(n)?pg(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,Yn([s.resolveAll(n.token,new ih,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,Yn([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new ih,n.isOptional):s.resolve(n.token,e,n.isOptional):pg(n)?(c=s.resolve(n.transform,e)).transform.apply(c,Yn([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(cw(t,i,d))}}},r.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},r})(),Kt=new qU});var F4=A(()=>{"use strict";Rc();Wo();mg();dw()});var q4=A(()=>{"use strict";Rc()});function zU(r){return function(e){uw.set(e,ew(e)),r&&r.token&&(Array.isArray(r.token)?r.token.forEach(function(t){Kt.register(t,e)}):Kt.register(r.token,e))}}var Go,gg=A(()=>{"use strict";Rc();Wo();Wo();Go=zU});var z4=A(()=>{"use strict";Wo()});var $4=A(()=>{"use strict";gg();Wo()});var V4=A(()=>{"use strict";Rc()});var K4=A(()=>{"use strict";Rc()});var W4=A(()=>{"use strict";Rc()});var G4=A(()=>{"use strict";gg();Wo()});var X4=A(()=>{"use strict";F4();q4();gg();z4();$4();V4();K4();W4();G4()});var Y4=A(()=>{"use strict"});var J4=A(()=>{"use strict"});var Q4=A(()=>{"use strict"});var Z4=A(()=>{"use strict";Y4();J4();Q4()});var e8=A(()=>{"use strict";I4();X4();Z4();ow();hg();Wo();if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`)});var lw,Bc,t8,hw=A(()=>{"use strict";ee();J();Bc=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};p([g({type:_.ObjectIdentifier})],Bc.prototype,"attrId",void 0);p([g({type:_.Any,repeated:"set"})],Bc.prototype,"attrValues",void 0);t8=lw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,lw.prototype)}};t8=lw=p([M({type:B.Sequence,itemType:Bc})],t8)});var pw,r8,s8=A(()=>{"use strict";ee();J();Wl();r8=pw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,pw.prototype)}};r8=pw=p([M({type:B.Sequence,itemType:Xs})],r8)});var $U,VU,n8,bu,Bce,Nce,Oce,Lce,Dce,Mce,Nc,mw=A(()=>{"use strict";$U="1.2.840.113549",VU=`${$U}.1`,n8=`${VU}.12`,bu=`${n8}.1`,Bce=`${bu}.1`,Nce=`${bu}.2`,Oce=`${bu}.3`,Lce=`${bu}.4`,Dce=`${bu}.5`,Mce=`${bu}.6`,Nc=`${n8}.10.1`});var Hce,Fce,qce,zce,$ce,Vce,yg,xg=A(()=>{"use strict";mw();Hce=`${Nc}.1`,Fce=`${Nc}.2`,qce=`${Nc}.3`,zce=`${Nc}.4`,$ce=`${Nc}.5`,Vce=`${Nc}.6`,yg="1.2.840.113549.1.9"});var bg,i8,Yce,Jce,o8=A(()=>{"use strict";ee();J();xg();bg=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],bg.prototype,"certId",void 0);p([g({type:_.Any,context:0})],bg.prototype,"certValue",void 0);i8=`${yg}.22`,Yce=`${i8}.1`,Jce=`${i8}.2`});var vg,KU,rde,a8=A(()=>{"use strict";ee();J();xg();vg=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],vg.prototype,"crlId",void 0);p([g({type:_.Any,context:0})],vg.prototype,"crltValue",void 0);KU=`${yg}.23`,rde=`${KU}.1`});var wg,Xo,c8=A(()=>{"use strict";ee();J();Tt();wg=class extends ze{},Xo=class{encryptionAlgorithm=new fe;encryptedData=new wg;constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Xo.prototype,"encryptionAlgorithm",void 0);p([g({type:wg})],Xo.prototype,"encryptedData",void 0)});var gw,yw,Sg,xw,Yo,d8=A(()=>{"use strict";ee();J();Tt();(function(r){r[r.v1=0]="v1"})(yw||(yw={}));Sg=class extends ze{},xw=gw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,gw.prototype)}};xw=gw=p([M({type:B.Sequence,itemType:Ir})],xw);Yo=class{version=yw.v1;privateKeyAlgorithm=new fe;privateKey=new Sg;attributes;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Yo.prototype,"version",void 0);p([g({type:fe})],Yo.prototype,"privateKeyAlgorithm",void 0);p([g({type:Sg})],Yo.prototype,"privateKey",void 0);p([g({type:xw,implicit:!0,context:0,optional:!0})],Yo.prototype,"attributes",void 0)});var _g=A(()=>{"use strict";c8();d8()});var u8,f8=A(()=>{"use strict";ee();_g();J();u8=class extends Yo{};u8=p([M({type:B.Sequence})],u8)});var l8,h8=A(()=>{"use strict";ee();_g();J();l8=class extends Xo{};l8=p([M({type:B.Sequence})],l8)});var Eg,p8=A(()=>{"use strict";ee();J();Eg=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Eg.prototype,"secretTypeId",void 0);p([g({type:_.Any,context:0})],Eg.prototype,"secretValue",void 0)});var m8=A(()=>{"use strict";o8();a8();f8();h8();p8();xg()});var Jo,bw=A(()=>{"use strict";ee();fg();J();Jo=class{mac=new Ic;macSalt=new ze;iterations=1;constructor(e={}){Object.assign(this,e)}};p([g({type:Ic})],Jo.prototype,"mac",void 0);p([g({type:ze})],Jo.prototype,"macSalt",void 0);p([g({type:_.Integer,defaultValue:1})],Jo.prototype,"iterations",void 0)});var Oc,g8=A(()=>{"use strict";ee();J();Wl();bw();Oc=class{version=3;authSafe=new Xs;macData=new Jo;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Oc.prototype,"version",void 0);p([g({type:Xs})],Oc.prototype,"authSafe",void 0);p([g({type:Jo,optional:!0})],Oc.prototype,"macData",void 0)});var vw,vu,y8,x8=A(()=>{"use strict";ee();J();hw();vu=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],vu.prototype,"bagId",void 0);p([g({type:_.Any,context:0})],vu.prototype,"bagValue",void 0);p([g({type:Bc,repeated:"set",optional:!0})],vu.prototype,"bagAttributes",void 0);y8=vw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,vw.prototype)}};y8=vw=p([M({type:B.Sequence,itemType:vu})],y8)});var b8=A(()=>{"use strict";hw();s8();m8();bw();mw();g8();x8()});var ww,Sw,_w,ar,nue,N8,ah,O8,L8,iue,oue,aue,cue,due,uue,fue,lue,Pw,hue,pue,mue,ch,gue,yue,xue,bue,vue,wue,Sue,_ue,dh,Eue,Cue,Tue,Aue,Iue,Rue,kue,Pue,Bue,Nue,Oue,Lue,Due,Cg,v8,w8,S8,Ew,_8,E8,Cw,C8,Tw,Tg,T8,A8,Aw,I8,Iw,R8,oh,k8,P8,Rw,kw,B8,Bw=A(()=>{"use strict";ee();J();Wl();b8();_g();Tt();bv();ar="1.2.840.113549.1.9",nue=`${ar}.0`,N8=`${ar}.24`,ah=`${ar}.25`,O8=`${ar}.26`,L8=`${ar}.27`,iue=`${N8}.1`,oue=`${N8}.2`,aue=`${ar}.1`,cue=`${ar}.2`,due=`${ar}.3`,uue=`${ar}.4`,fue=`${ar}.5`,lue=`${ar}.6`,Pw=`${ar}.7`,hue=`${ar}.8`,pue=`${ar}.9`,mue=`${ar}.13`,ch=`${ar}.14`,gue=`${ar}.15`,yue=`${ar}.20`,xue=`${ar}.21`,bue=`${ah}.1`,vue=`${ah}.2`,wue=`${ah}.3`,Sue=`${ah}.4`,_ue=`${ah}.5`,dh="1.3.6.1.5.5.7.9",Eue=`${dh}.1`,Cue=`${dh}.2`,Tue=`${dh}.3`,Aue=`${dh}.4`,Iue=`${dh}.5`,Rue=`${O8}.1`,kue=`${O8}.2`,Pue=`${L8}.1`,Bue=`${L8}.2`,Nue=`${ar}.16`,Oue=`${ar}.22`,Lue=`${ar}.23`,Due=`${mv}.65`,Cg=class extends hr{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};p([g({type:_.IA5String})],Cg.prototype,"ia5String",void 0);Cg=p([M({type:B.Choice})],Cg);v8=class extends Xs{};v8=p([M({type:B.Sequence})],v8);w8=class extends Oc{};w8=p([M({type:B.Sequence})],w8);S8=class extends Xo{};S8=p([M({type:B.Sequence})],S8);Ew=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.IA5String})],Ew.prototype,"value",void 0);Ew=p([M({type:B.Choice})],Ew);_8=class extends Cg{};_8=p([M({type:B.Choice})],_8);E8=class extends hr{};E8=p([M({type:B.Choice})],E8);Cw=class{value;constructor(e=new Date){this.value=e}};p([g({type:_.GeneralizedTime})],Cw.prototype,"value",void 0);Cw=p([M({type:B.Choice})],Cw);C8=class extends hr{};C8=p([M({type:B.Choice})],C8);Tw=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Tw.prototype,"value",void 0);Tw=p([M({type:B.Choice})],Tw);Tg=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Tg.prototype,"value",void 0);Tg=p([M({type:B.Choice})],Tg);T8=class extends Tg{};T8=p([M({type:B.Choice})],T8);A8=class extends hr{};A8=p([M({type:B.Choice})],A8);Aw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.ObjectIdentifier})],Aw.prototype,"value",void 0);Aw=p([M({type:B.Choice})],Aw);I8=class extends or{};I8=p([M({type:B.Choice})],I8);Iw=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};p([g({type:_.Integer})],Iw.prototype,"value",void 0);Iw=p([M({type:B.Choice})],Iw);R8=class extends ls{};R8=p([M({type:B.Sequence})],R8);oh=class extends hr{};oh=p([M({type:B.Choice})],oh);k8=ww=class extends Ts{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};k8=ww=p([M({type:B.Sequence})],k8);P8=Sw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Sw.prototype)}};P8=Sw=p([M({type:B.Set,itemType:fn})],P8);Rw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.BmpString})],Rw.prototype,"value",void 0);Rw=p([M({type:B.Choice})],Rw);kw=class extends fe{};kw=p([M({type:B.Sequence})],kw);B8=_w=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,_w.prototype)}};B8=_w=p([M({type:B.Sequence,itemType:kw})],B8)});var Nw,uh,Ow=A(()=>{"use strict";ee();J();Tt();uh=Nw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Nw.prototype)}};uh=Nw=p([M({type:B.Sequence,itemType:Ir})],uh)});var Jn,Lw=A(()=>{"use strict";ee();J();Tt();Ow();Jn=class{version=0;subject=new Ft;subjectPKInfo=new Rr;attributes=new uh;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Jn.prototype,"version",void 0);p([g({type:Ft})],Jn.prototype,"subject",void 0);p([g({type:Rr})],Jn.prototype,"subjectPKInfo",void 0);p([g({type:uh,implicit:!0,context:0,optional:!0})],Jn.prototype,"attributes",void 0)});var Qo,D8=A(()=>{"use strict";ee();J();Tt();Lw();Qo=class{certificationRequestInfo=new Jn;certificationRequestInfoRaw;signatureAlgorithm=new fe;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Jn,raw:!0})],Qo.prototype,"certificationRequestInfo",void 0);p([g({type:fe})],Qo.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Qo.prototype,"signature",void 0)});var M8=A(()=>{"use strict";Ow();D8();Lw()});function JU(r){return new RegExp(YU).test(r)}function QU(r,e){return`\\${Ue.ToHex(Ue.FromUtf8String(e)).toUpperCase()}`}function ZU(r){return r.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,QU)}function cj(r,e){return r.algorithm=new fe({algorithm:Gn,parameters:null}),e=pe.serialize(r),e}function Ig(r,e,t){if(t.length===1)r[e]=t[0].toTextObject();else{let s=new Rt("");t.forEach((n,i)=>{let o=n.toTextObject(),a=`${o[Rt.NAME]} ${i+1}`,c=s[a];Array.isArray(c)||(c=[],s[a]=c),c.push(o)}),r[e]=s}}function Rg(r,e,t,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new Qn("url",o)),r.push(new Pi({accessMethod:t,accessLocation:pe.parse(o.rawData,We)}))})}function dj(r,e=pr.get()){let t=be.toUint8Array(Ue.FromHex(r||"")),s=t&&t.length&&t.some(i=>i>0)?new Uint8Array(t):void 0;s||(s=e.getRandomValues(new Uint8Array(16)));let n=0;for(;n<s.length-1&&s[n]===0;)n++;if(s=s.slice(n),s[0]>127){let i=new Uint8Array(s.length+1);i[0]=0,i.set(s,1),s=i}return s.buffer}var Tfe,Oh,Vw,Lc,kg,gs,U8,j8,H8,F8,q8,z8,$8,V8,K8,W8,G8,X8,Y8,J8,Q8,Z8,eA,tA,rA,sA,nA,iA,oA,aA,cA,dA,uA,fA,tr,kh,SA,_A,Rt,Kw,Zn,Hi,wu,Zo,Is,EA,Ph,pr,YU,Bg,ms,ln,CA,lA,ej,hA,pA,mA,Dw,Mw,Uw,jw,Hw,Fw,qw,Ag,Qn,Fi,Rh,Bh,tj,rj,sj,Eu,nj,ij,oj,aj,gA,Nr,ea,ji,Ng,Og,yA,Lg,xA,Dg,Mg,Ug,rs,jg,Hg,Fg,qg,Cu,zg,Nh,Tu,Lh,Ww,Pg,Gw,Xw,qi,zw,bA,$w,vA,Yw,fh,lh,hh,ph,mh,gh,yh,Su,Jw,xh,bh,vh,wh,Sh,_h,Eh,Ch,Th,Ah,_u,Ih,$g,Vg,uj,fj,lj,hj,pj,wA,mj,gj,yj,xj,bj,vj,wj,TA=A(()=>{"use strict";Tfe=Ge(P6());J();Tt();Tt();Zb();ee();Wl();Vv();Vv();fg();fg();e8();Bw();Bw();M8();Oh="crypto.algorithm",Vw=class{getAlgorithms(){return Kt.resolveAll(Oh)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let s=t.toAsnAlgorithm(e);if(s)return s}if(/^[0-9.]+$/.test(e.name)){let t=new fe({algorithm:e.name});if("parameters"in e){let s=e;t.parameters=s.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let s of this.getAlgorithms()){let n=s.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},Lc="crypto.algorithmProvider";Kt.registerSingleton(Lc,Vw);gs="1.3.36.3.3.2.8.1.1",U8=`${gs}.1`,j8=`${gs}.2`,H8=`${gs}.3`,F8=`${gs}.4`,q8=`${gs}.5`,z8=`${gs}.6`,$8=`${gs}.7`,V8=`${gs}.8`,K8=`${gs}.9`,W8=`${gs}.10`,G8=`${gs}.11`,X8=`${gs}.12`,Y8=`${gs}.13`,J8=`${gs}.14`,Q8="brainpoolP160r1",Z8="brainpoolP160t1",eA="brainpoolP192r1",tA="brainpoolP192t1",rA="brainpoolP224r1",sA="brainpoolP224t1",nA="brainpoolP256r1",iA="brainpoolP256t1",oA="brainpoolP320r1",aA="brainpoolP320t1",cA="brainpoolP384r1",dA="brainpoolP384t1",uA="brainpoolP512r1",fA="brainpoolP512t1",tr="ECDSA",kh=kg=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case tr.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return o4;case"sha-256":return a4;case"sha-384":return c4;case"sha-512":return d4}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Mv;break;case"K-256":t=kg.SECP256K1;break;case"P-384":t=Uv;break;case"P-521":t=jv;break;case Q8:t=U8;break;case Z8:t=j8;break;case eA:t=H8;break;case tA:t=F8;break;case rA:t=q8;break;case sA:t=z8;break;case nA:t=$8;break;case iA:t=V8;break;case oA:t=K8;break;case aA:t=W8;break;case cA:t=G8;break;case dA:t=X8;break;case uA:t=Y8;break;case fA:t=J8;break}if(t)return new fe({algorithm:Sc,parameters:pe.serialize(new Wn({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Gl:return{name:tr,hash:{name:"SHA-1"}};case Xl:return{name:tr,hash:{name:"SHA-256"}};case Yl:return{name:tr,hash:{name:"SHA-384"}};case Jl:return{name:tr,hash:{name:"SHA-512"}};case Sc:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(pe.parse(e.parameters,Wn).namedCurve){case Mv:return{name:tr,namedCurve:"P-256"};case kg.SECP256K1:return{name:tr,namedCurve:"K-256"};case Uv:return{name:tr,namedCurve:"P-384"};case jv:return{name:tr,namedCurve:"P-521"};case U8:return{name:tr,namedCurve:Q8};case j8:return{name:tr,namedCurve:Z8};case H8:return{name:tr,namedCurve:eA};case F8:return{name:tr,namedCurve:tA};case q8:return{name:tr,namedCurve:rA};case z8:return{name:tr,namedCurve:sA};case $8:return{name:tr,namedCurve:nA};case V8:return{name:tr,namedCurve:iA};case K8:return{name:tr,namedCurve:oA};case W8:return{name:tr,namedCurve:aA};case G8:return{name:tr,namedCurve:cA};case X8:return{name:tr,namedCurve:dA};case Y8:return{name:tr,namedCurve:uA};case J8:return{name:tr,namedCurve:fA}}}}return null}};kh.SECP256K1="1.3.132.0.10";kh=kg=p([Go()],kh);Kt.registerSingleton(Oh,kh);SA=Symbol("name"),_A=Symbol("value"),Rt=class{constructor(e,t={},s=""){this[SA]=e,this[_A]=s;for(let n in t)this[n]=t[n]}};Rt.NAME=SA;Rt.VALUE=_A;Kw=class{static toTextObject(e){let t=new Rt("Algorithm Identifier",{},Zn.toString(e.algorithm));if(e.parameters)if(e.algorithm===Sc){let s=new kh().toWebAlgorithm(e);s&&"namedCurve"in s?t["Named Curve"]=s.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}},Zn=class{static toString(e){let t=this.items[e];return t||e}};Zn.items={[Ec]:"sha1",[ag]:"sha224",[Cc]:"sha256",[Tc]:"sha384",[Ac]:"sha512",[Gn]:"rsaEncryption",[uu]:"sha1WithRSAEncryption",[y4]:"sha224WithRSAEncryption",[og]:"sha256WithRSAEncryption",[fu]:"sha384WithRSAEncryption",[lu]:"sha512WithRSAEncryption",[Sc]:"ecPublicKey",[Gl]:"ecdsaWithSHA1",[ig]:"ecdsaWithSHA224",[Xl]:"ecdsaWithSHA256",[Yl]:"ecdsaWithSHA384",[Jl]:"ecdsaWithSHA512",[aT]:"TLS WWW server authentication",[cT]:"TLS WWW client authentication",[dT]:"Code Signing",[uT]:"E-mail Protection",[fT]:"Time Stamping",[lT]:"OCSP Signing",[r4]:"Signed Data"};Hi=class{static serialize(e){return this.serializeObj(e).join(`
30
- `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){let s=[],n=this.pad(t++),i="",o=e[Rt.VALUE];o&&(i=` ${o}`),s.push(`${n}${e[Rt.NAME]}:${i}`),n=this.pad(t);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],d=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")s.push(`${n}${d}${c}`);else if(c instanceof Date)s.push(`${n}${d}${c.toUTCString()}`);else if(Array.isArray(c))for(let u of c)u[Rt.NAME]=a,s.push(...this.serializeObj(u,t));else if(c instanceof Rt)c[Rt.NAME]=a,s.push(...this.serializeObj(c,t));else if(be.isBufferSource(c))a?(s.push(`${n}${d}`),s.push(...this.serializeBufferSource(c,t+1))):s.push(...this.serializeBufferSource(c,t));else if("toTextObject"in c){let u=c.toTextObject();u[Rt.NAME]=a,s.push(...this.serializeObj(u,t))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return s}static serializeBufferSource(e,t=0){let s=this.pad(t),n=be.toUint8Array(e),i=[];for(let o=0;o<n.length;){let a=[];for(let c=0;c<16&&o<n.length;c++){c===8&&a.push("");let d=n[o++].toString(16).padStart(2,"0");a.push(d)}i.push(`${s}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};Hi.oidSerializer=Zn;Hi.algorithmSerializer=Kw;Zo=class r{get rawData(){return ht(this,wu,"f")||Gt(this,wu,pe.serialize(this.asn),"f"),ht(this,wu,"f")}constructor(...e){wu.set(this,void 0),be.isBufferSource(e[0])?(this.asn=pe.parse(e[0],e[1]),Gt(this,wu,be.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof r?N6(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return pe.toString(this.rawData);case"text":return Hi.serialize(this.toTextObject());case"hex":return Ue.ToHex(this.rawData);case"base64":return Ue.ToBase64(this.rawData);case"base64url":return Ue.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Rt(this.getTextName(),{},e)}};wu=new WeakMap;Zo.NAME="ASN";Is=class r extends Zo{constructor(...e){let t;be.isBufferSource(e[0])?t=be.toArrayBuffer(e[0]):t=pe.serialize(new Kr({extnID:e[0],critical:e[1],extnValue:new ze(be.toArrayBuffer(e[2]))})),super(t,Kr)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Rt.NAME]===r.NAME&&(e[Rt.NAME]=Zn.toString(this.type)),e}},Ph=class r{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[EA]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(r.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(r.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=r.DEFAULT){let t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if(typeof e=="string"){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(r.DEFAULT,e);return this}};EA=Symbol.toStringTag;Ph.DEFAULT="default";pr=new Ph,YU=/^[0-2](?:\.[1-9][0-9]*)+$/;Bg=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return JU(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},ms=new Bg;ms.register("CN","2.5.4.3");ms.register("L","2.5.4.7");ms.register("ST","2.5.4.8");ms.register("O","2.5.4.10");ms.register("OU","2.5.4.11");ms.register("C","2.5.4.6");ms.register("DC","0.9.2342.19200300.100.1.25");ms.register("E","1.2.840.113549.1.9.1");ms.register("G","2.5.4.42");ms.register("I","2.5.4.43");ms.register("SN","2.5.4.4");ms.register("T","2.5.4.12");ln=class r{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new Bg,this.asn=new Ft;for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)){let n=t[s];this.extraNames.register(s,n)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Ft?this.asn=e:be.isBufferSource(e)?this.asn=pe.parse(e,Ft):this.asn=this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||ms.findId(e),s=[];for(let n of this.asn)for(let i of n)i.type===t&&s.push(i.value.toString());return s}getName(e){return this.extraNames.get(e)||ms.get(e)}toString(){return this.asn.map(e=>e.map(t=>{let s=this.getName(t.type)||t.type,n=t.value.anyValue?`#${Ue.ToHex(t.value.anyValue)}`:ZU(t.value.toString());return`${s}=${n}`}).join("+")).join(", ")}toJSON(){var e;let t=[];for(let s of this.asn){let n={};for(let i of s){let o=this.getName(i.type)||i.type;(e=n[o])!==null&&e!==void 0||(n[o]=[]),n[o].push(i.value.anyValue?`#${Ue.ToHex(i.value.anyValue)}`:i.value.toString())}t.push(n)}return t}fromString(e){let t=new Ft,s=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";for(;n=s.exec(`${e},`);){let[,o,a]=n,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),n[3]=c);let d=n[3];o=this.getTypeOid(o);let u=this.createAttribute(o,a);i==="+"?t[t.length-1].push(u):t.push(new No([u])),i=d}return t}fromJSON(e){let t=new Ft;for(let s of e){let n=new No;for(let i in s){let o=this.getTypeOid(i),a=s[i];for(let c of a){let d=this.createAttribute(o,c);n.push(d)}}t.push(n)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){let s=new ec({type:e});if(typeof t=="object")for(let n in t)switch(n){case"ia5String":s.value.ia5String=t[n];break;case"utf8String":s.value.utf8String=t[n];break;case"universalString":s.value.universalString=t[n];break;case"bmpString":s.value.bmpString=t[n];break;case"printableString":s.value.printableString=t[n];break}else if(t[0]==="#")s.value.anyValue=Ue.FromHex(t.slice(1));else{let n=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?s.value.ia5String=n:r.isPrintableString(n)?s.value.printableString=n:s.value.utf8String=n}return s}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/ig,`
31
- `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return pe.serialize(this.asn)}async getThumbprint(...e){var t;let s,n="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.toArrayBuffer())}},CA="Cannot initialize GeneralName from ASN.1 data.",lA=`${CA} Unsupported string format in use.`,ej=`${CA} Value doesn't match to GUID regular expression.`,hA=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,pA="1.3.6.1.4.1.311.25.1",mA="1.3.6.1.4.1.311.20.2.3",Dw="dns",Mw="dn",Uw="email",jw="ip",Hw="url",Fw="guid",qw="upn",Ag="id",Qn=class extends Zo{constructor(...e){let t;if(e.length===2)switch(e[0]){case Mw:{let s=new ln(e[1]).toArrayBuffer(),n=pe.parse(s,Ft);t=new We({directoryName:n});break}case Dw:t=new We({dNSName:e[1]});break;case Uw:t=new We({rfc822Name:e[1]});break;case Fw:{let s=new RegExp(hA,"i").exec(e[1]);if(!s)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let n=s.slice(1).map((i,o)=>o<3?Ue.ToHex(new Uint8Array(Ue.FromHex(i)).reverse()):i).join("");t=new We({otherName:new Oo({typeId:pA,value:pe.serialize(new ze(Ue.FromHex(n)))})});break}case jw:t=new We({iPAddress:e[1]});break;case Ag:t=new We({registeredID:e[1]});break;case qw:{t=new We({otherName:new Oo({typeId:mA,value:pe.serialize(u1.toASN(e[1]))})});break}case Hw:t=new We({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else be.isBufferSource(e[0])?t=pe.parse(e[0],We):t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=Dw,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Uw,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=jw,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=Hw,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Ag,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Mw,this.value=new ln(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===pA){this.type=Fw;let t=pe.parse(e.otherName.value,ze),s=new RegExp(hA,"i").exec(Ue.ToHex(t));if(!s)throw new Error(ej);this.value=s.slice(1).map((n,i)=>i<3?Ue.ToHex(new Uint8Array(Ue.FromHex(n)).reverse()):n).join("-")}else if(e.otherName.typeId===mA)this.type=qw,this.value=pe.parse(e.otherName.value,hr).toString();else throw new Error(lA);else throw new Error(lA)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Mw:case Dw:case Fw:case jw:case Ag:case qw:case Hw:e=this.type.toUpperCase();break;case Uw:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Ag&&(t=Zn.toString(t)),new Rt(e,void 0,t)}},Fi=class extends Zo{constructor(e){let t;if(e instanceof Xt)t=e;else if(Array.isArray(e)){let s=[];for(let n of e)if(n instanceof We)s.push(n);else{let i=pe.parse(new Qn(n.type,n.value).rawData,We);s.push(i)}t=new Xt(s)}else if(be.isBufferSource(e))t=pe.parse(e,Xt);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(t)}onInit(e){let t=[];for(let s of e){let n=null;try{n=new Qn(s)}catch{continue}t.push(n)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let s=t.toTextObject(),n=e[s[Rt.NAME]];Array.isArray(n)||(n=[],e[s[Rt.NAME]]=n),n.push(s)}return e}};Fi.NAME="GeneralNames";Rh="-{5}",Bh="\\n",tj=`[^${Bh}]+`,rj=`${Rh}BEGIN (${tj}(?=${Rh}))${Rh}`,sj=`${Rh}END \\1${Rh}`,Eu="\\n",nj=`[^:${Bh}]+`,ij=`(?:[^${Bh}]+${Eu}(?: +[^${Bh}]+${Eu})*)`,oj="[a-zA-Z0-9=+/]+",aj=`(?:${oj}${Eu})+`,gA=`${rj}${Eu}(?:((?:${nj}: ${ij})+))?${Eu}?(${aj})${sj}`,Nr=class{static isPem(e){return typeof e=="string"&&new RegExp(gA,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(gA,"g"),s=[],n=null;for(;n=t.exec(e);){let i=n[3].replace(new RegExp(`[${Bh}]+`,"g"),""),o={type:n[1],headers:[],rawData:Ue.FromBase64(i)},a=n[2];if(a){let c=a.split(new RegExp(Eu,"g")),d=null;for(let u of c){let[f,h]=u.split(/:(.*)/);if(h===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=f.trim()}else d&&o.headers.push(d),d={key:f,value:h.trim()}}d&&o.headers.push(d)}s.push(o)}return s}static decode(e){return this.decodeWithHeaders(e).map(s=>s.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){let s=new Array;return t?e.forEach(n=>{if(!be.isBufferSource(n))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");s.push(this.encodeStruct({type:t,rawData:be.toArrayBuffer(n)}))}):e.forEach(n=>{if(!("type"in n))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");s.push(this.encodeStruct(n))}),s.join(`
32
- `)}else{if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:be.toArrayBuffer(e)})}}static encodeStruct(e){var t;let s=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${s}-----`),!((t=e.headers)===null||t===void 0)&&t.length){for(let d of e.headers)n.push(`${d.key}: ${d.value}`);n.push("")}let i=Ue.ToBase64(e.rawData),o,a=0,c=Array();for(;a<i.length&&(i.length-a<64?o=i.substring(a):(o=i.substring(a,a+64),a+=64),o.length!==0);)if(c.push(o),o.length<64)break;return n.push(...c),n.push(`-----END ${s}-----`),n.join(`
33
- `)}};Nr.CertificateTag="CERTIFICATE";Nr.CrlTag="CRL";Nr.CertificateRequestTag="CERTIFICATE REQUEST";Nr.PublicKeyTag="PUBLIC KEY";Nr.PrivateKeyTag="PRIVATE KEY";ea=class r extends Zo{static isAsnEncoded(e){return be.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Nr.isPem(e))return Nr.decode(e)[0];if(Ue.isHex(e))return Ue.FromHex(e);if(Ue.isBase64(e))return Ue.FromBase64(e);if(Ue.isBase64Url(e))return Ue.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let t=be.toUint8Array(e);if(t.length>0&&t[0]===48)return be.toArrayBuffer(e);let s=Ue.ToBinary(e);if(Nr.isPem(s))return Nr.decode(s)[0];if(Ue.isHex(s))return Ue.FromHex(s);if(Ue.isBase64(s))return Ue.FromBase64(s);if(Ue.isBase64Url(s))return Ue.FromBase64Url(s);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){r.isAsnEncoded(e[0])?super(r.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Nr.encode(this.rawData,this.tag):super.toString(e)}},ji=class r extends ea{static async create(e,t=pr.get()){if(e instanceof r)return e;if(Ph.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let s=await t.subtle.exportKey("spki",e);return new r(s)}else{if(e.publicKey)return e.publicKey;if(be.isBufferSource(e))return new r(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){ea.isAsnEncoded(e)?super(e,Rr):super(e),this.tag=Nr.PublicKeyTag}async export(...e){let t,s=["verify"],n={hash:"SHA-256",...this.algorithm};e.length>1?(n=e[0]||n,s=e[1]||s,t=e[2]||pr.get()):t=e[0]||pr.get();let i=this.rawData,o=pe.parse(this.rawData,Rr);return o.algorithm.algorithm===$o&&(i=cj(o,i)),t.subtle.importKey("spki",i,n,!0,s)}onInit(e){let t=Kt.resolve(Lc),s=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===Gn){let n=pe.parse(e.subjectPublicKey,mu),i=be.toUint8Array(n.modulus);s.publicExponent=be.toUint8Array(n.publicExponent),s.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var t;let s,n="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,s="SHA-1";e.length===1?typeof e[0]=="string"?(s=e[0],t=pr.get()):t=e[0]:e.length===2?(s=e[0],t=e[1]):t=pr.get();let n=pe.parse(this.rawData,Rr);return await t.subtle.digest(s,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=pe.parse(this.rawData,Rr);switch(e.Algorithm=Hi.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Sc:e["EC Point"]=t.subjectPublicKey;break;case Gn:default:e["Raw Data"]=t.subjectPublicKey}return e}};Ng=class r extends Is{static async create(e,t=!1,s=pr.get()){if("name"in e&&"serialNumber"in e)return new r(e,t);let i=await(await ji.create(e,s)).getKeyIdentifier(s);return new r(Ue.ToHex(i),t)}constructor(...e){if(be.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let t=new qn({keyIdentifier:new nc(Ue.FromHex(e[0]))});super(Pm,e[1],pe.serialize(t))}else{let t=e[0],s=t.name instanceof Fi?pe.parse(t.name.rawData,Xt):t.name,n=new qn({authorityCertIssuer:s,authorityCertSerialNumber:Ue.FromHex(t.serialNumber)});super(Pm,e[1],pe.serialize(n))}}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,qn);t.keyIdentifier&&(this.keyId=Ue.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Ue.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,qn);return t.authorityCertIssuer&&(e["Authority Issuer"]=new Fi(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}};Ng.NAME="Authority Key Identifier";Og=class extends Is{constructor(...e){if(be.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,ic);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new ic({cA:e[0],pathLenConstraint:e[1]});super(Bm,e[2],pe.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};Og.NAME="Basic Constraints";(function(r){r.serverAuth="1.3.6.1.5.5.7.3.1",r.clientAuth="1.3.6.1.5.5.7.3.2",r.codeSigning="1.3.6.1.5.5.7.3.3",r.emailProtection="1.3.6.1.5.5.7.3.4",r.timeStamping="1.3.6.1.5.5.7.3.8",r.ocspSigning="1.3.6.1.5.5.7.3.9"})(yA||(yA={}));Lg=class extends Is{constructor(...e){if(be.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,Cl);this.usages=t.map(s=>s)}else{let t=new Cl(e[0]);super(Mm,e[1],pe.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(t=>Zn.toString(t)).join(", "),e}};Lg.NAME="Extended Key Usages";(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(xA||(xA={}));Dg=class extends Is{constructor(...e){if(be.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,Wd);this.usages=t.toNumber()}else{let t=new Wd(e[0]);super(Um,e[1],pe.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,Wd);return e[""]=t.toJSON().join(", "),e}};Dg.NAME="Key Usages";Mg=class r extends Is{static async create(e,t=!1,s=pr.get()){let i=await(await ji.create(e,s)).getKeyIdentifier(s);return new r(Ue.ToHex(i),t)}constructor(...e){if(be.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,us);this.keyId=Ue.ToHex(t)}else{let t=typeof e[0]=="string"?Ue.FromHex(e[0]):e[0],s=new us(t);super(G1,e[1],pe.serialize(s)),this.keyId=Ue.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,us);return e[""]=t,e}};Mg.NAME="Subject Key Identifier";Ug=class extends Is{constructor(...e){be.isBufferSource(e[0])?super(e[0]):super(V1,e[1],new Fi(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,qm);this.names=new Fi(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let s in t)e[s]=t[s];return e}};Ug.NAME="Subject Alternative Name";rs=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Is(e),s=this.items.get(t.type);return s?new s(e):t}};rs.items=new Map;jg=class extends Is{constructor(...e){var t;if(be.isBufferSource(e[0])){super(e[0]);let s=pe.parse(this.value,vl);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(t=e[1])!==null&&t!==void 0?t:!1,i=new vl(s.map(o=>new oc({policyIdentifier:o})));super(Om,n,pe.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(t=>new Rt("",{},Zn.toString(t))),e}};jg.NAME="Certificate Policies";rs.register(Om,jg);Hg=class extends Is{constructor(...e){var t;if(be.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new zn({distributionPoint:new Ni({fullName:[new We({uniformResourceIdentifier:o})]})})),i=new Mo(n);super(Lm,e[1],pe.serialize(i))}else{let s=new Mo(e[0]);super(Lm,e[1],pe.serialize(s))}(t=this.distributionPoints)!==null&&t!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Mo);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(t=>{var s;let n={};return t.distributionPoint&&(n[""]=(s=t.distributionPoint.fullName)===null||s===void 0?void 0:s.map(i=>new Qn(i).toString()).join(", ")),t.reasons&&(n.Reasons=t.reasons.toString()),t.cRLIssuer&&(n["CRL Issuer"]=t.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};Hg.NAME="CRL Distribution Points";Fg=class extends Is{constructor(...e){var t,s,n,i;if(be.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof sc){let o=new sc(e[0]);super(km,e[1],pe.serialize(o))}else{let o=e[0],a=new sc;Rg(a,o,C1,"ocsp"),Rg(a,o,T1,"caIssuers"),Rg(a,o,A1,"timeStamping"),Rg(a,o,I1,"caRepository"),super(km,e[1],pe.serialize(a))}(t=this.ocsp)!==null&&t!==void 0||(this.ocsp=[]),(s=this.caIssuers)!==null&&s!==void 0||(this.caIssuers=[]),(n=this.timeStamping)!==null&&n!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],pe.parse(e.extnValue,sc).forEach(s=>{switch(s.accessMethod){case C1:this.ocsp.push(new Qn(s.accessLocation));break;case T1:this.caIssuers.push(new Qn(s.accessLocation));break;case A1:this.timeStamping.push(new Qn(s.accessLocation));break;case I1:this.caRepository.push(new Qn(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Ig(e,"OCSP",this.ocsp),this.caIssuers.length&&Ig(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Ig(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Ig(e,"CA Repository",this.caRepository),e}};Fg.NAME="Authority Info Access";qg=class extends Is{constructor(...e){be.isBufferSource(e[0])?super(e[0]):super(F1,e[1],new Fi(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Xt);this.names=new Fi(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let s in t)e[s]=t[s];return e}};qg.NAME="Issuer Alternative Name";Cu=class r extends Zo{constructor(...e){let t;if(be.isBufferSource(e[0]))t=be.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>be.toArrayBuffer(i)):[];t=pe.serialize(new Ir({type:s,values:n}))}super(t,Ir)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(t=>new Rt("",{"":t})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Rt.NAME]===r.NAME&&(e[Rt.NAME]=Zn.toString(this.type)),e}};Cu.NAME="Attribute";zg=class extends Cu{constructor(...e){var t;if(be.isBufferSource(e[0]))super(e[0]);else{let s=new oh({printableString:e[0]});super(Pw,[pe.serialize(s)])}(t=this.password)!==null&&t!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let t=pe.parse(this.values[0],oh);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Rt.VALUE]=this.password,e}};zg.NAME="Challenge Password";Nh=class extends Cu{constructor(...e){var t;if(be.isBufferSource(e[0]))super(e[0]);else{let s=e[0],n=new Ts;for(let i of s)n.push(pe.parse(i.rawData,Kr));super(ch,[pe.serialize(n)])}(t=this.items)!==null&&t!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let t=pe.parse(this.values[0],Ts);this.items=t.map(s=>rs.create(pe.serialize(s)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(s=>s.toTextObject());for(let s of t)e[s[Rt.NAME]]=s;return e}};Nh.NAME="Extensions";Tu=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Cu(e),s=this.items.get(t.type);return s?new s(e):t}};Tu.items=new Map;Lh="crypto.signatureFormatter",Ww=class{toAsnSignature(e,t){return be.toArrayBuffer(t)}toWebSignature(e,t){return be.toArrayBuffer(t)}},Gw=Pg=class{static createPssParams(e,t){let s=Pg.getHashAlgorithm(e);return s?new Xn({hashAlgorithm:s,maskGenAlgorithm:new fe({algorithm:Vo,parameters:pe.serialize(s)}),saltLength:t}):null}static getHashAlgorithm(e){let t=Kt.resolve(Lc);return typeof e=="string"?t.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let t;if(typeof e.hash=="string")t=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")t=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(t.toLowerCase()){case"sha-1":return new fe({algorithm:uu,parameters:null});case"sha-256":return new fe({algorithm:og,parameters:null});case"sha-384":return new fe({algorithm:fu,parameters:null});case"sha-512":return new fe({algorithm:lu,parameters:null})}}else return new fe({algorithm:Gn,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let t=Pg.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new fe({algorithm:$o,parameters:pe.serialize(t)})}else return new fe({algorithm:$o,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Gn:return{name:"RSASSA-PKCS1-v1_5"};case uu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case og:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case fu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case lu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case $o:if(e.parameters){let t=pe.parse(e.parameters,Xn);return{name:"RSA-PSS",hash:Kt.resolve(Lc).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}else return{name:"RSA-PSS"}}return null}};Gw=Pg=p([Go()],Gw);Kt.registerSingleton(Oh,Gw);Xw=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new fe({algorithm:Ec});case"sha-256":return new fe({algorithm:Cc});case"sha-384":return new fe({algorithm:Tc});case"sha-512":return new fe({algorithm:Ac})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ec:return{name:"SHA-1"};case Cc:return{name:"SHA-256"};case Tc:return{name:"SHA-384"};case Ac:return{name:"SHA-512"}}return null}};Xw=p([Go()],Xw);Kt.registerSingleton(Oh,Xw);qi=class r{addPadding(e,t){let s=be.toUint8Array(t),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,t=!1){let s=be.toUint8Array(e);for(let n=0;n<s.length;n++)if(s[n]){s=s.slice(n);break}if(t&&s[0]>127){let n=new Uint8Array(s.length+1);return n.set(s,1),n.buffer}return s.buffer}toAsnSignature(e,t){if(e.name==="ECDSA"){let s=e.namedCurve,n=r.namedCurveSize.get(s)||r.defaultNamedCurveSize,i=new _c,o=be.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),pe.serialize(i)}return null}toWebSignature(e,t){if(e.name==="ECDSA"){let s=pe.parse(t,_c),n=e.namedCurve,i=r.namedCurveSize.get(n)||r.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(s.r)),a=this.addPadding(i,this.removePadding(s.s));return B6(o,a)}return null}};qi.namedCurveSize=new Map;qi.defaultNamedCurveSize=32;zw="1.3.101.110",bA="1.3.101.111",$w="1.3.101.112",vA="1.3.101.113",Yw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=$w;break;case"x25519":t=zw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=$w;break;case"ed448":t=vA;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=zw;break;case"x448":t=bA;break}}return t?new fe({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case $w:return{name:"Ed25519"};case vA:return{name:"EdDSA",namedCurve:"Ed448"};case zw:return{name:"X25519"};case bA:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Yw=p([Go()],Yw);Kt.registerSingleton(Oh,Yw);Jw=class extends ea{get subjectName(){return ht(this,lh,"f")||Gt(this,lh,new ln(this.asn.certificationRequestInfo.subject),"f"),ht(this,lh,"f")}get subject(){return ht(this,hh,"f")||Gt(this,hh,this.subjectName.toString(),"f"),ht(this,hh,"f")}get signatureAlgorithm(){if(!ht(this,ph,"f")){let e=Kt.resolve(Lc);Gt(this,ph,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,ph,"f")}get signature(){return ht(this,mh,"f")||Gt(this,mh,this.asn.signature,"f"),ht(this,mh,"f")}get publicKey(){return ht(this,gh,"f")||Gt(this,gh,new ji(this.asn.certificationRequestInfo.subjectPKInfo),"f"),ht(this,gh,"f")}get attributes(){return ht(this,yh,"f")||Gt(this,yh,this.asn.certificationRequestInfo.attributes.map(e=>Tu.create(pe.serialize(e))),"f"),ht(this,yh,"f")}get extensions(){if(!ht(this,Su,"f")){Gt(this,Su,[],"f");let e=this.getAttribute(ch);e instanceof Nh&&Gt(this,Su,e.items,"f")}return ht(this,Su,"f")}get tbs(){return ht(this,fh,"f")||Gt(this,fh,this.asn.certificationRequestInfoRaw||pe.serialize(this.asn.certificationRequestInfo),"f"),ht(this,fh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Qo]:[e];super(t[0],t[1]),fh.set(this,void 0),lh.set(this,void 0),hh.set(this,void 0),ph.set(this,void 0),mh.set(this,void 0),gh.set(this,void 0),yh.set(this,void 0),Su.set(this,void 0),this.tag=Nr.CertificateRequestTag}onInit(e){}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=pr.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(t,["verify"],e),n=Kt.resolveAll(Lh).reverse(),i=null;for(let a of n)if(i=a.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,s,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=pe.parse(this.rawData,Qo),s=t.certificationRequestInfo,n=new Rt("",{Version:`${$n[s.version]} (${s.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new Rt("");for(let o of this.attributes){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:Hi.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};fh=new WeakMap,lh=new WeakMap,hh=new WeakMap,ph=new WeakMap,mh=new WeakMap,gh=new WeakMap,yh=new WeakMap,Su=new WeakMap;Jw.NAME="PKCS#10 Certificate Request";$g=class extends ea{get publicKey(){return ht(this,Ih,"f")||Gt(this,Ih,new ji(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),ht(this,Ih,"f")}get serialNumber(){if(!ht(this,bh,"f")){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),Gt(this,bh,Ue.ToHex(t),"f")}return ht(this,bh,"f")}get subjectName(){return ht(this,vh,"f")||Gt(this,vh,new ln(this.asn.tbsCertificate.subject),"f"),ht(this,vh,"f")}get subject(){return ht(this,wh,"f")||Gt(this,wh,this.subjectName.toString(),"f"),ht(this,wh,"f")}get issuerName(){return ht(this,Sh,"f")||Gt(this,Sh,new ln(this.asn.tbsCertificate.issuer),"f"),ht(this,Sh,"f")}get issuer(){return ht(this,_h,"f")||Gt(this,_h,this.issuerName.toString(),"f"),ht(this,_h,"f")}get notBefore(){if(!ht(this,Eh,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Gt(this,Eh,e,"f")}return ht(this,Eh,"f")}get notAfter(){if(!ht(this,Ch,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Gt(this,Ch,e,"f")}return ht(this,Ch,"f")}get signatureAlgorithm(){if(!ht(this,Th,"f")){let e=Kt.resolve(Lc);Gt(this,Th,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,Th,"f")}get signature(){return ht(this,Ah,"f")||Gt(this,Ah,this.asn.signatureValue,"f"),ht(this,Ah,"f")}get extensions(){return ht(this,_u,"f")||(Gt(this,_u,[],"f"),this.asn.tbsCertificate.extensions&&Gt(this,_u,this.asn.tbsCertificate.extensions.map(e=>rs.create(pe.serialize(e))),"f")),ht(this,_u,"f")}get tbs(){return ht(this,xh,"f")||Gt(this,xh,this.asn.tbsCertificateRaw||pe.serialize(this.asn.tbsCertificate),"f"),ht(this,xh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Ks]:[e];super(t[0],t[1]),xh.set(this,void 0),bh.set(this,void 0),vh.set(this,void 0),wh.set(this,void 0),Sh.set(this,void 0),_h.set(this,void 0),Eh.set(this,void 0),Ch.set(this,void 0),Th.set(this,void 0),Ah.set(this,void 0),_u.set(this,void 0),Ih.set(this,void 0),this.tag=Nr.CertificateTag}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e=="string"){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e=="string"?t.type===e:t instanceof e)}async verify(e={},t=pr.get()){let s,n,i=e.publicKey;try{if(!i)s={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(s,["verify"],t);else if("publicKey"in i)s={...i.publicKey.algorithm,...this.signatureAlgorithm},n=await i.publicKey.export(s,["verify"],t);else if(i instanceof ji)s={...i.algorithm,...this.signatureAlgorithm},n=await i.export(s,["verify"],t);else if(be.isBufferSource(i)){let d=new ji(i);s={...d.algorithm,...this.signatureAlgorithm},n=await d.export(s,["verify"],t)}else s={...i.algorithm,...this.signatureAlgorithm},n=i}catch{return!1}let o=Kt.resolveAll(Lh).reverse(),a=null;for(let d of o)if(a=d.toWebSignature(s,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await t.subtle.verify(this.signatureAlgorithm,n,a,this.tbs);if(e.signatureOnly)return c;{let u=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let t,s="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(s=e[0]||s,t=e[1])),t??(t=pr.get()),await t.subtle.digest(s,this.rawData)}async isSelfSigned(e=pr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=pe.parse(this.rawData,Ks),s=t.tbsCertificate,n=new Rt("",{Version:`${$n[s.version]} (${s.version})`,"Serial Number":s.serialNumber,"Signature Algorithm":Hi.serializeAlgorithm(s.signature),Issuer:this.issuer,Validity:new Rt("",{"Not Before":s.validity.notBefore.getTime(),"Not After":s.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(s.issuerUniqueID&&(n["Issuer Unique ID"]=s.issuerUniqueID),s.subjectUniqueID&&(n["Subject Unique ID"]=s.subjectUniqueID),this.extensions.length){let i=new Rt("");for(let o of this.extensions){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:Hi.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};xh=new WeakMap,bh=new WeakMap,vh=new WeakMap,wh=new WeakMap,Sh=new WeakMap,_h=new WeakMap,Eh=new WeakMap,Ch=new WeakMap,Th=new WeakMap,Ah=new WeakMap,_u=new WeakMap,Ih=new WeakMap;$g.NAME="Certificate";Vg=class{static async createSelfSigned(e,t=pr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=pr.get()){var s;let n;e.publicKey instanceof ji?n=e.publicKey.rawData:"publicKey"in e.publicKey?n=e.publicKey.publicKey.rawData:be.isBufferSource(e.publicKey)?n=e.publicKey:n=await t.subtle.exportKey("spki",e.publicKey);let i=dj(e.serialNumber,t),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new Ks({tbsCertificate:new kr({version:$n.v3,serialNumber:i,validity:new Oi({notBefore:o,notAfter:a}),extensions:new Ts(((s=e.extensions)===null||s===void 0?void 0:s.map(C=>pe.parse(C.rawData,Kr)))||[]),subjectPublicKeyInfo:pe.parse(n,Rr)})});if(e.subject){let C=e.subject instanceof ln?e.subject:new ln(e.subject);c.tbsCertificate.subject=pe.parse(C.toArrayBuffer(),Ft)}if(e.issuer){let C=e.issuer instanceof ln?e.issuer:new ln(e.issuer);c.tbsCertificate.issuer=pe.parse(C.toArrayBuffer(),Ft)}let d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},f=Kt.resolve(Lc);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(u);let h=pe.serialize(c.tbsCertificate),y="signingKey"in e?await t.subtle.sign(u,e.signingKey,h):e.signature,v=Kt.resolveAll(Lh).reverse(),S=null;for(let C of v)if(S=C.toAsnSignature(u,y),S)break;if(!S)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=S,new $g(pe.serialize(c))}};(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(wA||(wA={}));uj=new WeakMap,fj=new WeakMap,lj=new WeakMap,hj=new WeakMap,pj=new WeakMap;mj=new WeakMap,gj=new WeakMap,yj=new WeakMap,xj=new WeakMap,bj=new WeakMap,vj=new WeakMap,wj=new WeakMap;rs.register(Bm,Og);rs.register(Mm,Lg);rs.register(Um,Dg);rs.register(G1,Mg);rs.register(Pm,Ng);rs.register(V1,Ug);rs.register(Lm,Hg);rs.register(km,Fg);rs.register(F1,qg);Tu.register(Pw,zg);Tu.register(ch,Nh);Kt.registerSingleton(Lh,Ww);Kt.registerSingleton(Lh,qi);qi.namedCurveSize.set("P-256",32);qi.namedCurveSize.set("K-256",32);qi.namedCurveSize.set("P-384",48);qi.namedCurveSize.set("P-521",66)});var IA=se((Hfe,AA)=>{"use strict";function _j(r){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(r)}AA.exports=_j});var Dh=se((Ffe,MA)=>{"use strict";var RA=require("util"),NA=IA(),kA=/[\{\[]/,PA=/[\}\]]/,BA=["do","if","in","for","let","new","try","var","case","else","enum","eval","null","this","true","void","with","await","break","catch","class","const","false","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof","NaN","undefined"],OA={};for(Kg=0;Kg<BA.length;Kg++)OA[BA[Kg]]=!0;var Kg,Ej=function(r){return NA(r)&&!OA.hasOwnProperty(r)},LA={s:function(r){return""+r},d:function(r){return""+Number(r)},o:function(r){return JSON.stringify(r)}},DA=function(){var r=[],e=0,t={},s=function(o){for(var a="";a.length<e*2;)a+=" ";r.push(a+o)},n=function(o){if(PA.test(o.trim()[0])&&kA.test(o[o.length-1])){e--,s(o),e++;return}if(kA.test(o[o.length-1])){s(o),e++;return}if(PA.test(o.trim()[0])){e--,s(o);return}s(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
34
- `)>-1)for(var a=o.trim().split(`
35
- `),c=0;c<a.length;c++)n(a[c].trim());else n(RA.format.apply(RA,arguments));return i};return i.scope={},i.formats=LA,i.sym=function(o){return(!o||!Ej(o))&&(o="tmp"),t[o]||(t[o]=0),o+(t[o]++||"")},i.property=function(o,a){return arguments.length===1&&(a=o,o=""),a=a+"",NA(a)?o?o+"."+a:a:o?o+"["+JSON.stringify(a)+"]":JSON.stringify(a)},i.toString=function(){return r.join(`
36
- `)},i.toFunction=function(o){o||(o={});var a="return ("+i.toString()+")";Object.keys(i.scope).forEach(function(u){o[u]||(o[u]=i.scope[u])});var c=Object.keys(o).map(function(u){return u}),d=c.map(function(u){return o[u]});return Function.apply(null,c.concat(a)).apply(null,d)},arguments.length&&i.apply(null,arguments),i};DA.formats=LA;MA.exports=DA});var jA=se((qfe,UA)=>{"use strict";var Gg=class{constructor(){this.next=null,this.buffer=null}};UA.exports=class Wg{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let t=new Gg;t.buffer=e,this.length>0?this.tail.next=t:this.head=t,this.tail=t,this.length+=e.length,this.count+=1}unshift(e){let t=new Gg;t.buffer=e,t.next=this.head,this.isEmpty()&&(this.tail=t),this.head=t,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,t){if(e<0||e>=this.length)return new Wg;if(t<0||t>this.length||t<e)return new Wg;let s=new Wg,n=this.head,i=e,o=t;for(;n;){if(n.buffer.length>i){i===0&&n.buffer.length<=o?s.push(n.buffer):n.buffer.length>=o?s.push(n.buffer.slice(i,o)):s.push(n.buffer.slice(i));break}i-=n.buffer.length,o-=n.buffer.length,n=n.next}if(n.buffer.length<o)for(;n;){if(n.buffer.length===o){s.push(n.buffer);break}else if(n.buffer.length>o){s.push(n.buffer.slice(0,o));break}else i<0&&n.buffer.length<o&&s.push(n.buffer);i-=n.buffer.length,o-=n.buffer.length,n=n.next}return s}}});var zA=se((zfe,qA)=>{"use strict";var Xg=Dh(),Cj=jA(),Dc=class r{constructor(){this.queue=new Cj,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let t=this.queue.shift();this.queue.unshift(t.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let t=0;t<e.length;t+=1)this.append(e[t]);else if(e instanceof r){if(this.offset>0){let s=this.queue.shift();this.queue.unshift(s.slice(this.offset)),this.offset=0}if(e.offset>0){let s=e.queue.shift();e.queue.unshift(s.slice(e.offset)),e.offset=0}let t=e.queue.head;for(;t;)this.queue.push(t.buffer),t=t.next}}get(e){let t=e;for(;t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let s=this.queue.head,{offset:n}=this;for(;s;){if(s.buffer.length-n>t)return s.buffer[t+n];t-=s.buffer.length-n,n=0,s=s.next}}slice(e,t){for(typeof e!="number"&&(e=0),typeof t!="number"&&(t=this.length);e<0;)e+=this.length;for(;t<0;)t+=this.length;if(t=Math.min(t,this.length),e>=this.length||t===0)return Buffer.alloc(0);let s=e;e=Math.min(s,t),t=Math.max(s,t);let n=this.queue.slice(e+this.offset,t+this.offset);if(n.count===1)return n.first;let i=n.head,o=Buffer.allocUnsafe(n.length),a=0;for(let c=0;c<n.count;c+=1)o.set(i.buffer,a),a+=i.buffer.length,i=i.next;return o}toString(e,t,s){return this.slice(t,s).toString(e)}consume(e){let t=e;for(;this.length>0;){let s=this.queue.first.length-this.offset;if(t>=s)this.queue.shift(),t-=s,this.offset=0;else{this.offset+=t;break}}}indexOf(e,t=0){if(!Number.isInteger(e))throw new TypeError("Invalid argument 1");if(e<0||e>255)throw new Error("Invalid argument 1");for(Number.isInteger(t)||(t=0);t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let s=this.queue.head,n=0,i=()=>{n+=s.buffer.length,s=s.next};for(;s;){let o=0;if(s===this.queue.head&&(o+=this.offset),t>=s.buffer.length-o){t-=s.buffer.length-o,i();continue}t<s.buffer.length&&(o+=t);let a=s.buffer.indexOf(e,o);if(a>-1)return a+n-this.offset;i(),o>this.offset&&(t=0)}return-1}},HA={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(HA).forEach(r=>{let e=Xg();e(`
37
- function bufferlist_${r}(offset = 0) {
38
- const start = offset + this.offset;
39
- const head = this.queue.first;
40
- const size = ${e.formats.d(HA[r])};
41
- const isFirtsChunkEnough = head.length - start >= size;
42
-
43
- return isFirtsChunkEnough
44
- ? head.${r}(start)
45
- : this.slice(offset, offset + size).${r}(0)
46
- }
47
- `),Dc.prototype[r]=e.toFunction()});var Tj=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Tj.forEach(r=>{let e=Xg();e(`
48
- function bufferlist_${r}(size, offset = 0) {
49
- const start = offset + this.offset;
50
- const head = this.queue.first;
51
- const isFirtsChunkEnough = head.length - start >= size;
52
-
53
- return isFirtsChunkEnough
54
- ? head.${r}(start, size)
55
- : this.slice(offset, offset + size).${r}(0, size)
56
- }
57
- `),Dc.prototype[r]=e.toFunction()});var FA={writeDoubleBE:8,writeDoubleLE:8,writeFloatBE:4,writeFloatLE:4,writeInt32BE:4,writeInt32LE:4,writeUInt32BE:4,writeUInt32LE:4,writeInt16BE:2,writeInt16LE:2,writeUInt16BE:2,writeUInt16LE:2,writeInt8:1,writeUInt8:1};Object.keys(FA).forEach(r=>{let e=Xg();e(`
58
- function bufferlist_${r}(value) {
59
- const size = ${e.formats.d(FA[r])};
60
- const buf = Buffer.allocUnsafe(size);
61
- buf.${r}(value, 0);
62
- this.append(buf);
63
- }
64
- `),Dc.prototype[r]=e.toFunction()});var Aj=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Aj.forEach(r=>{let e=Xg();e(`
65
- function bufferlist_${r}(value, size) {
66
- const buf = Buffer.allocUnsafe(size);
67
- buf.${r}(value, 0, size);
68
- this.append(buf);
69
- }
70
- `),Dc.prototype[r]=e.toFunction()});qA.exports=Dc});var Au=se((Vfe,$A)=>{"use strict";$A.exports=class extends Error{constructor(e,t){let s=`requested ${e} bytes but only ${t} available`;super(s),this.name="NotEnoughDataError"}}});var Mh=se((Kfe,WA)=>{"use strict";var{Transform:Ij}=require("stream"),Yg=Dh(),Rj=zA(),kj=Au(),VA=Symbol("buffer"),Mc=class extends Ij{constructor(e={}){super(e),this[VA]=new Rj}get buffer(){return this[VA]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,t){return this.buffer.slice(e,t)}consume(e){this.buffer.consume(e)}toString(e,t,s){return this.buffer.toString(e,t,s)}indexOf(e,t=0){return this.buffer.indexOf(e,t)}readBuffer(e){Qw(e,this.length);let t=this.slice(0,e);return this.consume(e),t}writeBuffer(e){this.append(e)}},KA={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1},Pj=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(KA).forEach(r=>{let e=Yg();e(`
71
- function binary_${r}() {
72
- const bytes = ${e.formats.d(KA[r])};
73
- assertSize(bytes, this.length);
74
-
75
- const res = this.buffer.${r}(0);
76
- this.consume(bytes);
77
-
78
- return res;
79
- }
80
- `),Mc.prototype[r]=e.toFunction({assertSize:Qw})});Pj.forEach(r=>{let e=Yg();e(`
81
- function binary_${r}(size) {
82
- assertSize(size, this.length);
83
-
84
- const res = this.buffer.${r}(size, 0);
85
- this.consume(size);
86
- return res;
87
- }
88
- `),Mc.prototype[r]=e.toFunction({assertSize:Qw})});var Bj=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];Bj.forEach(r=>{let e=Yg();e(`
89
- function binary_${r}(value) {
90
- this.buffer.${r}(value);
91
- }
92
- `),Mc.prototype[r]=e.toFunction()});var Nj=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Nj.forEach(r=>{let e=Yg();e(`
93
- function binary_${r}(value, size) {
94
- this.buffer.${r}(value, size);
95
- }
96
- `),Mc.prototype[r]=e.toFunction()});function Qw(r,e){if(r>e)throw new kj(r,e)}WA.exports=Mc});var XA=se((Wfe,GA)=>{"use strict";GA.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var QA=se((Gfe,JA)=>{"use strict";var Oj=XA();function YA(r){return Oj(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}JA.exports=function(e){var t,s;return!(YA(e)===!1||(t=e.constructor,typeof t!="function")||(s=t.prototype,YA(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var ei=se((Xfe,ZA)=>{"use strict";var Lj=QA();ZA.exports={isType:Dj,isUserType:Lj,isFunction:Uh,isDecodeType:Mj,isEncodeType:Uj};function Dj(r){return Zw(r)&&Uh(r.encode)&&Uh(r.decode)}function Uh(r){return typeof r=="function"}function Zw(r){return typeof r=="object"&&r!==null}function Mj(r){return Zw(r)&&Uh(r.decode)}function Uj(r){return Zw(r)&&Uh(r.encode)}});var ta=se((Yfe,e5)=>{"use strict";var jj=Symbol("skip"),Hj=Symbol("bytes");e5.exports={skip:jj,bytes:Hj}});var ra=se((Jfe,r5)=>{"use strict";var t5=ta();r5.exports=class Jg{constructor(){this[t5.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[t5.bytes]}static clone(e){let t=new Jg;return e instanceof Jg&&(t.node=e.node,t.current=e.current),t}static clean(e){e instanceof Jg&&(e.node=void 0,e.current=void 0)}}});var Iu=se((Qfe,a5)=>{"use strict";var{isType:Fj,isUserType:qj,isDecodeType:zj}=ei(),$j=Mh(),eS=ta(),s5=ra();a5.exports={decode:n5,decodeCommon:i5};function n5(r,e){let t=r;Buffer.isBuffer(r)&&(t=new $j,t.append(r));let s=new s5,n=i5(t,e,s);return n5.bytes=s.bytes,s5.clean(s),n}function i5(r,e,t){if(Fj(e)){let s=e.decode.call(t,r);return t[eS.bytes]+=e.decode.bytes,s}return o5(r,e,t)}function o5(r,e,t){Vj(e);let s=Object.create(null);t.node===void 0&&(t.node=s),t.current=s;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],a=e[o];if(!zj(a)){s[o]=o5(r,a,t),t.current=s;continue}let c=a.decode.call(t,r);t[eS.bytes]+=a.decode.bytes,a[eS.skip]!==!0&&(s[o]=c)}return s}function Vj(r){if(!qj(r))throw new TypeError("Argument #2 should be a plain object.")}});var jh=se((Zfe,h5)=>{"use strict";var{isUserType:Kj,isEncodeType:Wj,isType:Gj}=ei(),d5=ta(),c5=ra(),tS=Mh();h5.exports={encode:u5,encodeCommon:f5};function u5(r,e,t){let s=new c5;if(e instanceof tS){let n=t;t=e,e=n}return t instanceof tS||(t=new tS),f5(r,t,e,s),u5.bytes=s.bytes,c5.clean(s),t}function f5(r,e,t,s){Gj(t)?(t.encode.call(s,r,e),s[d5.bytes]+=t.encode.bytes):l5(r,e,t,s)}function l5(r,e,t,s){Xj(t),s.node===void 0&&(s.node=r),s.current=r;let n=Object.keys(t);for(let i=0;i<n.length;i+=1){let o=n[i],a=t[o],c=r[o];if(!Wj(a)){l5(c,e,a,s),s.current=r;continue}a.encode.call(s,c,e),s[d5.bytes]+=a.encode.bytes}}function Xj(r){if(!Kj(r))throw new TypeError("Argument `schema` should be a plain object.")}});var Hh=se((ele,b5)=>{"use strict";var{isUserType:Yj,isType:m5}=ei(),p5=ra(),g5=ta();b5.exports={encodingLength:Jj,encodingLengthCommon:y5};function Jj(r,e){let t=new p5;return y5(r,e,t),p5.clean(t),t.bytes}function y5(r,e,t){m5(e)?t[g5.bytes]+=e.encodingLength.call(t,r):x5(r,e,t)}function x5(r,e,t){if(!Yj(e))throw new TypeError("Argument `schema` should be a plain object.");t.node===void 0&&(t.node=r),t.current=r;let s=Object.keys(e);for(let n=0;n<s.length;n+=1){let i=s[n],o=e[i],a=r[i];if(!m5(o)){x5(a,o,t),t.current=r;continue}t[g5.bytes]+=o.encodingLength.call(t,a)}}});var A5=se((tle,T5)=>{"use strict";var{decodeCommon:C5}=Iu(),{encodeCommon:Qj}=jh(),{encodingLengthCommon:v5}=Hh(),{isType:w5,isUserType:Zj,isFunction:eH}=ei(),sa=ra();T5.exports=tH;function tH(r,e,t="count"){if(!w5(r)&&!Zj(r))throw new TypeError("Argument #1 should be a valid type.");let s=t==="bytes",n=typeof e=="number",i=w5(e),o=eH(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,f){S5(u);let h=sa.clone(this);a.bytes=0;let y=0;if(i?y=u.length:n?y=e:o&&(y=e(h),_5(y)),s||E5(y,u.length),s){let v=sa.clone(h);for(let S of u)v5(S,r,v);i&&(y=v.bytes),E5(v.bytes,y),sa.clean(v)}i&&(e.encode.call(h,y,f),a.bytes+=e.encode.bytes),u.forEach(v=>{Qj(v,f,r,h)}),a.bytes+=h.bytes,sa.clean(h)}function c(u){let f=0;c.bytes=0;let h=sa.clone(this);n?f=e:i?(f=e.decode.call(h,u),c.bytes+=e.decode.bytes):o&&(f=e(h)),_5(f);let y;return s?y=rH(r,f,u,h):y=sH(r,f,u,h),c.bytes+=h.bytes,sa.clean(h),y}function d(u){S5(u);let f=sa.clone(this),h=0;if(n&&s)return e;i&&!s&&(h=e.encodingLength(u.length));for(let y of u)v5(y,r,f);return sa.clean(f),h+=f.bytes,i&&s&&(h+=e.encodingLength(h)),h}}function S5(r){if(!Array.isArray(r))throw new TypeError("Argument #1 should be an Array.")}function _5(r){if(typeof r!="number")throw new TypeError("Length of an array should be a number.")}function E5(r,e){if(r!==e)throw new Error(`Argument #1 required length ${r} instead of ${e}`)}function rH(r,e,t,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(C5(t,r,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function sH(r,e,t,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=C5(t,r,s);return n}});var P5=se((rle,k5)=>{"use strict";var{isType:nH,isFunction:iH}=ei(),oH=Au(),aH=Mh();k5.exports=cH;function cH(r){let e=typeof r=="number",t=nH(r),s=iH(r),n=r===null;if(!e&&!t&&!s&&!n)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,d){I5(c),i.bytes=0;let u=this;if(e&&R5(r,c.length),t&&(r.encode.call(u,c.length,d),i.bytes+=r.encode.bytes),s){let f=r(u);rS(f),R5(f,c.length)}d.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),i.bytes+=c.length,n&&(d.writeUInt8(0),i.bytes+=1)}function o(c){let d=0;o.bytes=0;let u=this;if(e)d=r;else if(t)d=r.decode.call(u,c),o.bytes+=r.decode.bytes,rS(d);else if(s)d=r(u),rS(d);else if(n&&(d=c.indexOf(0),d===-1))throw new oH(c.length+1,c.length);let f=c.readBuffer(d);return o.bytes+=d,n&&(o.bytes+=1,c.consume(1)),f}function a(c){I5(c);let d=0;return e?r:(n?d=1:t&&(d=r.encodingLength(c.length)),d+c.length)}}function I5(r){if(!Buffer.isBuffer(r)&&!(r instanceof aH))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function R5(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}function rS(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}});var N5=se((sle,B5)=>{"use strict";var{isType:dH}=ei();B5.exports=uH;function uH(r){if(!dH(r))throw new TypeError("Argument #1 should be valid type.");function e(s){let n=this,i=r.decode.call(n,s);return e.bytes=r.decode.bytes,!!i}function t(s,n){let i=this;r.encode.call(i,s?1:0,n),t.bytes=r.encode.bytes}return{encode:t,decode:e,encodingLength:r.encodingLength}}});var L5=se((nle,O5)=>{"use strict";var{decodeCommon:fH}=Iu(),{encodeCommon:lH}=jh(),{encodingLengthCommon:hH}=Hh(),{isType:pH,isFunction:Qg}=ei(),mH=ta(),na=ra();O5.exports=gH;function gH(r,e=1){if(!pH(r))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Qg(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[mH.skip]:!0,encodingLength:t,decode:s,encode:n};function t(i){let o=na.clone(this),a=Qg(e)?e(o):e;return hH(i,r,o),na.clean(o),o.bytes*a}function s(i){let o=na.clone(this);s.bytes=0;let a=Qg(e)?e(o):e;if(a===0){na.clean(o);return}for(let c=a;c>0;c-=1)fH(i,r,o);s.bytes=o.bytes,na.clean(o)}function n(i,o){n.bytes=0;let a=na.clone(this),c=Qg(e)?e(a):e;if(c===0){na.clean(a);return}for(let d=c;d>0;d-=1)lH(0,o,r,a);n.bytes=a.bytes,na.clean(a)}}});var U5=se((ile,M5)=>{"use strict";var{isType:yH}=ei(),xH=Au();M5.exports=bH;function bH(r,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof r=="number")return{encode:SH(r,e),decode:_H(r,e),encodingLength:()=>r};if(yH(r))return{encode:EH(r,e),decode:CH(r,e),encodingLength:TH(r,e)};if(r===null)return{encode:vH(e),decode:wH(e),encodingLength(t){return Buffer.byteLength(t,e)+1}};if(typeof r=="function")return{encode:AH(r,e),decode:IH(r,e),encodingLength(t){return Buffer.byteLength(t,e)}};throw new TypeError("Unknown type of argument #1.")}function vH(r){return function e(t,s){let n=Buffer.from(t.toString(),r);s.writeBuffer(n),s.writeInt8(0),e.bytes=n.length+1}}function wH(r){return function e(t){let s=t.indexOf(0);if(s===-1)throw new xH(t.length+1,t.length);let n=s+1,i=t.readBuffer(n);return e.bytes=n,i.toString(r,0,s)}}function SH(r,e){return function t(s,n){if(s=s.toString(),Buffer.byteLength(s,e)!==r)throw new Error(`Size of string should be ${r} in bytes.`);let i=Buffer.from(s,e);n.writeBuffer(i),t.bytes=i.length}}function _H(r,e){return function t(s){let n=s.readBuffer(r);return t.bytes=r,n.toString(e)}}function EH(r,e){return function t(s,n){s=s.toString();let i=this;r.encode.call(i,Buffer.byteLength(s,e),n),t.bytes=r.encode.bytes;let o=Buffer.from(s,e);n.writeBuffer(o),t.bytes+=o.length}}function CH(r,e){return function t(s){let n=r.decode.call(this,s);if(typeof n!="number")throw new TypeError("Size of a string should be a number.");let i=s.readBuffer(n);return t.bytes=r.decode.bytes+i.length,i.toString(e)}}function TH(r,e){return function(s){let n=Buffer.byteLength(s,e);return r.encodingLength(n)+n}}function AH(r,e){return function t(s,n){t.bytes=0;let o=r(this),a=Buffer.from(s.toString(),e);D5(o),RH(o,a.length),n.writeBuffer(a),t.bytes+=a.length}}function IH(r,e){return function t(s){let n=r(this);D5(n);let i=s.readBuffer(n);return t.bytes=n,i.toString(e)}}function D5(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}function RH(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}});var H5=se((ole,j5)=>{"use strict";var Zg=Dh();j5.exports={doublebe:ys(8,"writeDoubleBE","readDoubleBE"),doublele:ys(8,"writeDoubleLE","readDoubleLE"),floatbe:ys(4,"writeFloatBE","readFloatBE"),floatle:ys(4,"writeFloatLE","readFloatLE"),int8:ys(1,"writeInt8","readInt8"),uint8:ys(1,"writeUInt8","readUInt8"),int16be:ys(2,"writeInt16BE","readInt16BE"),uint16be:ys(2,"writeUInt16BE","readUInt16BE"),int16le:ys(2,"writeInt16LE","readInt16LE"),uint16le:ys(2,"writeUInt16LE","readUInt16LE"),int32be:ys(4,"writeInt32BE","readInt32BE"),uint32be:ys(4,"writeUInt32BE","readUInt32BE"),int32le:ys(4,"writeInt32LE","readInt32LE"),uint32le:ys(4,"writeUInt32LE","readUInt32LE"),int24be:Js(3,"writeIntBE","readIntBE"),uint24be:Js(3,"writeUIntBE","readUIntBE"),int24le:Js(3,"writeIntLE","readIntLE"),uint24le:Js(3,"writeUIntLE","readUIntLE"),int40be:Js(5,"writeIntBE","readIntBE"),uint40be:Js(5,"writeUIntBE","readUIntBE"),int40le:Js(5,"writeIntLE","readIntLE"),uint40le:Js(5,"writeUIntLE","readUIntLE"),int48be:Js(6,"writeIntBE","readIntBE"),uint48be:Js(6,"writeUIntBE","readUIntBE"),int48le:Js(6,"writeIntLE","readIntLE"),uint48le:Js(6,"writeUIntLE","readUIntLE")};function ys(r,e,t){let s=Zg(),n=Zg();return s(`
97
- function decode_${t}(rstream) {
98
- decode_${t}.bytes = ${s.formats.d(r)};
99
- return rstream.${t}()
100
- }
101
- `),n(`
102
- function encode_${e}(value, wstream) {
103
- wstream.${e}(value);
104
- encode_${e}.bytes = ${s.formats.d(r)};
105
- }
106
- `),{encodingLength:()=>r,encode:n.toFunction(),decode:s.toFunction()}}function Js(r,e,t){let s=Zg(),n=Zg();return s(`
107
- function decode_${t}(rstream) {
108
- decode_${t}.bytes = ${s.formats.d(r)};
109
- return rstream.${t}(${s.formats.d(r)})
110
- }
111
- `),n(`
112
- function encode_${e}(value, wstream) {
113
- wstream.${e}(value, ${s.formats.d(r)});
114
- encode_${e}.bytes = ${s.formats.d(r)};
115
- }
116
- `),{encodingLength:()=>r,encode:n.toFunction(),decode:s.toFunction()}}});var q5=se((ale,F5)=>{"use strict";var{isType:kH,isFunction:sS,isUserType:PH}=ei(),nS=ta(),{decodeCommon:BH}=Iu(),{encodeCommon:NH}=jh(),{encodingLengthCommon:OH}=Hh(),ia=ra();F5.exports=LH;function LH(r,e){if(!kH(e)&&!PH(e))throw new TypeError("Argument #2 should be a valid type.");let t={encode:s,decode:n,encodingLength:i,[nS.skip]:!1};return t;function s(o,a){let c=ia.clone(this);s.bytes=0;let d=sS(r)?!!r(c):!!r;if(t[nS.skip]=!d,!d){ia.clean(c);return}NH(o,a,e,c),s.bytes=c.bytes,ia.clean(c)}function n(o){let a=ia.clone(this);n.bytes=0;let c=sS(r)?!!r(a):!!r;if(t[nS.skip]=!c,!c){ia.clean(a);return}let d=BH(o,e,a);return n.bytes=a.bytes,ia.clean(a),d}function i(o){let a=ia.clone(this);return(sS(r)?r(a):r)&&OH(o,e,a),ia.clean(a),a.bytes}}});var V5=se((cle,$5)=>{"use strict";var ey=ta(),{decodeCommon:DH}=Iu(),z5=ra();$5.exports=MH;function MH(...r){if(r.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:t,encode:()=>{},[ey.skip]:!0};return e;function t(s){t.bytes=0;let n=z5.clone(this);for(let i of r){let o=DH(s,i,n);if(i[ey.skip]!==!0)return t.bytes=n.bytes,z5.clean(n),e[ey.skip]=!1,o}e[ey.skip]=!0}}});var X5=se((dle,G5)=>{"use strict";var W5=Dh(),UH=Au(),Fh=class{constructor(e){this.stream=e,this.index=0}append(e){this.stream.append(e)}commit(){this.stream.consume(this.index)}get(e=0){return this.stream.get(this.index+e)}get length(){return this.stream.length}slice(e,t){return this.stream.slice(e,t)}toString(e,t,s){return this.stream.toString(e,t,s)}readBuffer(e){iS(this.index+e,this.length);let t=this.stream.slice(this.index,this.index+e);return this.index+=e,t}indexOf(e,t=0){return this.stream.indexOf(e,this.index+t)-this.index}},K5={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(K5).forEach(r=>{let e=W5(),t=K5[r];e(`
117
- function transaction_${r}() {
118
- assertSize(this.index + ${e.formats.d(t)}, this.length);
119
- const value = this.stream.buffer.${r}(this.index);
120
- this.index += ${e.formats.d(t)};
121
- return value;
122
- }
123
- `),Fh.prototype[r]=e.toFunction({assertSize:iS})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(r=>{let e=W5();e(`
124
- function transaction_${r}(bytes) {
125
- assertSize(this.index + bytes, this.length);
126
- const value = this.stream.buffer.${r}(bytes, this.index);
127
- this.index += bytes;
128
- return value;
129
- }
130
- `),Fh.prototype[r]=e.toFunction({assertSize:iS})});G5.exports=Fh;function iS(r,e){if(r>e)throw new UH(r,e)}});var Zt=se((ule,sI)=>{"use strict";var oS=Mh(),jH=A5(),HH=P5(),FH=N5(),qH=L5(),zH=U5(),Y5=H5(),$H=q5(),VH=V5(),{encode:Z5}=jh(),{decode:eI}=Iu(),{encodingLength:KH}=Hh(),WH=X5(),tI=Au(),rI={array:jH,bool:FH,buffer:HH,reserved:qH,string:zH,when:$H,select:VH};for(let r of Object.keys(Y5))rI[r]=Y5[r];var ty=Symbol("schema");function J5(r){let e=new oS({readableObjectMode:!1,writableObjectMode:!0,transform:GH});return e[ty]=r,e}function Q5(r){let e=null,t=Buffer.isBuffer(r);t||(e=r);let s=new oS({transform:XH,readableObjectMode:!0,writableObjectMode:!1});return s[ty]=e,t&&s.append(r),s}function GH(r,e,t){try{Z5(r,this[ty],this);let s=this.slice();this.consume(s.length),t(null,s)}catch(s){t(s)}}function XH(r,e,t){this.append(r);try{for(;this.length>0;){let s=new WH(this),n=eI(s,this[ty]);s.commit(),this.push(n)}t()}catch(s){s instanceof tI?t():t(s)}}sI.exports={createEncodeStream:J5,createDecodeStream:Q5,encode:Z5,decode:eI,encodingLength:KH,createEncode:J5,createDecode:Q5,types:rI,BinaryStream:oS,NotEnoughDataError:tI}});var zi,Uc,nI=A(()=>{"use strict";zi=Ge(require("crypto"),1),Uc=zi&&typeof zi=="object"&&"webcrypto"in zi?zi.webcrypto:zi&&typeof zi=="object"&&"randomBytes"in zi?zi:void 0});function jc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function qh(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function hn(r,...e){if(!jc(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ry(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");qh(r.outputLen),qh(r.blockLen)}function ku(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function oI(r,e){hn(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Vi(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function sy(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function pn(r,e){return r<<32-e|r>>>e}function Ki(r){if(hn(r),aI)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=YH[r[t]];return e}function iI(r){if(r>=$i._0&&r<=$i._9)return r-$i._0;if(r>=$i.A&&r<=$i.F)return r-($i.A-10);if(r>=$i.a&&r<=$i.f)return r-($i.a-10)}function Hc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(aI)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){let o=iI(r.charCodeAt(i)),a=iI(r.charCodeAt(i+1));if(o===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}s[n]=o*16+a}return s}function cI(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function zh(r){return typeof r=="string"&&(r=cI(r)),hn(r),r}function mn(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];hn(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return t}function ny(r){let e=s=>r().update(zh(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function iy(r=32){if(Uc&&typeof Uc.getRandomValues=="function")return Uc.getRandomValues(new Uint8Array(r));if(Uc&&typeof Uc.randomBytes=="function")return Uint8Array.from(Uc.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}var aI,YH,$i,Ru,Fc=A(()=>{"use strict";nI();aI=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",YH=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));$i={_0:48,_9:57,A:65,F:70,a:97,f:102};Ru=class{}});function $h(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function oa(r,e,t=""){let s=jc(r),n=r?.length,i=e!==void 0;if(!s||i&&n!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function Vh(r){let e=r.toString(16);return e.length&1?"0"+e:e}function dI(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?dS:BigInt("0x"+r)}function Pu(r){return dI(Ki(r))}function uS(r){return hn(r),dI(Ki(Uint8Array.from(r).reverse()))}function oy(r,e){return Hc(r.toString(16).padStart(e*2,"0"))}function fS(r,e){return oy(r,e).reverse()}function Wr(r,e,t){let s;if(typeof e=="string")try{s=Hc(e)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(jc(e))s=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let n=s.length;if(typeof t=="number"&&n!==t)throw new Error(r+" of length "+t+" expected, got "+n);return s}function uI(r,e,t){return aS(r)&&aS(e)&&aS(t)&&e<=r&&r<t}function fI(r,e,t,s){if(!uI(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function ay(r){let e;for(e=0;r>dS;r>>=cS,e+=1);return e}function lI(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=y=>new Uint8Array(y),n=y=>Uint8Array.of(y),i=s(r),o=s(r),a=0,c=()=>{i.fill(1),o.fill(0),a=0},d=(...y)=>t(o,i,...y),u=(y=s(0))=>{o=d(n(0),y),i=d(),y.length!==0&&(o=d(n(1),y),i=d())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let y=0,v=[];for(;y<e;){i=d();let S=i.slice();v.push(S),y+=i.length}return mn(...v)};return(y,v)=>{c(),u(y);let S;for(;!(S=v(f()));)u();return c(),S}}function Kh(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(n,i,o){let a=r[n];if(o&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([n,i])=>s(n,i,!1)),Object.entries(t).forEach(([n,i])=>s(n,i,!0))}function lS(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let i=r(t,...s);return e.set(t,i),i}}var dS,cS,aS,aa,cy=A(()=>{"use strict";Fc();Fc();dS=BigInt(0),cS=BigInt(1);aS=r=>typeof r=="bigint"&&dS<=r;aa=r=>(cS<<BigInt(r))-cS});function gn(r,e){let t=r%e;return t>=xs?t:e+t}function hI(r,e){if(r===xs)throw new Error("invert: expected non-zero number");if(e<=xs)throw new Error("invert: expected positive modulus, got "+e);let t=gn(r,e),s=e,n=xs,i=Gr,o=Gr,a=xs;for(;t!==xs;){let d=s/t,u=s%t,f=n-o*d,h=i-a*d;s=t,t=u,n=o,i=a,o=f,a=h}if(s!==Gr)throw new Error("invert: does not exist");return gn(n,e)}function hS(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function vI(r,e){let t=(r.ORDER+Gr)/gI,s=r.pow(e,t);return hS(r,s,e),s}function ZH(r,e){let t=(r.ORDER-yI)/xI,s=r.mul(e,qc),n=r.pow(s,t),i=r.mul(e,n),o=r.mul(r.mul(i,qc),n),a=r.mul(i,r.sub(o,r.ONE));return hS(r,a,e),a}function eF(r){let e=ti(r),t=wI(r),s=t(e,e.neg(e.ONE)),n=t(e,s),i=t(e,e.neg(s)),o=(r+JH)/bI;return(a,c)=>{let d=a.pow(c,o),u=a.mul(d,s),f=a.mul(d,n),h=a.mul(d,i),y=a.eql(a.sqr(u),c),v=a.eql(a.sqr(f),c);d=a.cmov(d,u,y),u=a.cmov(h,f,v);let S=a.eql(a.sqr(u),c),C=a.cmov(d,u,S);return hS(a,C,c),C}}function wI(r){if(r<mI)throw new Error("sqrt is not defined for small field");let e=r-Gr,t=0;for(;e%qc===xs;)e/=qc,t++;let s=qc,n=ti(r);for(;pI(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return vI;let i=n.pow(s,e),o=(e+Gr)/qc;return function(c,d){if(c.is0(d))return d;if(pI(c,d)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,i),h=c.pow(d,e),y=c.pow(d,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let v=1,S=c.sqr(h);for(;!c.eql(S,c.ONE);)if(v++,S=c.sqr(S),v===u)throw new Error("Cannot find square root");let C=Gr<<BigInt(u-v-1),O=c.pow(f,C);u=v,f=c.sqr(O),h=c.mul(h,f),y=c.mul(y,O)}return y}}function tF(r){return r%gI===mI?vI:r%xI===yI?ZH:r%bI===QH?eF(r):wI(r)}function pS(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=rF.reduce((s,n)=>(s[n]="function",s),e);return Kh(r,t),r}function sF(r,e,t){if(t<xs)throw new Error("invalid exponent, negatives unsupported");if(t===xs)return r.ONE;if(t===Gr)return e;let s=r.ONE,n=e;for(;t>xs;)t&Gr&&(s=r.mul(s,n)),n=r.sqr(n),t>>=Gr;return s}function dy(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(s[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(s[c]=r.mul(o,s[c]),r.mul(o,a)),i),s}function pI(r,e){let t=(r.ORDER-Gr)/qc,s=r.pow(e,t),n=r.eql(s,r.ONE),i=r.eql(s,r.ZERO),o=r.eql(s,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function uy(r,e){e!==void 0&&qh(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ti(r,e,t=!1,s={}){if(r<=xs)throw new Error("invalid field: expected ORDER > 0, got "+r);let n,i,o=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||t)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(n=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(t=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(i=s.sqrt);let{nBitLength:c,nByteLength:d}=uy(r,n);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:d,MASK:aa(c),ZERO:xs,ONE:Gr,allowedLengths:a,create:h=>gn(h,r),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return xs<=h&&h<r},is0:h=>h===xs,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Gr)===Gr,neg:h=>gn(-h,r),eql:(h,y)=>h===y,sqr:h=>gn(h*h,r),add:(h,y)=>gn(h+y,r),sub:(h,y)=>gn(h-y,r),mul:(h,y)=>gn(h*y,r),pow:(h,y)=>sF(f,h,y),div:(h,y)=>gn(h*hI(y,r),r),sqrN:h=>h*h,addN:(h,y)=>h+y,subN:(h,y)=>h-y,mulN:(h,y)=>h*y,inv:h=>hI(h,r),sqrt:i||(h=>(u||(u=tF(r)),u(f,h))),toBytes:h=>t?fS(h,d):oy(h,d),fromBytes:(h,y=!0)=>{if(a){if(!a.includes(h.length)||h.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let S=new Uint8Array(d);S.set(h,t?0:S.length-h.length),h=S}if(h.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+h.length);let v=t?uS(h):Pu(h);if(o&&(v=gn(v,r)),!y&&!f.isValid(v))throw new Error("invalid field element: outside of range 0..ORDER");return v},invertBatch:h=>dy(f,h),cmov:(h,y,v)=>v?y:h});return Object.freeze(f)}function SI(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function mS(r){let e=SI(r);return e+Math.ceil(e/2)}function _I(r,e,t=!1){let s=r.length,n=SI(e),i=mS(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=t?uS(r):Pu(r),a=gn(o,e-Gr)+Gr;return t?fS(a,n):oy(a,n)}var xs,Gr,qc,mI,gI,yI,JH,xI,QH,bI,rF,fy=A(()=>{"use strict";cy();xs=BigInt(0),Gr=BigInt(1),qc=BigInt(2),mI=BigInt(3),gI=BigInt(4),yI=BigInt(5),JH=BigInt(7),xI=BigInt(8),QH=BigInt(9),bI=BigInt(16);rF=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function nF(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(t>>n&i),a=Number(t&i),c=s?4:0,d=s?0:4;r.setUint32(e+c,o,s),r.setUint32(e+d,a,s)}function EI(r,e,t){return r&e^~r&t}function CI(r,e,t){return r&e^r&t^e&t}var Wh,Wi,Or,Lr,TI=A(()=>{"use strict";Fc();Wh=class extends Ru{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=sy(this.buffer)}update(e){ku(this),e=zh(e),hn(e);let{view:t,buffer:s,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let c=sy(e);for(;n<=i-o;o+=n)this.process(c,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ku(this),oI(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Vi(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(s,0),o=0);for(let f=o;f<n;f++)t[f]=0;nF(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=sy(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,u=this.get();if(d>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<d;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},Wi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Or=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Lr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function iF(r,e=!1){return e?{h:Number(r&ly),l:Number(r>>AI&ly)}:{h:Number(r>>AI&ly)|0,l:Number(r&ly)|0}}function II(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){let{h:o,l:a}=iF(r[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function ri(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var ly,AI,gS,yS,zc,$c,Gh,Xh,RI,kI,PI,BI,NI,OI,LI=A(()=>{"use strict";ly=BigInt(4294967295),AI=BigInt(32);gS=(r,e,t)=>r>>>t,yS=(r,e,t)=>r<<32-t|e>>>t,zc=(r,e,t)=>r>>>t|e<<32-t,$c=(r,e,t)=>r<<32-t|e>>>t,Gh=(r,e,t)=>r<<64-t|e>>>t-32,Xh=(r,e,t)=>r>>>t-32|e<<64-t;RI=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),kI=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,PI=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),BI=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,NI=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),OI=(r,e,t,s,n,i)=>e+t+s+n+i+(r/2**32|0)|0});var aF,ca,xS,DI,cF,dF,da,ua,hy,bS,MI,UI,jI,HI=A(()=>{"use strict";TI();LI();Fc();aF=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ca=new Uint32Array(64),xS=class extends Wh{constructor(e=32){super(64,e,8,!1),this.A=Wi[0]|0,this.B=Wi[1]|0,this.C=Wi[2]|0,this.D=Wi[3]|0,this.E=Wi[4]|0,this.F=Wi[5]|0,this.G=Wi[6]|0,this.H=Wi[7]|0}get(){let{A:e,B:t,C:s,D:n,E:i,F:o,G:a,H:c}=this;return[e,t,s,n,i,o,a,c]}set(e,t,s,n,i,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)ca[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let h=ca[f-15],y=ca[f-2],v=pn(h,7)^pn(h,18)^h>>>3,S=pn(y,17)^pn(y,19)^y>>>10;ca[f]=S+ca[f-7]+v+ca[f-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:c,G:d,H:u}=this;for(let f=0;f<64;f++){let h=pn(a,6)^pn(a,11)^pn(a,25),y=u+h+EI(a,c,d)+aF[f]+ca[f]|0,S=(pn(s,2)^pn(s,13)^pn(s,22))+CI(s,n,i)|0;u=d,d=c,c=a,a=o+y|0,o=i,i=n,n=s,s=y+S|0}s=s+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(s,n,i,o,a,c,d,u)}roundClean(){Vi(ca)}destroy(){this.set(0,0,0,0,0,0,0,0),Vi(this.buffer)}},DI=II(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),cF=DI[0],dF=DI[1],da=new Uint32Array(80),ua=new Uint32Array(80),hy=class extends Wh{constructor(e=64){super(128,e,16,!1),this.Ah=Lr[0]|0,this.Al=Lr[1]|0,this.Bh=Lr[2]|0,this.Bl=Lr[3]|0,this.Ch=Lr[4]|0,this.Cl=Lr[5]|0,this.Dh=Lr[6]|0,this.Dl=Lr[7]|0,this.Eh=Lr[8]|0,this.El=Lr[9]|0,this.Fh=Lr[10]|0,this.Fl=Lr[11]|0,this.Gh=Lr[12]|0,this.Gl=Lr[13]|0,this.Hh=Lr[14]|0,this.Hl=Lr[15]|0}get(){let{Ah:e,Al:t,Bh:s,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:d,El:u,Fh:f,Fl:h,Gh:y,Gl:v,Hh:S,Hl:C}=this;return[e,t,s,n,i,o,a,c,d,u,f,h,y,v,S,C]}set(e,t,s,n,i,o,a,c,d,u,f,h,y,v,S,C){this.Ah=e|0,this.Al=t|0,this.Bh=s|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=y|0,this.Gl=v|0,this.Hh=S|0,this.Hl=C|0}process(e,t){for(let z=0;z<16;z++,t+=4)da[z]=e.getUint32(t),ua[z]=e.getUint32(t+=4);for(let z=16;z<80;z++){let Q=da[z-15]|0,oe=ua[z-15]|0,te=zc(Q,oe,1)^zc(Q,oe,8)^gS(Q,oe,7),Ee=$c(Q,oe,1)^$c(Q,oe,8)^yS(Q,oe,7),ge=da[z-2]|0,Y=ua[z-2]|0,Ze=zc(ge,Y,19)^Gh(ge,Y,61)^gS(ge,Y,6),vt=$c(ge,Y,19)^Xh(ge,Y,61)^yS(ge,Y,6),Fe=PI(Ee,vt,ua[z-7],ua[z-16]),$=BI(Fe,te,Ze,da[z-7],da[z-16]);da[z]=$|0,ua[z]=Fe|0}let{Ah:s,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:d,Dl:u,Eh:f,El:h,Fh:y,Fl:v,Gh:S,Gl:C,Hh:O,Hl:K}=this;for(let z=0;z<80;z++){let Q=zc(f,h,14)^zc(f,h,18)^Gh(f,h,41),oe=$c(f,h,14)^$c(f,h,18)^Xh(f,h,41),te=f&y^~f&S,Ee=h&v^~h&C,ge=NI(K,oe,Ee,dF[z],ua[z]),Y=OI(ge,O,Q,te,cF[z],da[z]),Ze=ge|0,vt=zc(s,n,28)^Gh(s,n,34)^Gh(s,n,39),Fe=$c(s,n,28)^Xh(s,n,34)^Xh(s,n,39),$=s&i^s&a^i&a,V=n&o^n&c^o&c;O=S|0,K=C|0,S=y|0,C=v|0,y=f|0,v=h|0,{h:f,l:h}=ri(d|0,u|0,Y|0,Ze|0),d=a|0,u=c|0,a=i|0,c=o|0,i=s|0,o=n|0;let H=RI(Ze,Fe,V);s=kI(H,Y,vt,$),n=H|0}({h:s,l:n}=ri(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=ri(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=ri(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=ri(this.Dh|0,this.Dl|0,d|0,u|0),{h:f,l:h}=ri(this.Eh|0,this.El|0,f|0,h|0),{h:y,l:v}=ri(this.Fh|0,this.Fl|0,y|0,v|0),{h:S,l:C}=ri(this.Gh|0,this.Gl|0,S|0,C|0),{h:O,l:K}=ri(this.Hh|0,this.Hl|0,O|0,K|0),this.set(s,n,i,o,a,c,d,u,f,h,y,v,S,C,O,K)}roundClean(){Vi(da,ua)}destroy(){Vi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},bS=class extends hy{constructor(){super(48),this.Ah=Or[0]|0,this.Al=Or[1]|0,this.Bh=Or[2]|0,this.Bl=Or[3]|0,this.Ch=Or[4]|0,this.Cl=Or[5]|0,this.Dh=Or[6]|0,this.Dl=Or[7]|0,this.Eh=Or[8]|0,this.El=Or[9]|0,this.Fh=Or[10]|0,this.Fl=Or[11]|0,this.Gh=Or[12]|0,this.Gl=Or[13]|0,this.Hh=Or[14]|0,this.Hl=Or[15]|0}},MI=ny(()=>new xS),UI=ny(()=>new hy),jI=ny(()=>new bS)});var py,vS,FI=A(()=>{"use strict";Fc();py=class extends Ru{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ry(e);let s=zh(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(s.length>n?e.create().update(s).digest():s);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Vi(i)}update(e){return ku(this),this.iHash.update(e),this}digestInto(e){ku(this),hn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:s,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vS=(r,e,t)=>new py(r,e).update(t).digest();vS.create=(r,e)=>new py(r,e)});function Yh(r,e){let t=e.negate();return r?t:e}function gy(r,e){let t=dy(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function VI(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function wS(r,e){VI(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,i=aa(r),o=BigInt(r);return{windows:t,windowSize:s,mask:i,maxNumber:n,shiftBy:o}}function qI(r,e,t){let{windowSize:s,mask:n,maxNumber:i,shiftBy:o}=t,a=Number(r&n),c=r>>o;a>s&&(a-=i,c+=Vc);let d=e*s,u=d+Math.abs(a)-1,f=a===0,h=a<0,y=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:y,offsetF:d}}function uF(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function fF(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}function _S(r){return KI.get(r)||1}function zI(r){if(r!==Bu)throw new Error("invalid wNAF")}function WI(r,e,t,s){let n=e,i=r.ZERO,o=r.ZERO;for(;t>Bu||s>Bu;)t&Vc&&(i=i.add(n)),s&Vc&&(o=o.add(n)),n=n.double(),t>>=Vc,s>>=Vc;return{p1:i,p2:o}}function GI(r,e,t,s){uF(t,r),fF(s,e);let n=t.length,i=s.length;if(n!==i)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,a=ay(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=aa(c),u=new Array(Number(d)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c,h=o;for(let y=f;y>=0;y-=c){u.fill(o);for(let S=0;S<i;S++){let C=s[S],O=Number(C>>BigInt(y)&d);u[O]=u[O].add(t[S])}let v=o;for(let S=u.length-1,C=o;S>0;S--)C=C.add(u[S]),v=v.add(C);if(h=h.add(v),y!==0)for(let S=0;S<c;S++)h=h.double()}return h}function $I(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return pS(e),e}else return ti(r,{isLE:t})}function XI(r,e,t={},s){if(s===void 0&&(s=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>Bu))throw new Error(`CURVE.${c} must be positive bigint`)}let n=$I(e.p,t.Fp,s),i=$I(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}var Bu,Vc,SS,KI,my,YI=A(()=>{"use strict";cy();fy();Bu=BigInt(0),Vc=BigInt(1);SS=new WeakMap,KI=new WeakMap;my=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>Bu;)t&Vc&&(s=s.add(n)),n=n.double(),t>>=Vc;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=wS(t,this.bits),i=[],o=e,a=o;for(let c=0;c<s;c++){a=o,i.push(a);for(let d=1;d<n;d++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=wS(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:y}=qI(s,a,o);s=c,u?i=i.add(Yh(h,t[y])):n=n.add(Yh(f,t[d]))}return zI(s),{p:n,f:i}}wNAFUnsafe(e,t,s,n=this.ZERO){let i=wS(e,this.bits);for(let o=0;o<i.windows&&s!==Bu;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=qI(s,o,i);if(s=a,!d){let f=t[c];n=n.add(u?f.negate():f)}}return zI(s),n}getPrecomputes(e,t,s){let n=SS.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),SS.set(t,n))),n}cached(e,t,s){let n=_S(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let i=_S(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),t,n)}createCache(e,t){VI(t,this.bits),KI.set(e,t),SS.delete(e)}hasCache(e){return _S(e)!==1}}});function lF(r,e,t){let[[s,n],[i,o]]=e,a=JI(o*r,t),c=JI(-n*r,t),d=r-a*s-c*i,u=-a*n-c*o,f=d<Xi,h=u<Xi;f&&(d=-d),h&&(u=-u);let y=aa(Math.ceil(ay(t)/2))+Ou;if(d<Xi||d>=y||u<Xi||u>=y)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:d,k2neg:h,k2:u}}function CS(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ES(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return $h(t.lowS,"lowS"),$h(t.prehash,"prehash"),t.format!==void 0&&CS(t.format),t}function Nu(r,e){let{BYTES:t}=r,s;if(typeof e=="bigint")s=e;else{let n=Wr("private key",e);try{s=r.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function pF(r,e={}){let t=XI("weierstrass",r,e),{Fp:s,Fn:n}=t,i=t.CURVE,{h:o,n:a}=i;Kh(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!s.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=eR(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(Fe,$,V){let{x:H,y:me}=$.toAffine(),Te=s.toBytes(H);if($h(V,"isCompressed"),V){u();let ne=!s.isOdd(me);return mn(ZI(ne),Te)}else return mn(Uint8Array.of(4),Te,s.toBytes(me))}function h(Fe){oa(Fe,void 0,"Point");let{publicKey:$,publicKeyUncompressed:V}=d,H=Fe.length,me=Fe[0],Te=Fe.subarray(1);if(H===$&&(me===2||me===3)){let ne=s.fromBytes(Te);if(!s.isValid(ne))throw new Error("bad point: is not on curve, wrong x");let T=S(ne),R;try{R=s.sqrt(T)}catch(L){let ce=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+ce)}u();let F=s.isOdd(R);return(me&1)===1!==F&&(R=s.neg(R)),{x:ne,y:R}}else if(H===V&&me===4){let ne=s.BYTES,T=s.fromBytes(Te.subarray(0,ne)),R=s.fromBytes(Te.subarray(ne,ne*2));if(!C(T,R))throw new Error("bad point: is not on curve");return{x:T,y:R}}else throw new Error(`bad point: got length ${H}, expected compressed=${$} or uncompressed=${V}`)}let y=e.toBytes||f,v=e.fromBytes||h;function S(Fe){let $=s.sqr(Fe),V=s.mul($,Fe);return s.add(s.add(V,s.mul(Fe,i.a)),i.b)}function C(Fe,$){let V=s.sqr($),H=S(Fe);return s.eql(V,H)}if(!C(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let O=s.mul(s.pow(i.a,yy),hF),K=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(O,K)))throw new Error("bad curve params: a or b");function z(Fe,$,V=!1){if(!s.isValid($)||V&&s.is0($))throw new Error(`bad point coordinate ${Fe}`);return $}function Q(Fe){if(!(Fe instanceof Y))throw new Error("ProjectivePoint expected")}function oe(Fe){if(!c||!c.basises)throw new Error("no endo");return lF(Fe,c.basises,n.ORDER)}let te=lS((Fe,$)=>{let{X:V,Y:H,Z:me}=Fe;if(s.eql(me,s.ONE))return{x:V,y:H};let Te=Fe.is0();$==null&&($=Te?s.ONE:s.inv(me));let ne=s.mul(V,$),T=s.mul(H,$),R=s.mul(me,$);if(Te)return{x:s.ZERO,y:s.ZERO};if(!s.eql(R,s.ONE))throw new Error("invZ was invalid");return{x:ne,y:T}}),Ee=lS(Fe=>{if(Fe.is0()){if(e.allowInfinityPoint&&!s.is0(Fe.Y))return;throw new Error("bad point: ZERO")}let{x:$,y:V}=Fe.toAffine();if(!s.isValid($)||!s.isValid(V))throw new Error("bad point: x or y not field elements");if(!C($,V))throw new Error("bad point: equation left != right");if(!Fe.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function ge(Fe,$,V,H,me){return V=new Y(s.mul(V.X,Fe),V.Y,V.Z),$=Yh(H,$),V=Yh(me,V),$.add(V)}class Y{constructor($,V,H){this.X=z("x",$),this.Y=z("y",V,!0),this.Z=z("z",H),Object.freeze(this)}static CURVE(){return i}static fromAffine($){let{x:V,y:H}=$||{};if(!$||!s.isValid(V)||!s.isValid(H))throw new Error("invalid affine point");if($ instanceof Y)throw new Error("projective point not allowed");return s.is0(V)&&s.is0(H)?Y.ZERO:new Y(V,H,s.ONE)}static fromBytes($){let V=Y.fromAffine(v(oa($,void 0,"point")));return V.assertValidity(),V}static fromHex($){return Y.fromBytes(Wr("pointHex",$))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute($=8,V=!0){return vt.createCache(this,$),V||this.multiply(yy),this}assertValidity(){Ee(this)}hasEvenY(){let{y:$}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd($)}equals($){Q($);let{X:V,Y:H,Z:me}=this,{X:Te,Y:ne,Z:T}=$,R=s.eql(s.mul(V,T),s.mul(Te,me)),F=s.eql(s.mul(H,T),s.mul(ne,me));return R&&F}negate(){return new Y(this.X,s.neg(this.Y),this.Z)}double(){let{a:$,b:V}=i,H=s.mul(V,yy),{X:me,Y:Te,Z:ne}=this,T=s.ZERO,R=s.ZERO,F=s.ZERO,I=s.mul(me,me),L=s.mul(Te,Te),ce=s.mul(ne,ne),he=s.mul(me,Te);return he=s.add(he,he),F=s.mul(me,ne),F=s.add(F,F),T=s.mul($,F),R=s.mul(H,ce),R=s.add(T,R),T=s.sub(L,R),R=s.add(L,R),R=s.mul(T,R),T=s.mul(he,T),F=s.mul(H,F),ce=s.mul($,ce),he=s.sub(I,ce),he=s.mul($,he),he=s.add(he,F),F=s.add(I,I),I=s.add(F,I),I=s.add(I,ce),I=s.mul(I,he),R=s.add(R,I),ce=s.mul(Te,ne),ce=s.add(ce,ce),I=s.mul(ce,he),T=s.sub(T,I),F=s.mul(ce,L),F=s.add(F,F),F=s.add(F,F),new Y(T,R,F)}add($){Q($);let{X:V,Y:H,Z:me}=this,{X:Te,Y:ne,Z:T}=$,R=s.ZERO,F=s.ZERO,I=s.ZERO,L=i.a,ce=s.mul(i.b,yy),he=s.mul(V,Te),ct=s.mul(H,ne),xt=s.mul(me,T),Ot=s.add(V,H),_t=s.add(Te,ne);Ot=s.mul(Ot,_t),_t=s.add(he,ct),Ot=s.sub(Ot,_t),_t=s.add(V,me);let Dt=s.add(Te,T);return _t=s.mul(_t,Dt),Dt=s.add(he,xt),_t=s.sub(_t,Dt),Dt=s.add(H,me),R=s.add(ne,T),Dt=s.mul(Dt,R),R=s.add(ct,xt),Dt=s.sub(Dt,R),I=s.mul(L,_t),R=s.mul(ce,xt),I=s.add(R,I),R=s.sub(ct,I),I=s.add(ct,I),F=s.mul(R,I),ct=s.add(he,he),ct=s.add(ct,he),xt=s.mul(L,xt),_t=s.mul(ce,_t),ct=s.add(ct,xt),xt=s.sub(he,xt),xt=s.mul(L,xt),_t=s.add(_t,xt),he=s.mul(ct,_t),F=s.add(F,he),he=s.mul(Dt,_t),R=s.mul(Ot,R),R=s.sub(R,he),he=s.mul(Ot,ct),I=s.mul(Dt,I),I=s.add(I,he),new Y(R,F,I)}subtract($){return this.add($.negate())}is0(){return this.equals(Y.ZERO)}multiply($){let{endo:V}=e;if(!n.isValidNot0($))throw new Error("invalid scalar: out of range");let H,me,Te=ne=>vt.cached(this,ne,T=>gy(Y,T));if(V){let{k1neg:ne,k1:T,k2neg:R,k2:F}=oe($),{p:I,f:L}=Te(T),{p:ce,f:he}=Te(F);me=L.add(he),H=ge(V.beta,I,ce,ne,R)}else{let{p:ne,f:T}=Te($);H=ne,me=T}return gy(Y,[H,me])[0]}multiplyUnsafe($){let{endo:V}=e,H=this;if(!n.isValid($))throw new Error("invalid scalar: out of range");if($===Xi||H.is0())return Y.ZERO;if($===Ou)return H;if(vt.hasCache(this))return this.multiply($);if(V){let{k1neg:me,k1:Te,k2neg:ne,k2:T}=oe($),{p1:R,p2:F}=WI(Y,H,Te,T);return ge(V.beta,R,F,me,ne)}else return vt.unsafe(H,$)}multiplyAndAddUnsafe($,V,H){let me=this.multiplyUnsafe(V).add($.multiplyUnsafe(H));return me.is0()?void 0:me}toAffine($){return te(this,$)}isTorsionFree(){let{isTorsionFree:$}=e;return o===Ou?!0:$?$(Y,this):vt.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:$}=e;return o===Ou?this:$?$(Y,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes($=!0){return $h($,"isCompressed"),this.assertValidity(),y(Y,this,$)}toHex($=!0){return Ki(this.toBytes($))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes($=!0){return this.toBytes($)}_setWindowSize($){this.precompute($)}static normalizeZ($){return gy(Y,$)}static msm($,V){return GI(Y,n,$,V)}static fromPrivateKey($){return Y.BASE.multiply(Nu(n,$))}}Y.BASE=new Y(i.Gx,i.Gy,s.ONE),Y.ZERO=new Y(s.ZERO,s.ONE,s.ZERO),Y.Fp=s,Y.Fn=n;let Ze=n.BITS,vt=new my(Y,e.endo?Math.ceil(Ze/2):Ze);return Y.BASE.precompute(8),Y}function ZI(r){return Uint8Array.of(r?2:3)}function eR(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function mF(r,e={}){let{Fn:t}=r,s=e.randomBytes||iy,n=Object.assign(eR(r.Fp,t),{seed:mS(t.ORDER)});function i(y){try{return!!Nu(t,y)}catch{return!1}}function o(y,v){let{publicKey:S,publicKeyUncompressed:C}=n;try{let O=y.length;return v===!0&&O!==S||v===!1&&O!==C?!1:!!r.fromBytes(y)}catch{return!1}}function a(y=s(n.seed)){return _I(oa(y,n.seed,"seed"),t.ORDER)}function c(y,v=!0){return r.BASE.multiply(Nu(t,y)).toBytes(v)}function d(y){let v=a(y);return{secretKey:v,publicKey:c(v)}}function u(y){if(typeof y=="bigint")return!1;if(y instanceof r)return!0;let{secretKey:v,publicKey:S,publicKeyUncompressed:C}=n;if(t.allowedLengths||v===S)return;let O=Wr("key",y).length;return O===S||O===C}function f(y,v,S=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(v)===!1)throw new Error("second arg must be public key");let C=Nu(t,y);return r.fromHex(v).multiply(C).toBytes(S)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:y=>Nu(t,y),precompute(y=8,v=r.BASE){return v.precompute(y,!1)}},lengths:n})}function gF(r,e,t={}){ry(e),Kh(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=t.randomBytes||iy,n=t.hmac||((V,...H)=>vS(e,V,mn(...H))),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y}=mF(r,t),v={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},S="compact";function C(V){let H=a>>Ou;return V>H}function O(V,H){if(!o.isValidNot0(H))throw new Error(`invalid signature ${V}: out of range 1..Point.Fn.ORDER`);return H}function K(V,H){CS(H);let me=y.signature,Te=H==="compact"?me:H==="recovered"?me+1:void 0;return oa(V,Te,`${H} signature`)}class z{constructor(H,me,Te){this.r=O("r",H),this.s=O("s",me),Te!=null&&(this.recovery=Te),Object.freeze(this)}static fromBytes(H,me=S){K(H,me);let Te;if(me==="der"){let{r:F,s:I}=Gi.toSig(oa(H));return new z(F,I)}me==="recovered"&&(Te=H[0],me="compact",H=H.subarray(1));let ne=o.BYTES,T=H.subarray(0,ne),R=H.subarray(ne,ne*2);return new z(o.fromBytes(T),o.fromBytes(R),Te)}static fromHex(H,me){return this.fromBytes(Hc(H),me)}addRecoveryBit(H){return new z(this.r,this.s,H)}recoverPublicKey(H){let me=i.ORDER,{r:Te,s:ne,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*QI<me&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let F=T===2||T===3?Te+a:Te;if(!i.isValid(F))throw new Error("recovery id 2 or 3 invalid");let I=i.toBytes(F),L=r.fromBytes(mn(ZI((T&1)===0),I)),ce=o.inv(F),he=oe(Wr("msgHash",H)),ct=o.create(-he*ce),xt=o.create(ne*ce),Ot=r.BASE.multiplyUnsafe(ct).add(L.multiplyUnsafe(xt));if(Ot.is0())throw new Error("point at infinify");return Ot.assertValidity(),Ot}hasHighS(){return C(this.s)}toBytes(H=S){if(CS(H),H==="der")return Hc(Gi.hexFromSig(this));let me=o.toBytes(this.r),Te=o.toBytes(this.s);if(H==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return mn(Uint8Array.of(this.recovery),me,Te)}return mn(me,Te)}toHex(H){return Ki(this.toBytes(H))}assertValidity(){}static fromCompact(H){return z.fromBytes(Wr("sig",H),"compact")}static fromDER(H){return z.fromBytes(Wr("sig",H),"der")}normalizeS(){return this.hasHighS()?new z(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ki(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ki(this.toBytes("compact"))}}let Q=t.bits2int||function(H){if(H.length>8192)throw new Error("input is too large");let me=Pu(H),Te=H.length*8-c;return Te>0?me>>BigInt(Te):me},oe=t.bits2int_modN||function(H){return o.create(Q(H))},te=aa(c);function Ee(V){return fI("num < 2^"+c,V,Xi,te),o.toBytes(V)}function ge(V,H){return oa(V,void 0,"message"),H?oa(e(V),void 0,"prehashed message"):V}function Y(V,H,me){if(["recovered","canonical"].some(ct=>ct in me))throw new Error("sign() legacy options not supported");let{lowS:Te,prehash:ne,extraEntropy:T}=ES(me,v);V=ge(V,ne);let R=oe(V),F=Nu(o,H),I=[Ee(F),Ee(R)];if(T!=null&&T!==!1){let ct=T===!0?s(y.secretKey):T;I.push(Wr("extraEntropy",ct))}let L=mn(...I),ce=R;function he(ct){let xt=Q(ct);if(!o.isValidNot0(xt))return;let Ot=o.inv(xt),_t=r.BASE.multiply(xt).toAffine(),Dt=o.create(_t.x);if(Dt===Xi)return;let Bs=o.create(Ot*o.create(ce+Dt*F));if(Bs===Xi)return;let Ns=(_t.x===Dt?0:2)|Number(_t.y&Ou),Ca=Bs;return Te&&C(Bs)&&(Ca=o.neg(Bs),Ns^=1),new z(Dt,Ca,Ns)}return{seed:L,k2sig:he}}function Ze(V,H,me={}){V=Wr("message",V);let{seed:Te,k2sig:ne}=Y(V,H,me);return lI(e.outputLen,o.BYTES,n)(Te,ne)}function vt(V){let H,me=typeof V=="string"||jc(V),Te=!me&&V!==null&&typeof V=="object"&&typeof V.r=="bigint"&&typeof V.s=="bigint";if(!me&&!Te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Te)H=new z(V.r,V.s);else if(me){try{H=z.fromBytes(Wr("sig",V),"der")}catch(ne){if(!(ne instanceof Gi.Err))throw ne}if(!H)try{H=z.fromBytes(Wr("sig",V),"compact")}catch{return!1}}return H||!1}function Fe(V,H,me,Te={}){let{lowS:ne,prehash:T,format:R}=ES(Te,v);if(me=Wr("publicKey",me),H=ge(Wr("message",H),T),"strict"in Te)throw new Error("options.strict was renamed to lowS");let F=R===void 0?vt(V):z.fromBytes(Wr("sig",V),R);if(F===!1)return!1;try{let I=r.fromBytes(me);if(ne&&F.hasHighS())return!1;let{r:L,s:ce}=F,he=oe(H),ct=o.inv(ce),xt=o.create(he*ct),Ot=o.create(L*ct),_t=r.BASE.multiplyUnsafe(xt).add(I.multiplyUnsafe(Ot));return _t.is0()?!1:o.create(_t.x)===L}catch{return!1}}function $(V,H,me={}){let{prehash:Te}=ES(me,v);return H=ge(H,Te),z.fromBytes(V,"recovered").recoverPublicKey(H).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y,Point:r,sign:Ze,verify:Fe,recoverPublicKey:$,Signature:z,hash:e})}function yF(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,s=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,n=ti(e.n,{BITS:r.nBitLength,allowedLengths:s,modFromBytes:r.wrapPrivateKey}),i={Fp:t,Fn:n,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:i}}function xF(r){let{CURVE:e,curveOpts:t}=yF(r),s={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:s}}function bF(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,uy(t.Fn.ORDER,t.Fn.BITS))})}function tR(r){let{CURVE:e,curveOpts:t,hash:s,ecdsaOpts:n}=xF(r),i=pF(e,t),o=gF(i,s,n);return bF(r,o)}var JI,TS,Gi,Xi,Ou,QI,yy,hF,rR=A(()=>{"use strict";FI();Fc();cy();YI();fy();JI=(r,e)=>(r+(r>=0?e:-e)/QI)/e;TS=class extends Error{constructor(e=""){super(e)}},Gi={Err:TS,_tlv:{encode:(r,e)=>{let{Err:t}=Gi;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,n=Vh(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=s>127?Vh(n.length/2|128):"";return Vh(r)+i+n+e},decode(r,e){let{Err:t}=Gi,s=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("tlv.decode: wrong tlv");let n=e[s++],i=!!(n&128),o=0;if(!i)o=n;else{let c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let d=e.subarray(s,s+c);if(d.length!==c)throw new t("tlv.decode: length bytes not complete");if(d[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of d)o=o<<8|u;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(r){let{Err:e}=Gi;if(r<Xi)throw new e("integer: negative integers are not allowed");let t=Vh(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Gi;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Pu(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=Gi,n=Wr("signature",r),{v:i,l:o}=s.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,i),{v:d,l:u}=s.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(d)}},hexFromSig(r){let{_tlv:e,_int:t}=Gi,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),i=s+n;return e.encode(48,i)}},Xi=BigInt(0),Ou=BigInt(1),QI=BigInt(2),yy=BigInt(3),hF=BigInt(4)});function xy(r,e){let t=s=>tR({...r,hash:s});return{...t(e),create:t}}var sR=A(()=>{"use strict";rR();});var nR,iR,oR,vF,wF,SF,aR,zle,$le,cR=A(()=>{"use strict";HI();sR();fy();nR={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},iR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},oR={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},vF=ti(nR.p),wF=ti(iR.p),SF=ti(oR.p),aR=xy({...nR,Fp:vF,lowS:!1},MI),zle=xy({...iR,Fp:wF,lowS:!1},jI),$le=xy({...oR,Fp:SF,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},UI)});var by,dR=A(()=>{"use strict";cR();by=aR});var fR=se(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.LEB128=fa.SignedLEB128=fa.UnsignedLEB128=void 0;var Lu;(function(r){r[r.LOWER_7=127]="LOWER_7",r[r.UPPER_1=128]="UPPER_1"})(Lu||(Lu={}));var uR=r=>Number.isSafeInteger(r),Kc=class{static decode(e,t=0){let s=this.$scanForNullBytes(e,t),n=0,i=0;for(let o=0;o<=s-t;o++){let a=e[t+o]&Lu.LOWER_7;n|=a<<i,i+=7}return n}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let t=[],s=e;do{let n=s&Lu.LOWER_7;s>>=7,s&&(n=n|Lu.UPPER_1),t.push(n)}while(s);return Uint8Array.from(t)}static check(e){if(!uR(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,t=0){let s=t,n=0;do{if(s>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");n=e.slice(s,s+1)[0],s++}while(n&Lu.UPPER_1);return s-1}static getLength(e,t=0){return this.$scanForNullBytes(e,t)-t}};fa.UnsignedLEB128=Kc;var Jh=class{static $ceil7mul(e){let t=e;for(;t%7;)t++;return t}static check(e){if(!uR(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let t=Math.ceil(Math.log2(-e));return Kc.encode((1<<this.$ceil7mul(t))+e)}static decode(e,t=0){let s=Kc.decode(e,t);return-((1<<Math.ceil(Math.log2(s)))-s)}};fa.SignedLEB128=Jh;var Qh=class{};fa.LEB128=Qh;Qh.encode=r=>(r>=0?Kc:Jh).encode(r);Qh.decode=(r,e=0,t=!1)=>(t?Jh:Kc).decode(r,e)});var hR=se((AS,lR)=>{"use strict";(function(r){"use strict";function e(T){return parseInt(T)===T}function t(T){if(!e(T.length))return!1;for(var R=0;R<T.length;R++)if(!e(T[R])||T[R]<0||T[R]>255)return!1;return!0}function s(T,R){if(T.buffer&&T.name==="Uint8Array")return R&&(T.slice?T=T.slice():T=Array.prototype.slice.call(T)),T;if(Array.isArray(T)){if(!t(T))throw new Error("Array contains invalid value: "+T);return new Uint8Array(T)}if(e(T.length)&&t(T))return new Uint8Array(T);throw new Error("unsupported array-like object")}function n(T){return new Uint8Array(T)}function i(T,R,F,I,L){(I!=null||L!=null)&&(T.slice?T=T.slice(I,L):T=Array.prototype.slice.call(T,I,L)),R.set(T,F)}var o=(function(){function T(F){var I=[],L=0;for(F=encodeURI(F);L<F.length;){var ce=F.charCodeAt(L++);ce===37?(I.push(parseInt(F.substr(L,2),16)),L+=2):I.push(ce)}return s(I)}function R(F){for(var I=[],L=0;L<F.length;){var ce=F[L];ce<128?(I.push(String.fromCharCode(ce)),L++):ce>191&&ce<224?(I.push(String.fromCharCode((ce&31)<<6|F[L+1]&63)),L+=2):(I.push(String.fromCharCode((ce&15)<<12|(F[L+1]&63)<<6|F[L+2]&63)),L+=3)}return I.join("")}return{toBytes:T,fromBytes:R}})(),a=(function(){function T(I){for(var L=[],ce=0;ce<I.length;ce+=2)L.push(parseInt(I.substr(ce,2),16));return L}var R="0123456789abcdef";function F(I){for(var L=[],ce=0;ce<I.length;ce++){var he=I[ce];L.push(R[(he&240)>>4]+R[he&15])}return L.join("")}return{toBytes:T,fromBytes:F}})(),c={16:10,24:12,32:14},d=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],u=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],f=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],h=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],y=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],v=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],S=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],C=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],O=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],K=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],z=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],Q=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],oe=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],te=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],Ee=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function ge(T){for(var R=[],F=0;F<T.length;F+=4)R.push(T[F]<<24|T[F+1]<<16|T[F+2]<<8|T[F+3]);return R}var Y=function(T){if(!(this instanceof Y))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(T,!0)}),this._prepare()};Y.prototype._prepare=function(){var T=c[this.key.length];if(T==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var R=0;R<=T;R++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var F=(T+1)*4,I=this.key.length/4,L=ge(this.key),ce,R=0;R<I;R++)ce=R>>2,this._Ke[ce][R%4]=L[R],this._Kd[T-ce][R%4]=L[R];for(var he=0,ct=I,xt;ct<F;){if(xt=L[I-1],L[0]^=u[xt>>16&255]<<24^u[xt>>8&255]<<16^u[xt&255]<<8^u[xt>>24&255]^d[he]<<24,he+=1,I!=8)for(var R=1;R<I;R++)L[R]^=L[R-1];else{for(var R=1;R<I/2;R++)L[R]^=L[R-1];xt=L[I/2-1],L[I/2]^=u[xt&255]^u[xt>>8&255]<<8^u[xt>>16&255]<<16^u[xt>>24&255]<<24;for(var R=I/2+1;R<I;R++)L[R]^=L[R-1]}for(var R=0,Ot,_t;R<I&&ct<F;)Ot=ct>>2,_t=ct%4,this._Ke[Ot][_t]=L[R],this._Kd[T-Ot][_t]=L[R++],ct++}for(var Ot=1;Ot<T;Ot++)for(var _t=0;_t<4;_t++)xt=this._Kd[Ot][_t],this._Kd[Ot][_t]=Q[xt>>24&255]^oe[xt>>16&255]^te[xt>>8&255]^Ee[xt&255]},Y.prototype.encrypt=function(T){if(T.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var R=this._Ke.length-1,F=[0,0,0,0],I=ge(T),L=0;L<4;L++)I[L]^=this._Ke[0][L];for(var ce=1;ce<R;ce++){for(var L=0;L<4;L++)F[L]=h[I[L]>>24&255]^y[I[(L+1)%4]>>16&255]^v[I[(L+2)%4]>>8&255]^S[I[(L+3)%4]&255]^this._Ke[ce][L];I=F.slice()}for(var he=n(16),ct,L=0;L<4;L++)ct=this._Ke[R][L],he[4*L]=(u[I[L]>>24&255]^ct>>24)&255,he[4*L+1]=(u[I[(L+1)%4]>>16&255]^ct>>16)&255,he[4*L+2]=(u[I[(L+2)%4]>>8&255]^ct>>8)&255,he[4*L+3]=(u[I[(L+3)%4]&255]^ct)&255;return he},Y.prototype.decrypt=function(T){if(T.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var R=this._Kd.length-1,F=[0,0,0,0],I=ge(T),L=0;L<4;L++)I[L]^=this._Kd[0][L];for(var ce=1;ce<R;ce++){for(var L=0;L<4;L++)F[L]=C[I[L]>>24&255]^O[I[(L+3)%4]>>16&255]^K[I[(L+2)%4]>>8&255]^z[I[(L+1)%4]&255]^this._Kd[ce][L];I=F.slice()}for(var he=n(16),ct,L=0;L<4;L++)ct=this._Kd[R][L],he[4*L]=(f[I[L]>>24&255]^ct>>24)&255,he[4*L+1]=(f[I[(L+3)%4]>>16&255]^ct>>16)&255,he[4*L+2]=(f[I[(L+2)%4]>>8&255]^ct>>8)&255,he[4*L+3]=(f[I[(L+1)%4]&255]^ct)&255;return he};var Ze=function(T){if(!(this instanceof Ze))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new Y(T)};Ze.prototype.encrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16)i(T,F,0,I,I+16),F=this._aes.encrypt(F),i(F,R,I);return R},Ze.prototype.decrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16)i(T,F,0,I,I+16),F=this._aes.decrypt(F),i(F,R,I);return R};var vt=function(T,R){if(!(this instanceof vt))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=s(R,!0),this._aes=new Y(T)};vt.prototype.encrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16){i(T,F,0,I,I+16);for(var L=0;L<16;L++)F[L]^=this._lastCipherblock[L];this._lastCipherblock=this._aes.encrypt(F),i(this._lastCipherblock,R,I)}return R},vt.prototype.decrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16){i(T,F,0,I,I+16),F=this._aes.decrypt(F);for(var L=0;L<16;L++)R[I+L]=F[L]^this._lastCipherblock[L];i(T,this._lastCipherblock,0,I,I+16)}return R};var Fe=function(T,R,F){if(!(this instanceof Fe))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");F||(F=1),this.segmentSize=F,this._shiftRegister=s(R,!0),this._aes=new Y(T)};Fe.prototype.encrypt=function(T){if(T.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var R=s(T,!0),F,I=0;I<R.length;I+=this.segmentSize){F=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=F[L];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(R,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return R},Fe.prototype.decrypt=function(T){if(T.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var R=s(T,!0),F,I=0;I<R.length;I+=this.segmentSize){F=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=F[L];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(T,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return R};var $=function(T,R){if(!(this instanceof $))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=s(R,!0),this._lastPrecipherIndex=16,this._aes=new Y(T)};$.prototype.encrypt=function(T){for(var R=s(T,!0),F=0;F<R.length;F++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),R[F]^=this._lastPrecipher[this._lastPrecipherIndex++];return R},$.prototype.decrypt=$.prototype.encrypt;var V=function(T){if(!(this instanceof V))throw Error("Counter must be instanitated with `new`");T!==0&&!T&&(T=1),typeof T=="number"?(this._counter=n(16),this.setValue(T)):this.setBytes(T)};V.prototype.setValue=function(T){if(typeof T!="number"||parseInt(T)!=T)throw new Error("invalid counter value (must be an integer)");if(T>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var R=15;R>=0;--R)this._counter[R]=T%256,T=parseInt(T/256)},V.prototype.setBytes=function(T){if(T=s(T,!0),T.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=T},V.prototype.increment=function(){for(var T=15;T>=0;T--)if(this._counter[T]===255)this._counter[T]=0;else{this._counter[T]++;break}};var H=function(T,R){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",R instanceof V||(R=new V(R)),this._counter=R,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new Y(T)};H.prototype.encrypt=function(T){for(var R=s(T,!0),F=0;F<R.length;F++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),R[F]^=this._remainingCounter[this._remainingCounterIndex++];return R},H.prototype.decrypt=H.prototype.encrypt;function me(T){T=s(T,!0);var R=16-T.length%16,F=n(T.length+R);i(T,F);for(var I=T.length;I<F.length;I++)F[I]=R;return F}function Te(T){if(T=s(T,!0),T.length<16)throw new Error("PKCS#7 invalid length");var R=T[T.length-1];if(R>16)throw new Error("PKCS#7 padding byte out of range");for(var F=T.length-R,I=0;I<R;I++)if(T[F+I]!==R)throw new Error("PKCS#7 invalid padding byte");var L=n(F);return i(T,L,0,0,F),L}var ne={AES:Y,Counter:V,ModeOfOperation:{ecb:Ze,cbc:vt,cfb:Fe,ofb:$,ctr:H},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:me,strip:Te}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof AS<"u"?lR.exports=ne:typeof define=="function"&&define.amd?define([],function(){return ne}):(r.aesjs&&(ne._aesjs=r.aesjs),r.aesjs=ne)})(AS)});function gR(r,e,t){var s=e?0:4,n=e?4:0,i=e?0:3,o=e?1:2,a=e?2:1,c=e?3:0,d=e?AF:RF,u=e?IF:kF,f=v.prototype,h="is"+r,y="_"+h;return f.buffer=void 0,f.offset=0,f[y]=!0,f.toNumber=K,f.toString=z,f.toJSON=K,f.toArray=CF,Uu&&(f.toBuffer=TF),Mu&&(f.toArrayBuffer=yR),v[h]=S,v;function v(te,Ee,ge,Y){return this instanceof v?C(this,te,Ee,ge,Y):new v(te,Ee,ge,Y)}function S(te){return!!(te&&te[y])}function C(te,Ee,ge,Y,Ze){if(Mu&&vy&&(Ee instanceof vy&&(Ee=new Mu(Ee)),Y instanceof vy&&(Y=new Mu(Y))),!Ee&&!ge&&!Y&&!ju){te.buffer=xR(pR,0);return}if(!mR(Ee,ge)){var vt=ju||Array;Ze=ge,Y=Ee,ge=0,Ee=ju===Uu?Uu.alloc(8):new vt(8)}te.buffer=Ee,te.offset=ge|=0,wy!==typeof Y&&(typeof Y=="string"?O(Ee,ge,Y,Ze||10):mR(Y,Ze)?IS(Ee,ge,Y,Ze):typeof Ze=="number"?(Q(Ee,ge+s,Y),Q(Ee,ge+n,Ze)):Y>0?d(Ee,ge,Y):Y<0?u(Ee,ge,Y):IS(Ee,ge,pR,0))}function O(te,Ee,ge,Y){var Ze=0,vt=ge.length,Fe=0,$=0;ge[0]==="-"&&Ze++;for(var V=Ze;Ze<vt;){var H=parseInt(ge[Ze++],Y);if(!(H>=0))break;$=$*Y+H,Fe=Fe*Y+Math.floor($/Du),$%=Du}V&&(Fe=~Fe,$?$=Du-$:Fe++),Q(te,Ee+s,Fe),Q(te,Ee+n,$)}function K(){var te=this.buffer,Ee=this.offset,ge=oe(te,Ee+s),Y=oe(te,Ee+n);return t||(ge|=0),ge?ge*Du+Y:Y}function z(te){var Ee=this.buffer,ge=this.offset,Y=oe(Ee,ge+s),Ze=oe(Ee,ge+n),vt="",Fe=!t&&Y&2147483648;for(Fe&&(Y=~Y,Ze=Du-Ze),te=te||10;;){var $=Y%te*Du+Ze;if(Y=Math.floor(Y/te),Ze=Math.floor($/te),vt=($%te).toString(te)+vt,!Y&&!Ze)break}return Fe&&(vt="-"+vt),vt}function Q(te,Ee,ge){te[Ee+c]=ge&255,ge=ge>>8,te[Ee+a]=ge&255,ge=ge>>8,te[Ee+o]=ge&255,ge=ge>>8,te[Ee+i]=ge&255}function oe(te,Ee){return te[Ee+i]*EF+(te[Ee+o]<<16)+(te[Ee+a]<<8)+te[Ee+c]}}function CF(r){var e=this.buffer,t=this.offset;return ju=null,r!==!1&&_F(e)?e.length===8?e:e.slice(t,t+8):xR(e,t)}function TF(r){var e=this.buffer,t=this.offset;return ju=Uu,r!==!1&&Uu.isBuffer(e)?e.length===8?e:e.slice(t,t+8):Uu.from(yR.call(this,r))}function yR(r){var e=this.buffer,t=this.offset,s=e.buffer;if(ju=Mu,r!==!1&&!e.offset&&s instanceof vy)return s.byteLength===8?s:s.slice(t,t+8);var n=new Mu(8);return IS(n,0,e,t),n.buffer}function mR(r,e){var t=r&&r.length;return e|=0,t&&e+8<=t&&typeof r[e]!="string"}function IS(r,e,t,s){e|=0,s|=0;for(var n=0;n<8;n++)r[e++]=t[s++]&255}function xR(r,e){return Array.prototype.slice.call(r,e,e+8)}function AF(r,e,t){for(var s=e+8;s>e;)r[--s]=t&255,t/=256}function IF(r,e,t){var s=e+8;for(t++;s>e;)r[--s]=-t&255^255,t/=256}function RF(r,e,t){for(var s=e+8;e<s;)r[e++]=t&255,t/=256}function kF(r,e,t){var s=e+8;for(t++;e<s;)r[e++]=-t&255^255,t/=256}function PF(r){return!!r&&Object.prototype.toString.call(r)=="[object Array]"}var wy,Uu,Mu,vy,pR,_F,Du,EF,ju,Sy,RS,_y=A(()=>{"use strict";wy="undefined",Uu=wy!==typeof Buffer&&Buffer,Mu=wy!==typeof Uint8Array&&Uint8Array,vy=wy!==typeof ArrayBuffer&&ArrayBuffer,pR=[0,0,0,0,0,0,0,0],_F=Array.isArray||PF,Du=4294967296,EF=16777216,Sy=gR("Uint64BE",!0,!0),RS=gR("Int64BE",!0,!1)});var PS=se(bR=>{"use strict";var $e=bR,{Buffer:Ey}=require("buffer"),BF=require("os");$e.toBuffer=function(r,e,t){t=~~t;let s;if(this.isV4Format(r))s=e||Ey.alloc(t+4),r.split(/\./g).map(n=>{s[t++]=parseInt(n,10)&255});else if(this.isV6Format(r)){let n=r.split(":",8),i;for(i=0;i<n.length;i++){let o=this.isV4Format(n[i]),a;o&&(a=this.toBuffer(n[i]),n[i]=a.slice(0,2).toString("hex")),a&&++i<8&&n.splice(i,0,a.slice(2,4).toString("hex"))}if(n[0]==="")for(;n.length<8;)n.unshift("0");else if(n[n.length-1]==="")for(;n.length<8;)n.push("0");else if(n.length<8){for(i=0;i<n.length&&n[i]!=="";i++);let o=[i,1];for(i=9-n.length;i>0;i--)o.push("0");n.splice(...o)}for(s=e||Ey.alloc(t+16),i=0;i<n.length;i++){let o=parseInt(n[i],16);s[t++]=o>>8&255,s[t++]=o&255}}if(!s)throw Error(`Invalid ip address: ${r}`);return s};$e.toString=function(r,e,t){e=~~e,t=t||r.length-e;let s=[];if(t===4){for(let n=0;n<t;n++)s.push(r[e+n]);s=s.join(".")}else if(t===16){for(let n=0;n<t;n+=2)s.push(r.readUInt16BE(e+n).toString(16));s=s.join(":"),s=s.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),s=s.replace(/:{3,4}/,"::")}return s};var NF=/^(\d{1,3}\.){3,3}\d{1,3}$/,OF=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;$e.isV4Format=function(r){return NF.test(r)};$e.isV6Format=function(r){return OF.test(r)};function Zh(r){return r===4?"ipv4":r===6?"ipv6":r?r.toLowerCase():"ipv4"}$e.fromPrefixLen=function(r,e){r>32?e="ipv6":e=Zh(e);let t=4;e==="ipv6"&&(t=16);let s=Ey.alloc(t);for(let n=0,i=s.length;n<i;++n){let o=8;r<8&&(o=r),r-=o,s[n]=~(255>>o)&255}return $e.toString(s)};$e.mask=function(r,e){r=$e.toBuffer(r),e=$e.toBuffer(e);let t=Ey.alloc(Math.max(r.length,e.length)),s;if(r.length===e.length)for(s=0;s<r.length;s++)t[s]=r[s]&e[s];else if(e.length===4)for(s=0;s<e.length;s++)t[s]=r[r.length-4+s]&e[s];else{for(s=0;s<t.length-6;s++)t[s]=0;for(t[10]=255,t[11]=255,s=0;s<r.length;s++)t[s+12]=r[s]&e[s+12];s+=12}for(;s<t.length;s++)t[s]=0;return $e.toString(t)};$e.cidr=function(r){let e=r.split("/"),t=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${t}`);let s=$e.fromPrefixLen(parseInt(e[1],10));return $e.mask(t,s)};$e.subnet=function(r,e){let t=$e.toLong($e.mask(r,e)),s=$e.toBuffer(e),n=0;for(let o=0;o<s.length;o++)if(s[o]===255)n+=8;else{let a=s[o]&255;for(;a;)a=a<<1&255,n++}let i=2**(32-n);return{networkAddress:$e.fromLong(t),firstAddress:i<=2?$e.fromLong(t):$e.fromLong(t+1),lastAddress:i<=2?$e.fromLong(t+i-1):$e.fromLong(t+i-2),broadcastAddress:$e.fromLong(t+i-1),subnetMask:e,subnetMaskLength:n,numHosts:i<=2?i:i-2,length:i,contains(o){return t===$e.toLong($e.mask(o,e))}}};$e.cidrSubnet=function(r){let e=r.split("/"),t=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${t}`);let s=$e.fromPrefixLen(parseInt(e[1],10));return $e.subnet(t,s)};$e.not=function(r){let e=$e.toBuffer(r);for(let t=0;t<e.length;t++)e[t]=255^e[t];return $e.toString(e)};$e.or=function(r,e){if(r=$e.toBuffer(r),e=$e.toBuffer(e),r.length===e.length){for(let i=0;i<r.length;++i)r[i]|=e[i];return $e.toString(r)}let t=r,s=e;e.length>r.length&&(t=e,s=r);let n=t.length-s.length;for(let i=n;i<t.length;++i)t[i]|=s[i-n];return $e.toString(t)};$e.isEqual=function(r,e){if(r=$e.toBuffer(r),e=$e.toBuffer(e),r.length===e.length){for(let s=0;s<r.length;s++)if(r[s]!==e[s])return!1;return!0}if(e.length===4){let s=e;e=r,r=s}for(let s=0;s<10;s++)if(e[s]!==0)return!1;let t=e.readUInt16BE(10);if(t!==0&&t!==65535)return!1;for(let s=0;s<4;s++)if(r[s]!==e[s+12])return!1;return!0};$e.isPrivate=function(r){if($e.isLoopback(r))return!0;if(!$e.isV6Format(r)){let e=$e.normalizeToLong(r);if(e<0)throw new Error("invalid ipv4 address");r=$e.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^f[cd][0-9a-f]{2}:/i.test(r)||/^fe80:/i.test(r)||/^::1$/.test(r)||/^::$/.test(r)};$e.isPublic=function(r){return!$e.isPrivate(r)};$e.isLoopback=function(r){return!/\./.test(r)&&!/:/.test(r)&&(r=$e.fromLong(Number(r))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(r)||/^0177\./.test(r)||/^0x7f\./i.test(r)||/^fe80::1$/i.test(r)||/^::1$/.test(r)||/^::$/.test(r)};$e.loopback=function(r){if(r=Zh(r),r!=="ipv4"&&r!=="ipv6")throw new Error("family must be ipv4 or ipv6");return r==="ipv4"?"127.0.0.1":"fe80::1"};$e.address=function(r,e){let t=BF.networkInterfaces();if(e=Zh(e),r&&r!=="private"&&r!=="public"){let n=t[r].filter(i=>Zh(i.family)===e);return n.length===0?void 0:n[0].address}let s=Object.keys(t).map(n=>{let i=t[n].filter(o=>(o.family=Zh(o.family),o.family!==e||$e.isLoopback(o.address)?!1:r?r==="public"?$e.isPrivate(o.address):$e.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return s.length?s[0]:$e.loopback(e)};$e.toLong=function(r){let e=0;return r.split(".").forEach(t=>{e<<=8,e+=parseInt(t)}),e>>>0};$e.fromLong=function(r){return`${r>>>24}.${r>>16&255}.${r>>8&255}.${r&255}`};$e.normalizeToLong=function(r){let e=r.split(".").map(n=>n.startsWith("0x")||n.startsWith("0X")?parseInt(n,16):n.startsWith("0")&&n!=="0"&&/^[0-7]+$/.test(n)?parseInt(n,8):/^[1-9]\d*$/.test(n)||n==="0"?parseInt(n,10):NaN);if(e.some(isNaN))return-1;let t=0;switch(e.length){case 1:t=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;t=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;t=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(n=>n>255))return-1;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return t>>>0}});var wR=se((Jle,vR)=>{"use strict";vR.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var s,n,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(n=s;n--!==0;)if(!r(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),s=i.length,s!==Object.keys(t).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[n]))return!1;for(n=s;n--!==0;){var o=i[n];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var SR=se(BS=>{"use strict";BS.toString=function(r){switch(r){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+r};BS.toType=function(r){switch(r.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}});var _R=se(NS=>{"use strict";NS.toString=function(r){switch(r){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+r};NS.toRcode=function(r){switch(r.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var ER=se(OS=>{"use strict";OS.toString=function(r){switch(r){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+r};OS.toOpcode=function(r){switch(r.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var CR=se(LS=>{"use strict";LS.toString=function(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r};LS.toClass=function(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var TR=se(DS=>{"use strict";DS.toString=function(r){switch(r){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return r<0?null:`OPTION_${r}`};DS.toCode=function(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var RR=se((IR,MS)=>{"use strict";var AR=(function(r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.decode=f,r.encode=u,r.familyOf=d,r.name=void 0,r.sizeOf=c,r.v6=r.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,t=4,s=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,n=16,i={name:"v4",size:t,isFormat:h=>e.test(h),encode(h,y,v){v=~~v,y=y||new Uint8Array(v+t);let S=h.length,C=0;for(let O=0;O<S;){let K=h.charCodeAt(O++);K===46?(y[v++]=C,C=0):C=C*10+(K-48)}return y[v]=C,y},decode(h,y){return y=~~y,`${h[y++]}.${h[y++]}.${h[y++]}.${h[y]}`}};r.v4=i;let o={name:"v6",size:n,isFormat:h=>h.length>0&&s.test(h),encode(h,y,v){v=~~v;let S=v+n,C=-1,O=0,K=0,z=!0,Q=!1;y=y||new Uint8Array(v+n);for(let oe=0;oe<h.length;oe++){let te=h.charCodeAt(oe);te===58?(z?C!==-1?(v<S&&(y[v]=0),v<S-1&&(y[v+1]=0),v+=2):v<S&&(C=v):(Q===!0?(v<S&&(y[v]=K),v++):(v<S&&(y[v]=O>>8),v<S-1&&(y[v+1]=O&255),v+=2),O=0,K=0),z=!0,Q=!1):te===46?(v<S&&(y[v]=K),v++,K=0,O=0,z=!1,Q=!0):(z=!1,te>=97?te-=87:te>=65?te-=55:(te-=48,K=K*10+te),O=(O<<4)+te)}if(z===!1)Q===!0?(v<S&&(y[v]=K),v++):(v<S&&(y[v]=O>>8),v<S-1&&(y[v+1]=O&255),v+=2);else if(C===0)v<S&&(y[v]=0),v<S-1&&(y[v+1]=0),v+=2;else if(C!==-1){v+=2;for(let oe=Math.min(v-1,S-1);oe>=C+2;oe--)y[oe]=y[oe-2];y[C]=0,y[C+1]=0,C=v}if(C!==v&&C!==-1)for(v>S-2&&(v=S-2);S>C;)y[--S]=v<S&&v>C?y[--v]:0;else for(;v<S;)y[v++]=0;return y},decode(h,y){y=~~y;let v="";for(let S=0;S<n;S+=2)S!==0&&(v+=":"),v+=(h[y+S]<<8|h[y+S+1]).toString(16);return v.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};r.v6=o;let a="ip";r.name=a;function c(h){if(i.isFormat(h))return i.size;if(o.isFormat(h))return o.size;throw Error(`Invalid ip address: ${h}`)}function d(h){return c(h)===i.size?1:2}function u(h,y,v){v=~~v;let S=c(h);return typeof y=="function"&&(y=y(v+S)),S===i.size?i.encode(h,y,v):o.encode(h,y,v)}function f(h,y,v){if(y=~~y,v=v||h.length-y,v===i.size)return i.decode(h,y,v);if(v===o.size)return o.decode(h,y,v);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in r?r.default:r})({});typeof define=="function"&&define.amd?define([],function(){return AR}):typeof MS=="object"&&typeof IR=="object"&&(MS.exports=AR)});var BR=se(Ve=>{"use strict";var Ke=require("buffer").Buffer,io=SR(),LF=_R(),DF=ER(),Ty=CR(),US=TR(),Wc=RR(),MF=0,kR=32768,jS=32768,UF=~jS,PR=32768,jF=~PR,we=Ve.name={};we.encode=function(r,e,t,{mail:s=!1}={}){e||(e=Ke.alloc(we.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let o=[];if(s){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):o.length===0&&a.length?o.push(a+"."+c):o.push(c)})}else o=i.split(".");for(let a=0;a<o.length;a++){let c=e.write(o[a],t+1);e[t]=c,t+=c+1}}return e[t++]=0,we.encode.bytes=t-n,e};we.encode.bytes=0;we.decode=function(r,e,{mail:t=!1}={}){e||(e=0);let s=[],n=e,i=0,o=0,a=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let c=r[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let d=r.toString("utf-8",e,e+c);t&&(d=d.replace(/\./g,"\\.")),s.push(d),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let d=r.readUInt16BE(e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,o+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return we.decode.bytes=o,s.length===0?".":s.join(".")};we.decode.bytes=0;we.encodingLength=function(r){return r==="."||r===".."?1:Ke.byteLength(r.replace(/^\.|\.$/gm,""))+2};var St={};St.encode=function(r,e,t){e||(e=Ke.alloc(St.encodingLength(r))),t||(t=0);let s=e.write(r,t+1);return e[t]=s,St.encode.bytes=s+1,e};St.encode.bytes=0;St.decode=function(r,e){e||(e=0);let t=r[e],s=r.toString("utf-8",e+1,e+1+t);return St.decode.bytes=t+1,s};St.decode.bytes=0;St.encodingLength=function(r){return Ke.byteLength(r)+1};var bn={};bn.encode=function(r,e,t){e||(e=bn.encodingLength(r)),t||(t=0);let s=(r.flags||0)&32767,n=r.type==="response"?kR:MF;return e.writeUInt16BE(r.id||0,t),e.writeUInt16BE(s|n,t+2),e.writeUInt16BE(r.questions.length,t+4),e.writeUInt16BE(r.answers.length,t+6),e.writeUInt16BE(r.authorities.length,t+8),e.writeUInt16BE(r.additionals.length,t+10),e};bn.encode.bytes=12;bn.decode=function(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=r.readUInt16BE(e+2);return{id:r.readUInt16BE(e),type:t&kR?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:DF.toString(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:LF.toString(t&15),questions:new Array(r.readUInt16BE(e+4)),answers:new Array(r.readUInt16BE(e+6)),authorities:new Array(r.readUInt16BE(e+8)),additionals:new Array(r.readUInt16BE(e+10))}};bn.decode.bytes=12;bn.encodingLength=function(){return 12};var Yi=Ve.unknown={};Yi.encode=function(r,e,t){return e||(e=Ke.alloc(Yi.encodingLength(r))),t||(t=0),e.writeUInt16BE(r.length,t),r.copy(e,t+2),Yi.encode.bytes=r.length+2,e};Yi.encode.bytes=0;Yi.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s=r.slice(e+2,e+2+t);return Yi.decode.bytes=t+2,s};Yi.decode.bytes=0;Yi.encodingLength=function(r){return r.length+2};var Ji=Ve.ns={};Ji.encode=function(r,e,t){return e||(e=Ke.alloc(Ji.encodingLength(r))),t||(t=0),we.encode(r,e,t+2),e.writeUInt16BE(we.encode.bytes,t),Ji.encode.bytes=we.encode.bytes+2,e};Ji.encode.bytes=0;Ji.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s=we.decode(r,e+2);return Ji.decode.bytes=t+2,s};Ji.decode.bytes=0;Ji.encodingLength=function(r){return we.encodingLength(r)+2};var Qi=Ve.soa={};Qi.encode=function(r,e,t){e||(e=Ke.alloc(Qi.encodingLength(r))),t||(t=0);let s=t;return t+=2,we.encode(r.mname,e,t),t+=we.encode.bytes,we.encode(r.rname,e,t,{mail:!0}),t+=we.encode.bytes,e.writeUInt32BE(r.serial||0,t),t+=4,e.writeUInt32BE(r.refresh||0,t),t+=4,e.writeUInt32BE(r.retry||0,t),t+=4,e.writeUInt32BE(r.expire||0,t),t+=4,e.writeUInt32BE(r.minimum||0,t),t+=4,e.writeUInt16BE(t-s-2,s),Qi.encode.bytes=t-s,e};Qi.encode.bytes=0;Qi.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.mname=we.decode(r,e),e+=we.decode.bytes,s.rname=we.decode(r,e,{mail:!0}),e+=we.decode.bytes,s.serial=r.readUInt32BE(e),e+=4,s.refresh=r.readUInt32BE(e),e+=4,s.retry=r.readUInt32BE(e),e+=4,s.expire=r.readUInt32BE(e),e+=4,s.minimum=r.readUInt32BE(e),e+=4,Qi.decode.bytes=e-t,s};Qi.decode.bytes=0;Qi.encodingLength=function(r){return 22+we.encodingLength(r.mname)+we.encodingLength(r.rname)};var Zi=Ve.txt={};Zi.encode=function(r,e,t){Array.isArray(r)||(r=[r]);for(let n=0;n<r.length;n++)if(typeof r[n]=="string"&&(r[n]=Ke.from(r[n])),!Ke.isBuffer(r[n]))throw new Error("Must be a Buffer");e||(e=Ke.alloc(Zi.encodingLength(r))),t||(t=0);let s=t;return t+=2,r.forEach(function(n){e[t++]=n.length,n.copy(e,t,0,n.length),t+=n.length}),e.writeUInt16BE(t-s-2,s),Zi.encode.bytes=t-s,e};Zi.encode.bytes=0;Zi.decode=function(r,e){e||(e=0);let t=e,s=r.readUInt16BE(e);e+=2;let n=[];for(;s>0;){let i=r[e++];if(--s,s<i)throw new Error("Buffer overflow");n.push(r.slice(e,e+i)),e+=i,s-=i}return Zi.decode.bytes=e-t,n};Zi.decode.bytes=0;Zi.encodingLength=function(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Ke.byteLength(t)+1:e+=t.length+1}),e};var eo=Ve.null={};eo.encode=function(r,e,t){e||(e=Ke.alloc(eo.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=Ke.from(r)),r||(r=Ke.alloc(0));let s=t;t+=2;let n=r.length;return r.copy(e,t,0,n),t+=n,e.writeUInt16BE(t-s-2,s),eo.encode.bytes=t-s,e};eo.encode.bytes=0;eo.decode=function(r,e){e||(e=0);let t=e,s=r.readUInt16BE(e);e+=2;let n=r.slice(e,e+s);return e+=s,eo.decode.bytes=e-t,n};eo.decode.bytes=0;eo.encodingLength=function(r){return r?(Ke.isBuffer(r)?r.length:Ke.byteLength(r))+2:2};var to=Ve.hinfo={};to.encode=function(r,e,t){e||(e=Ke.alloc(to.encodingLength(r))),t||(t=0);let s=t;return t+=2,St.encode(r.cpu,e,t),t+=St.encode.bytes,St.encode(r.os,e,t),t+=St.encode.bytes,e.writeUInt16BE(t-s-2,s),to.encode.bytes=t-s,e};to.encode.bytes=0;to.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.cpu=St.decode(r,e),e+=St.decode.bytes,s.os=St.decode(r,e),e+=St.decode.bytes,to.decode.bytes=e-t,s};to.decode.bytes=0;to.encodingLength=function(r){return St.encodingLength(r.cpu)+St.encodingLength(r.os)+2};var yn=Ve.ptr={},HF=Ve.cname=yn,FF=Ve.dname=yn;yn.encode=function(r,e,t){return e||(e=Ke.alloc(yn.encodingLength(r))),t||(t=0),we.encode(r,e,t+2),e.writeUInt16BE(we.encode.bytes,t),yn.encode.bytes=we.encode.bytes+2,e};yn.encode.bytes=0;yn.decode=function(r,e){e||(e=0);let t=we.decode(r,e+2);return yn.decode.bytes=we.decode.bytes+2,t};yn.decode.bytes=0;yn.encodingLength=function(r){return we.encodingLength(r)+2};var ro=Ve.srv={};ro.encode=function(r,e,t){e||(e=Ke.alloc(ro.encodingLength(r))),t||(t=0),e.writeUInt16BE(r.priority||0,t+2),e.writeUInt16BE(r.weight||0,t+4),e.writeUInt16BE(r.port||0,t+6),we.encode(r.target,e,t+8);let s=we.encode.bytes+6;return e.writeUInt16BE(s,t),ro.encode.bytes=s+2,e};ro.encode.bytes=0;ro.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s={};return s.priority=r.readUInt16BE(e+2),s.weight=r.readUInt16BE(e+4),s.port=r.readUInt16BE(e+6),s.target=we.decode(r,e+8),ro.decode.bytes=t+2,s};ro.decode.bytes=0;ro.encodingLength=function(r){return 8+we.encodingLength(r.target)};var Rs=Ve.caa={};Rs.ISSUER_CRITICAL=128;Rs.encode=function(r,e,t){let s=Rs.encodingLength(r);return e||(e=Ke.alloc(Rs.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=Rs.ISSUER_CRITICAL),e.writeUInt16BE(s-2,t),t+=2,e.writeUInt8(r.flags||0,t),t+=1,St.encode(r.tag,e,t),t+=St.encode.bytes,e.write(r.value,t),t+=Ke.byteLength(r.value),Rs.encode.bytes=s,e};Rs.encode.bytes=0;Rs.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e);e+=2;let s=e,n={};return n.flags=r.readUInt8(e),e+=1,n.tag=St.decode(r,e),e+=St.decode.bytes,n.value=r.toString("utf-8",e,s+t),n.issuerCritical=!!(n.flags&Rs.ISSUER_CRITICAL),Rs.decode.bytes=t+2,n};Rs.decode.bytes=0;Rs.encodingLength=function(r){return St.encodingLength(r.tag)+St.encodingLength(r.value)+2};var la=Ve.mx={};la.encode=function(r,e,t){e||(e=Ke.alloc(la.encodingLength(r))),t||(t=0);let s=t;return t+=2,e.writeUInt16BE(r.preference||0,t),t+=2,we.encode(r.exchange,e,t),t+=we.encode.bytes,e.writeUInt16BE(t-s-2,s),la.encode.bytes=t-s,e};la.encode.bytes=0;la.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.preference=r.readUInt16BE(e),e+=2,s.exchange=we.decode(r,e),e+=we.decode.bytes,la.decode.bytes=e-t,s};la.encodingLength=function(r){return 4+we.encodingLength(r.exchange)};var so=Ve.a={};so.encode=function(r,e,t){return e||(e=Ke.alloc(so.encodingLength(r))),t||(t=0),e.writeUInt16BE(4,t),t+=2,Wc.v4.encode(r,e,t),so.encode.bytes=6,e};so.encode.bytes=0;so.decode=function(r,e){e||(e=0),e+=2;let t=Wc.v4.decode(r,e);return so.decode.bytes=6,t};so.decode.bytes=0;so.encodingLength=function(){return 6};var no=Ve.aaaa={};no.encode=function(r,e,t){return e||(e=Ke.alloc(no.encodingLength(r))),t||(t=0),e.writeUInt16BE(16,t),t+=2,Wc.v6.encode(r,e,t),no.encode.bytes=18,e};no.encode.bytes=0;no.decode=function(r,e){e||(e=0),e+=2;let t=Wc.v6.decode(r,e);return no.decode.bytes=18,t};no.decode.bytes=0;no.encodingLength=function(){return 18};var bs=Ve.option={};bs.encode=function(r,e,t){e||(e=Ke.alloc(bs.encodingLength(r))),t||(t=0);let s=t,n=US.toCode(r.code);if(e.writeUInt16BE(n,t),t+=2,r.data)e.writeUInt16BE(r.data.length,t),t+=2,r.data.copy(e,t),t+=r.data.length;else switch(n){case 8:let i=r.sourcePrefixLength||0,o=r.family||Wc.familyOf(r.ip),a=Wc.encode(r.ip,Ke.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,t),t+=2,e.writeUInt16BE(o,t),t+=2,e.writeUInt8(i,t++),e.writeUInt8(r.scopePrefixLength||0,t++),a.copy(e,t,0,c),t+=c;break;case 11:r.timeout?(e.writeUInt16BE(2,t),t+=2,e.writeUInt16BE(r.timeout,t),t+=2):(e.writeUInt16BE(0,t),t+=2);break;case 12:let d=r.length||0;e.writeUInt16BE(d,t),t+=2,e.fill(0,t,t+d),t+=d;break;case 14:let u=r.tags.length*2;e.writeUInt16BE(u,t),t+=2;for(let f of r.tags)e.writeUInt16BE(f,t),t+=2;break;default:throw new Error(`Unknown roption code: ${r.code}`)}return bs.encode.bytes=t-s,e};bs.encode.bytes=0;bs.decode=function(r,e){e||(e=0);let t={};t.code=r.readUInt16BE(e),t.type=US.toString(t.code),e+=2;let s=r.readUInt16BE(e);switch(e+=2,t.data=r.slice(e,e+s),t.code){case 8:t.family=r.readUInt16BE(e),e+=2,t.sourcePrefixLength=r.readUInt8(e++),t.scopePrefixLength=r.readUInt8(e++);let n=Ke.alloc(t.family===1?4:16);r.copy(n,0,e,e+s-4),t.ip=Wc.decode(n);break;case 11:s>0&&(t.timeout=r.readUInt16BE(e),e+=2);break;case 14:t.tags=[];for(let i=0;i<s;i+=2)t.tags.push(r.readUInt16BE(e)),e+=2}return bs.decode.bytes=s+4,t};bs.decode.bytes=0;bs.encodingLength=function(r){if(r.data)return r.data.length+4;switch(US.toCode(r.code)){case 8:let t=r.sourcePrefixLength||0;return Math.ceil(t/8)+8;case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)};var Ps=Ve.opt={};Ps.encode=function(r,e,t){e||(e=Ke.alloc(Ps.encodingLength(r))),t||(t=0);let s=t,n=Hu(r,bs);return e.writeUInt16BE(n,t),t=ep(r,bs,e,t+2),Ps.encode.bytes=t-s,e};Ps.encode.bytes=0;Ps.decode=function(r,e){e||(e=0);let t=e,s=[],n=r.readUInt16BE(e);e+=2;let i=0;for(;n>0;)s[i++]=bs.decode(r,e),e+=bs.decode.bytes,n-=bs.decode.bytes;return Ps.decode.bytes=e-t,s};Ps.decode.bytes=0;Ps.encodingLength=function(r){return 2+Hu(r||[],bs)};var ss=Ve.dnskey={};ss.PROTOCOL_DNSSEC=3;ss.ZONE_KEY=128;ss.SECURE_ENTRYPOINT=32768;ss.encode=function(r,e,t){e||(e=Ke.alloc(ss.encodingLength(r))),t||(t=0);let s=t,n=r.key;if(!Ke.isBuffer(n))throw new Error("Key must be a Buffer");return t+=2,e.writeUInt16BE(r.flags,t),t+=2,e.writeUInt8(ss.PROTOCOL_DNSSEC,t),t+=1,e.writeUInt8(r.algorithm,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,ss.encode.bytes=t-s,e.writeUInt16BE(ss.encode.bytes-2,s),e};ss.encode.bytes=0;ss.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);if(e+=2,s.flags=r.readUInt16BE(e),e+=2,r.readUInt8(e)!==ss.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,s.algorithm=r.readUInt8(e),e+=1,s.key=r.slice(e,t+n+2),e+=s.key.length,ss.decode.bytes=e-t,s};ss.decode.bytes=0;ss.encodingLength=function(r){return 6+Ke.byteLength(r.key)};var si=Ve.rrsig={};si.encode=function(r,e,t){e||(e=Ke.alloc(si.encodingLength(r))),t||(t=0);let s=t,n=r.signature;if(!Ke.isBuffer(n))throw new Error("Signature must be a Buffer");return t+=2,e.writeUInt16BE(io.toType(r.typeCovered),t),t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.labels,t),t+=1,e.writeUInt32BE(r.originalTTL,t),t+=4,e.writeUInt32BE(r.expiration,t),t+=4,e.writeUInt32BE(r.inception,t),t+=4,e.writeUInt16BE(r.keyTag,t),t+=2,we.encode(r.signersName,e,t),t+=we.encode.bytes,n.copy(e,t,0,n.length),t+=n.length,si.encode.bytes=t-s,e.writeUInt16BE(si.encode.bytes-2,s),e};si.encode.bytes=0;si.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.typeCovered=io.toString(r.readUInt16BE(e)),e+=2,s.algorithm=r.readUInt8(e),e+=1,s.labels=r.readUInt8(e),e+=1,s.originalTTL=r.readUInt32BE(e),e+=4,s.expiration=r.readUInt32BE(e),e+=4,s.inception=r.readUInt32BE(e),e+=4,s.keyTag=r.readUInt16BE(e),e+=2,s.signersName=we.decode(r,e),e+=we.decode.bytes,s.signature=r.slice(e,t+n+2),e+=s.signature.length,si.decode.bytes=e-t,s};si.decode.bytes=0;si.encodingLength=function(r){return 20+we.encodingLength(r.signersName)+Ke.byteLength(r.signature)};var ni=Ve.rp={};ni.encode=function(r,e,t){e||(e=Ke.alloc(ni.encodingLength(r))),t||(t=0);let s=t;return t+=2,we.encode(r.mbox||".",e,t,{mail:!0}),t+=we.encode.bytes,we.encode(r.txt||".",e,t),t+=we.encode.bytes,ni.encode.bytes=t-s,e.writeUInt16BE(ni.encode.bytes-2,s),e};ni.encode.bytes=0;ni.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.mbox=we.decode(r,e,{mail:!0})||".",e+=we.decode.bytes,s.txt=we.decode(r,e)||".",e+=we.decode.bytes,ni.decode.bytes=e-t,s};ni.decode.bytes=0;ni.encodingLength=function(r){return 2+we.encodingLength(r.mbox||".")+we.encodingLength(r.txt||".")};var Cr={};Cr.encode=function(r,e,t){e||(e=Ke.alloc(Cr.encodingLength(r))),t||(t=0);let s=t;for(var n=[],i=0;i<r.length;i++){var o=io.toType(r[i]);n[o>>8]===void 0&&(n[o>>8]=[]),n[o>>8][o>>3&31]|=1<<7-(o&7)}for(i=0;i<n.length;i++)if(n[i]!==void 0){var a=Ke.from(n[i]);e.writeUInt8(i,t),t+=1,e.writeUInt8(a.length,t),t+=1,a.copy(e,t),t+=a.length}return Cr.encode.bytes=t-s,e};Cr.encode.bytes=0;Cr.decode=function(r,e,t){e||(e=0);let s=e;for(var n=[];e-s<t;){var i=r.readUInt8(e);e+=1;var o=r.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=r.readUInt8(e+a),d=0;d<8;d++)if(c&1<<7-d){var u=io.toString(i<<8|a<<3|d);n.push(u)}e+=o}return Cr.decode.bytes=e-s,n};Cr.decode.bytes=0;Cr.encodingLength=function(r){for(var e=[],t=0;t<r.length;t++){var s=io.toType(r[t]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}var n=0;for(t=0;t<e.length;t++)e[t]!==void 0&&(n+=2+Math.ceil((e[t]+1)/8));return n};var ii=Ve.nsec={};ii.encode=function(r,e,t){e||(e=Ke.alloc(ii.encodingLength(r))),t||(t=0);let s=t;return t+=2,we.encode(r.nextDomain,e,t),t+=we.encode.bytes,Cr.encode(r.rrtypes,e,t),t+=Cr.encode.bytes,ii.encode.bytes=t-s,e.writeUInt16BE(ii.encode.bytes-2,s),e};ii.encode.bytes=0;ii.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.nextDomain=we.decode(r,e),e+=we.decode.bytes,s.rrtypes=Cr.decode(r,e,n-(e-t)),e+=Cr.decode.bytes,ii.decode.bytes=e-t,s};ii.decode.bytes=0;ii.encodingLength=function(r){return 2+we.encodingLength(r.nextDomain)+Cr.encodingLength(r.rrtypes)};var oi=Ve.nsec3={};oi.encode=function(r,e,t){e||(e=Ke.alloc(oi.encodingLength(r))),t||(t=0);let s=t,n=r.salt;if(!Ke.isBuffer(n))throw new Error("salt must be a Buffer");let i=r.nextDomain;if(!Ke.isBuffer(i))throw new Error("nextDomain must be a Buffer");return t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.flags,t),t+=1,e.writeUInt16BE(r.iterations,t),t+=2,e.writeUInt8(n.length,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,e.writeUInt8(i.length,t),t+=1,i.copy(e,t,0,i.length),t+=i.length,Cr.encode(r.rrtypes,e,t),t+=Cr.encode.bytes,oi.encode.bytes=t-s,e.writeUInt16BE(oi.encode.bytes-2,s),e};oi.encode.bytes=0;oi.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);e+=2,s.algorithm=r.readUInt8(e),e+=1,s.flags=r.readUInt8(e),e+=1,s.iterations=r.readUInt16BE(e),e+=2;let i=r.readUInt8(e);e+=1,s.salt=r.slice(e,e+i),e+=i;let o=r.readUInt8(e);return e+=1,s.nextDomain=r.slice(e,e+o),e+=o,s.rrtypes=Cr.decode(r,e,n-(e-t)),e+=Cr.decode.bytes,oi.decode.bytes=e-t,s};oi.decode.bytes=0;oi.encodingLength=function(r){return 8+r.salt.length+r.nextDomain.length+Cr.encodingLength(r.rrtypes)};var ai=Ve.ds={};ai.encode=function(r,e,t){e||(e=Ke.alloc(ai.encodingLength(r))),t||(t=0);let s=t,n=r.digest;if(!Ke.isBuffer(n))throw new Error("Digest must be a Buffer");return t+=2,e.writeUInt16BE(r.keyTag,t),t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.digestType,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,ai.encode.bytes=t-s,e.writeUInt16BE(ai.encode.bytes-2,s),e};ai.encode.bytes=0;ai.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.keyTag=r.readUInt16BE(e),e+=2,s.algorithm=r.readUInt8(e),e+=1,s.digestType=r.readUInt8(e),e+=1,s.digest=r.slice(e,t+n+2),e+=s.digest.length,ai.decode.bytes=e-t,s};ai.decode.bytes=0;ai.encodingLength=function(r){return 6+Ke.byteLength(r.digest)};var ks=Ve.sshfp={};ks.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};ks.encode=function(e,t,s){t||(t=Ke.alloc(ks.encodingLength(e))),s||(s=0);let n=s;s+=2,t[s]=e.algorithm,s+=1,t[s]=e.hash,s+=1;let i=Ke.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==ks.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(t,s),s+=i.byteLength,ks.encode.bytes=s-n,t.writeUInt16BE(ks.encode.bytes-2,n),t};ks.encode.bytes=0;ks.decode=function(e,t){t||(t=0);let s=t,n={};t+=2,n.algorithm=e[t],t+=1,n.hash=e[t],t+=1;let i=ks.getFingerprintLengthForHashType(n.hash);return n.fingerprint=e.slice(t,t+i).toString("hex").toUpperCase(),t+=i,ks.decode.bytes=t-s,n};ks.decode.bytes=0;ks.encodingLength=function(r){return 4+Ke.from(r.fingerprint,"hex").byteLength};var ci=Ve.naptr={};ci.encode=function(r,e,t){e||(e=Ke.alloc(ci.encodingLength(r))),t||(t=0);let s=t;return t+=2,e.writeUInt16BE(r.order||0,t),t+=2,e.writeUInt16BE(r.preference||0,t),t+=2,St.encode(r.flags,e,t),t+=St.encode.bytes,St.encode(r.services,e,t),t+=St.encode.bytes,St.encode(r.regexp,e,t),t+=St.encode.bytes,we.encode(r.replacement,e,t),t+=we.encode.bytes,ci.encode.bytes=t-s,e.writeUInt16BE(ci.encode.bytes-2,s),e};ci.encode.bytes=0;ci.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.order=r.readUInt16BE(e),e+=2,s.preference=r.readUInt16BE(e),e+=2,s.flags=St.decode(r,e),e+=St.decode.bytes,s.services=St.decode(r,e),e+=St.decode.bytes,s.regexp=St.decode(r,e),e+=St.decode.bytes,s.replacement=we.decode(r,e),e+=we.decode.bytes,ci.decode.bytes=e-t,s};ci.decode.bytes=0;ci.encodingLength=function(r){return St.encodingLength(r.flags)+St.encodingLength(r.services)+St.encodingLength(r.regexp)+we.encodingLength(r.replacement)+6};var di=Ve.tlsa={};di.encode=function(r,e,t){e||(e=Ke.alloc(di.encodingLength(r))),t||(t=0);let s=t,n=r.certificate;if(!Ke.isBuffer(n))throw new Error("Certificate must be a Buffer");return t+=2,e.writeUInt8(r.usage,t),t+=1,e.writeUInt8(r.selector,t),t+=1,e.writeUInt8(r.matchingType,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,di.encode.bytes=t-s,e.writeUInt16BE(di.encode.bytes-2,s),e};di.encode.bytes=0;di.decode=function(r,e){e||(e=0);let t=e,s={},n=r.readUInt16BE(e);return e+=2,s.usage=r.readUInt8(e),e+=1,s.selector=r.readUInt8(e),e+=1,s.matchingType=r.readUInt8(e),e+=1,s.certificate=r.slice(e,t+n+2),e+=s.certificate.length,di.decode.bytes=e-t,s};di.decode.bytes=0;di.encodingLength=function(r){return 5+Ke.byteLength(r.certificate)};var HS=Ve.record=function(r){switch(r.toUpperCase()){case"A":return so;case"PTR":return yn;case"CNAME":return HF;case"DNAME":return FF;case"TXT":return Zi;case"NULL":return eo;case"AAAA":return no;case"SRV":return ro;case"HINFO":return to;case"CAA":return Rs;case"NS":return Ji;case"SOA":return Qi;case"MX":return la;case"OPT":return Ps;case"DNSKEY":return ss;case"RRSIG":return si;case"RP":return ni;case"NSEC":return ii;case"NSEC3":return oi;case"SSHFP":return ks;case"DS":return ai;case"NAPTR":return ci;case"TLSA":return di}return Yi},Dr=Ve.answer={};Dr.encode=function(r,e,t){e||(e=Ke.alloc(Dr.encodingLength(r))),t||(t=0);let s=t;if(we.encode(r.name,e,t),t+=we.encode.bytes,e.writeUInt16BE(io.toType(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(r.udpPayloadSize||4096,t+2),e.writeUInt8(r.extendedRcode||0,t+4),e.writeUInt8(r.ednsVersion||0,t+5),e.writeUInt16BE(r.flags||0,t+6),t+=8,Ps.encode(r.options||[],e,t),t+=Ps.encode.bytes}else{let n=Ty.toClass(r.class===void 0?"IN":r.class);r.flush&&(n|=jS),e.writeUInt16BE(n,t+2),e.writeUInt32BE(r.ttl||0,t+4),t+=8;let i=HS(r.type);i.encode(r.data,e,t),t+=i.encode.bytes}return Dr.encode.bytes=t-s,e};Dr.encode.bytes=0;Dr.decode=function(r,e){e||(e=0);let t={},s=e;if(t.name=we.decode(r,e),e+=we.decode.bytes,t.type=io.toString(r.readUInt16BE(e)),t.type==="OPT")t.udpPayloadSize=r.readUInt16BE(e+2),t.extendedRcode=r.readUInt8(e+4),t.ednsVersion=r.readUInt8(e+5),t.flags=r.readUInt16BE(e+6),t.flag_do=(t.flags>>15&1)===1,t.options=Ps.decode(r,e+8),e+=8+Ps.decode.bytes;else{let n=r.readUInt16BE(e+2);t.ttl=r.readUInt32BE(e+4),t.class=Ty.toString(n&UF),t.flush=!!(n&jS);let i=HS(t.type);t.data=i.decode(r,e+8),e+=8+i.decode.bytes}return Dr.decode.bytes=e-s,t};Dr.decode.bytes=0;Dr.encodingLength=function(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return we.encodingLength(r.name)+8+HS(r.type).encodingLength(e)};var xn=Ve.question={};xn.encode=function(r,e,t){e||(e=Ke.alloc(xn.encodingLength(r))),t||(t=0);let s=t;return we.encode(r.name,e,t),t+=we.encode.bytes,e.writeUInt16BE(io.toType(r.type),t),t+=2,e.writeUInt16BE(Ty.toClass(r.class===void 0?"IN":r.class),t),t+=2,xn.encode.bytes=t-s,r};xn.encode.bytes=0;xn.decode=function(r,e){e||(e=0);let t=e,s={};return s.name=we.decode(r,e),e+=we.decode.bytes,s.type=io.toString(r.readUInt16BE(e)),e+=2,s.class=Ty.toString(r.readUInt16BE(e)),e+=2,s.class&PR&&(s.class&=jF),xn.decode.bytes=e-t,s};xn.decode.bytes=0;xn.encodingLength=function(r){return we.encodingLength(r.name)+4};Ve.AUTHORITATIVE_ANSWER=1024;Ve.TRUNCATED_RESPONSE=512;Ve.RECURSION_DESIRED=256;Ve.RECURSION_AVAILABLE=128;Ve.AUTHENTIC_DATA=32;Ve.CHECKING_DISABLED=16;Ve.DNSSEC_OK=32768;Ve.encode=function(r,e,t){let s=!e;s&&(e=Ke.alloc(Ve.encodingLength(r))),t||(t=0);let n=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),bn.encode(r,e,t),t+=bn.encode.bytes,t=ep(r.questions,xn,e,t),t=ep(r.answers,Dr,e,t),t=ep(r.authorities,Dr,e,t),t=ep(r.additionals,Dr,e,t),Ve.encode.bytes=t-n,s&&Ve.encode.bytes!==e.length?e.slice(0,Ve.encode.bytes):e};Ve.encode.bytes=0;Ve.decode=function(r,e){e||(e=0);let t=e,s=bn.decode(r,e);return e+=bn.decode.bytes,e=Cy(s.questions,xn,r,e),e=Cy(s.answers,Dr,r,e),e=Cy(s.authorities,Dr,r,e),e=Cy(s.additionals,Dr,r,e),Ve.decode.bytes=e-t,s};Ve.decode.bytes=0;Ve.encodingLength=function(r){return bn.encodingLength(r)+Hu(r.questions||[],xn)+Hu(r.answers||[],Dr)+Hu(r.authorities||[],Dr)+Hu(r.additionals||[],Dr)};Ve.streamEncode=function(r){let e=Ve.encode(r),t=Ke.alloc(2);t.writeUInt16BE(e.byteLength);let s=Ke.concat([t,e]);return Ve.streamEncode.bytes=s.byteLength,s};Ve.streamEncode.bytes=0;Ve.streamDecode=function(r){let e=r.readUInt16BE(0);if(r.byteLength<e+2)return null;let t=Ve.decode(r.slice(2));return Ve.streamDecode.bytes=Ve.decode.bytes,t};Ve.streamDecode.bytes=0;function Hu(r,e){let t=0;for(let s=0;s<r.length;s++)t+=e.encodingLength(r[s]);return t}function ep(r,e,t,s){for(let n=0;n<r.length;n++)e.encode(r[n],t,s),s+=e.encode.bytes;return s}function Cy(r,e,t,s){for(let n=0;n<r.length;n++)r[n]=e.decode(t,s),s+=e.decode.bytes;return s}});var LR=se((nhe,OR)=>{"use strict";var NR=WF;process.nextTick(KF,42);OR.exports=qF;function qF(r){var e=s;return t;function t(n){e(n||$F)}function s(n){var i=[n];e=o,r(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=zF(c)?s:u;i.length;)u(i.shift());function u(f){NR(VF,f,d)}}}}function zF(r){return Object.prototype.toString.call(r)==="[object Error]"}function $F(){}function VF(r,e){r.apply(null,e)}function KF(r){r===42&&(NR=process.nextTick)}function WF(r,e,t){process.nextTick(function(){r(e,t)})}});var UR=se((ihe,MR)=>{"use strict";var FS=BR(),GF=require("dgram"),XF=LR(),YF=require("events"),zS=require("os"),qS=function(){};MR.exports=function(r){r||(r={});var e=new YF.EventEmitter,t=typeof r.port=="number"?r.port:5353,s=r.type||"udp4",n=r.ip||r.host||(s==="udp4"?"224.0.0.251":null),i={address:n,port:t},o={},a=!1,c=null;if(s==="udp6"&&(!n||!r.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=r.socket||GF.createSocket({type:s,reuseAddr:r.reuseAddr!==!1,toString:function(){return s}});d.on("error",function(f){f.code==="EACCES"||f.code==="EADDRINUSE"?e.emit("error",f):e.emit("warning",f)}),d.on("message",function(f,h){try{f=FS.decode(f)}catch(y){e.emit("warning",y);return}e.emit("packet",f,h),f.type==="query"&&e.emit("query",f,h),f.type==="response"&&e.emit("response",f,h)}),d.on("listening",function(){t||(t=i.port=d.address().port),r.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),d.setMulticastTTL(r.ttl||255),d.setMulticastLoopback(r.loopback!==!1))});var u=XF(function(f){if(!t||r.bind===!1)return f(null);d.once("error",f),d.bind(t,r.bind||r.interface,function(){d.removeListener("error",f),f(null)})});return u(function(f){if(f)return e.emit("error",f);e.emit("ready")}),e.send=function(f,h,y){if(typeof h=="function")return e.send(f,null,h);y||(y=qS),h?!h.host&&!h.address&&(h.address=i.address):h=i,u(v);function v(S){if(a)return y();if(S)return y(S);var C=FS.encode(f);d.send(C,0,C.length,h.port,h.address||h.host,y)}},e.response=e.respond=function(f,h,y){Array.isArray(f)&&(f={answers:f}),f.type="response",f.flags=(f.flags||0)|FS.AUTHORITATIVE_ANSWER,e.send(f,h,y)},e.query=function(f,h,y,v){if(typeof h=="function")return e.query(f,null,null,h);if(typeof h=="object"&&h&&h.port)return e.query(f,null,h,y);if(typeof y=="function")return e.query(f,h,null,y);v||(v=qS),typeof f=="string"&&(f=[{name:f,type:h||"ANY"}]),Array.isArray(f)&&(f={type:"query",questions:f}),f.type="query",e.send(f,y,v)},e.destroy=function(f){if(f||(f=qS),a)return process.nextTick(f);a=!0,clearInterval(c);for(var h in o)try{d.dropMembership(n,h)}catch{}o={},d.close(f)},e.update=function(){for(var f=r.interface?[].concat(r.interface):QF(),h=!1,y=0;y<f.length;y++){var v=f[y];if(!o[v])try{d.addMembership(n,v),o[v]=!0,h=!0}catch(S){e.emit("warning",S)}}if(h){if(d.setMulticastInterface)try{d.setMulticastInterface(r.interface||JF())}catch(S){e.emit("warning",S)}e.emit("networkInterface")}},e};function JF(){for(var r=zS.networkInterfaces(),e=Object.keys(r),t=0;t<e.length;t++)for(var s=r[e[t]],n=0;n<s.length;n++){var i=s[n];if(DR(i.family)&&!i.internal)return zS.platform()==="darwin"&&e[t]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function QF(){for(var r=zS.networkInterfaces(),e=Object.keys(r),t=[],s=0;s<e.length;s++)for(var n=r[e[s]],i=0;i<n.length;i++){var o=n[i];if(DR(o.family)){t.push(o.address);break}}return t}function DR(r){return r===4||r==="IPv4"}});var M7={};Tf(M7,{AV1Obu:()=>M9,AV1RtpPayload:()=>l_,AttributeKeys:()=>vz,BitStream:()=>ba,BitWriter:()=>Tp,BitWriter2:()=>ux,BufferChain:()=>rq,CONSENT_FAILURES:()=>U_,CONSENT_INTERVAL:()=>fB,COOKIE:()=>wx,Candidate:()=>Sa,CandidatePair:()=>D_,CandidatePairState:()=>lB,CipherContext:()=>kp,CipherSuite:()=>Jy,CipherSuiteList:()=>i9,Connection:()=>vB,ConnectionStates:()=>eV,CurveType:()=>b2,DEFAULT_MAX_MESSAGE_SIZE:()=>Xu,DePacketizerBase:()=>Wq,Directions:()=>Hy,DtlsClient:()=>I_,DtlsServer:()=>jP,DtlsSocket:()=>R2,DtlsStates:()=>m$,Event:()=>Ie,EventDisposer:()=>Qk,ExtensionProfiles:()=>ya,FINGERPRINT_LENGTH:()=>HP,FINGERPRINT_XOR:()=>FP,GenericNack:()=>Dp,GroupDescription:()=>Zu,H264RtpPayload:()=>F9,HEADER_LENGTH:()=>co,HashAlgorithm:()=>Rp,ICE_COMPLETED:()=>M_,ICE_FAILED:()=>vp,INTEGRITY_LENGTH:()=>k2,IPV4_PROTOCOL:()=>P2,IPV6_PROTOCOL:()=>B2,IceCandidate:()=>nE,IceGathererStates:()=>w$,IceTransportStates:()=>v$,Inactive:()=>MB,Int:()=>Np,MediaDescription:()=>cx,MediaStream:()=>UB,MediaStreamTrack:()=>Fp,MediaStreamTrackFactory:()=>d$,Message:()=>Qs,NalUnitType:()=>ga,NamedCurveAlgorithm:()=>ho,NamedCurveAlgorithmList:()=>x2,OpusRtpPayload:()=>z9,PacketChunk:()=>tP,PacketResult:()=>sP,PacketStatus:()=>rP,PictureLossIndication:()=>Op,Profiles:()=>Fq,PromiseQueue:()=>uq,ProtectionProfileAeadAes128Gcm:()=>ad,ProtectionProfileAes128CmHmacSha1_80:()=>df,RETRY_MAX:()=>qP,RETRY_RTO:()=>zP,RTCCertificate:()=>sE,RTCDataChannel:()=>F2,RTCDataChannelParameters:()=>q2,RTCDtlsFingerprint:()=>ix,RTCDtlsParameters:()=>ox,RTCDtlsTransport:()=>$_,RTCIceCandidate:()=>t7,RTCIceGatherer:()=>ZB,RTCIceParameters:()=>iE,RTCIceTransport:()=>QB,RTCP_HEADER_SIZE:()=>ex,RTCPeerConnection:()=>Y$,RTCRtcpFeedback:()=>EB,RTCRtcpParameters:()=>Fz,RTCRtpCodecParameters:()=>_a,RTCRtpCodingParameters:()=>TB,RTCRtpHeaderExtensionParameters:()=>gi,RTCRtpReceiver:()=>uE,RTCRtpRtxParameters:()=>CB,RTCRtpSender:()=>B7,RTCRtpSimulcastParameters:()=>z2,RTCRtpTransceiver:()=>DB,RTCSctpCapabilities:()=>aE,RTCSctpTransport:()=>A7,RTCSessionDescription:()=>k7,RTCStatsReport:()=>LB,RTP_EXTENSION_URI:()=>Yt,ReceiverEstimatedMaxBitrate:()=>Lp,RecvDelta:()=>_p,Recvonly:()=>X2,Red:()=>T2,RedEncoder:()=>_P,RedHandler:()=>EP,RedHeader:()=>E_,RtcpHeader:()=>go,RtcpPacketConverter:()=>cP,RtcpPayloadSpecificFeedback:()=>tf,RtcpReceiverInfo:()=>vx,RtcpRrPacket:()=>rf,RtcpSenderInfo:()=>C2,RtcpSourceDescriptionPacket:()=>Up,RtcpSrPacket:()=>sd,RtcpTransportLayerFeedback:()=>rd,RtpBuilder:()=>fz,RtpHeader:()=>po,RtpPacket:()=>mo,RtpRouter:()=>P7,RunLengthChunk:()=>Qu,SDPManager:()=>O7,Sendonly:()=>G2,Sendrecv:()=>Y2,SessionDescription:()=>Cp,SignalingStates:()=>Z$,SignatureAlgorithm:()=>mi,SignatureScheme:()=>n_,SourceDescriptionChunk:()=>_2,SourceDescriptionItem:()=>E2,SrtcpSession:()=>OP,SrtpAuthenticationError:()=>nd,SrtpContext:()=>Pp,SrtpSession:()=>LP,SsrcDescription:()=>dx,StatusVectorChunk:()=>Z9,StunOverTurnProtocol:()=>eB,StunProtocol:()=>tx,TcpTransport:()=>s9,TransceiverManager:()=>D7,TransportWideCC:()=>Mp,TurnProtocol:()=>rB,UdpTransport:()=>Yy,Vp8RtpPayload:()=>V9,Vp9RtpPayload:()=>W9,WeriftError:()=>lq,addSDPHeader:()=>o2,andDirection:()=>eE,buffer2ArrayBuffer:()=>nq,bufferArrayXor:()=>eq,bufferReader:()=>is,bufferWriter:()=>er,bufferWriterLE:()=>Fk,bufferXor:()=>ZF,candidateFoundation:()=>rx,candidateFromIce:()=>of,candidateFromSdp:()=>dE,candidatePairPriority:()=>sx,candidatePriority:()=>Ep,candidateToIce:()=>e7,candidateToSdp:()=>cE,certificateTypes:()=>o9,classes:()=>N2,codecParametersFromString:()=>Vp,codecParametersToString:()=>q$,compactNtp:()=>rE,crc32:()=>Wk,crc32c:()=>m2,createBufferWriter:()=>Sp,createSelfSignedCertificate:()=>c$,createStunOverTurnClient:()=>B_,createTurnClient:()=>nB,dePacketizeRtpPackets:()=>Gq,debug:()=>ut,deepMerge:()=>$B,defaultOptions:()=>hB,defaultPeerConfig:()=>J$,depacketizerCodecs:()=>Xq,deserializeAbsSendTime:()=>xP,deserializeAudioLevelIndication:()=>bP,deserializeString:()=>gP,deserializeUint16BE:()=>yP,deserializeVideoOrientation:()=>vP,dumpBuffer:()=>sq,enumerate:()=>Yq,findCodecByMimeType:()=>f2,findPort:()=>Yk,fingerprint:()=>Q2,generateStatsId:()=>qt,getBit:()=>xe,getDataChannelMessageSize:()=>SB,getGlobalIp:()=>Dz,getHostAddresses:()=>bB,getStatsTimestamp:()=>Ea,growBufferSize:()=>h_,int:()=>Yu,interfaceAddress:()=>lx,isDtls:()=>jB,isLinkLocalAddress:()=>xB,isMedia:()=>X9,isRtcp:()=>dP,keyLength:()=>N9,leb128decode:()=>j9,makeIntegrityKey:()=>iB,methods:()=>O2,microTime:()=>FB,milliTime:()=>tE,nodeIpAddress:()=>F_,normalizeFamilyNodeV18:()=>Ip,normalizeFingerprintAlgorithm:()=>Z2,normalizeFingerprintValue:()=>nx,ntpTime:()=>qB,ntpTime2Sec:()=>aP,paddingBits:()=>tq,paddingByte:()=>Ap,paddingLength:()=>k_,parseGroup:()=>Gy,parseIceServers:()=>zB,parseMessage:()=>Sx,random16:()=>p2,random32:()=>Xy,randomPort:()=>y2,randomPorts:()=>fq,reverseDirection:()=>HB,reverseSimulcastDirection:()=>o$,rtpHeaderExtensionsParser:()=>uP,saltLength:()=>O9,serializeAbsSendTime:()=>mP,serializeAudioLevelIndication:()=>rz,serializeRepairedRtpStreamId:()=>hP,serializeSdesMid:()=>fP,serializeSdesRTPStreamID:()=>lP,serializeTransportWideCC:()=>pP,serverReflexiveCandidate:()=>mB,signatures:()=>v2,sortCandidatePairs:()=>pB,supportedAudioCodecs:()=>zz,supportedCodecs:()=>W2,supportedVideoCodecs:()=>qz,timer:()=>Jq,timestampSeconds:()=>qp,uint16Add:()=>Ur,uint16Gt:()=>fx,uint16Gte:()=>dq,uint24:()=>Xk,uint32Add:()=>Yc,uint32Gt:()=>li,uint32Gte:()=>Gu,uint8Add:()=>Gk,unwrapRtx:()=>TP,url2Address:()=>Mz,useAV1X:()=>RB,useAbsSendTime:()=>Gz,useAudioLevelIndication:()=>Yz,useDependencyDescriptor:()=>Xz,useFIR:()=>Hz,useH264:()=>AB,useNACK:()=>Zp,useOPUS:()=>V2,usePCMU:()=>K2,usePLI:()=>ff,useREMB:()=>e0,useRepairedRtpStreamId:()=>Kz,useSdesMid:()=>$z,useSdesRTPStreamId:()=>Vz,useTWCC:()=>_B,useTransportWideCC:()=>Wz,useVP8:()=>$2,useVP9:()=>IB,useVideoOrientation:()=>Jz,validateAddress:()=>H_,validateRemoteCandidate:()=>j_,wrapRtx:()=>AP});function p2(){return h2.jspack.Unpack("!H",(0,l2.randomBytes)(2))[0]}function Xy(){return h2.jspack.Unpack("!L",(0,l2.randomBytes)(4))[0]}function ZF(r,e){if(r.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let t=r.length,s=Buffer.allocUnsafe(t);for(let n=0;n<t;n++)s[n]=r[n]^e[n];return s}function eq(r){let e=[...r].sort((s,n)=>s.length-n.length).reverse()[0].length,t=Buffer.allocUnsafe(e);for(let s=0;s<e;s++)t[s]=0,r.forEach(n=>{t[s]^=n[s]??0});return t}function xe(r,e,t=1){let s=r.toString(2).split("");s=[...Array(8-s.length).fill("0"),...s];let n=s.slice(e,e+t).join("");return Number.parseInt(n,2)}function Ap(r){let e=r.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function tq(r,e){let t=r.toString(2);return[...[...Array(e-t.length)].map(()=>"0"),...t].join("")}function er(r,e){return Sp(r)(e)}function Sp(r,e){let t=r.reduce((n,i)=>n+i,0),s=e?Buffer.alloc(t):void 0;return n=>{let i=s||Buffer.alloc(t),o=0;return n.forEach((a,c)=>{let d=r[c];d===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,d),o+=d}),i}}function Fk(r,e){let t=r.reduce((i,o)=>i+o,0),s=Buffer.alloc(t),n=0;return e.forEach((i,o)=>{let a=r[o];a===8?s.writeBigUInt64LE(i,n):s.writeUIntLE(i,n,a),n+=a}),s}function is(r,e){let t=0;return e.map(s=>{let n;return s===8?n=r.readBigUInt64BE(t):n=r.readUIntBE(t,s),t+=s,n})}function nq(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function qk(r){return typeof r!="string"}function zk(r){let e=new Array(256),t=0;for(let s=0;s<256;++s)t=s,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,e[s]=t;return new Int32Array(e)}function $k(r){let e=new Int32Array(4096),t=0,s=0,n=0;for(n=0;n<256;++n)e[n]=r[n];for(n=0;n<256;++n)for(s=r[n],t=256+n;t<4096;t+=256)s=e[t]=s>>>8^r[s&255];let i=[];for(n=1;n<16;++n)i[n-1]=e.subarray(n*256,n*256+256);return i}function Vk(r,e,t){let s=e^-1,n=0,i=r.length,o=0,a=0;for(;n<i;)o=r.charCodeAt(n++),o<128?s=s>>>8^t[(s^o)&255]:o<2048?(s=s>>>8^t[(s^(192|o>>6&31))&255],s=s>>>8^t[(s^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=r.charCodeAt(n++)&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|a>>6&15|(o&3)<<4))&255],s=s>>>8^t[(s^(128|a&63))&255]):(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}function Kk(r,e,t,s){let[n,i,o,a,c,d,u,f,h,y,v,S,C,O,K]=s,z=e^-1,Q=0,oe=r.length-15;for(;Q<oe;)z=K[r[Q++]^z&255]^O[r[Q++]^z>>>8&255]^C[r[Q++]^z>>>16&255]^S[r[Q++]^z>>>24]^v[r[Q++]]^y[r[Q++]]^h[r[Q++]]^f[r[Q++]]^u[r[Q++]]^d[r[Q++]]^c[r[Q++]]^a[r[Q++]]^o[r[Q++]]^i[r[Q++]]^n[r[Q++]]^t[r[Q++]];for(oe+=15;Q<oe;)z=z>>>8^t[(z^r[Q++])&255];return~z>>>0}function Wk(r,e=0){return qk(r)?Kk(r,e,r_,aq):Vk(r,e,r_)}function m2(r,e=0){return qk(r)?Kk(r,e,s_,cq):Vk(r,e,s_)}function Gk(r,e){return r+e&255}function Ur(r,e){return r+e&65535}function Yc(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}function Xk(r){return r&16777215}function fx(r,e){return r<e&&e-r>32768||r>e&&r-e<32768}function dq(r,e){return r===e||fx(r,e)}function li(r,e){return r<e&&e-r>2147483648||r>e&&r-e<2147483648}function Gu(r,e){return r===e||li(r,e)}async function y2(r="udp4",e){let t=(0,g2.createSocket)(r);setImmediate(()=>t.bind({port:0,address:lx(r,e)})),await new Promise(n=>{t.once("error",n),t.once("listening",n)});let s=t.address()?.port;return await new Promise(n=>t.close(()=>n())),s}async function fq(r,e="udp4",t){return Promise.all([...Array(r)].map(()=>y2(e,t)))}async function Yk(r,e,t="udp4",s){let n;for(let i=r;i<=e;i++){let o=(0,g2.createSocket)(t);if(setImmediate(()=>o.bind({port:i,address:lx(t,s)})),await new Promise(c=>{o.once("error",d=>c(d)),o.once("listening",()=>c())})){await new Promise(c=>o.close(()=>c()));continue}if(n=o.address()?.port,await new Promise(c=>o.close(()=>c())),r<=n&&n<=e)break}if(!n)throw new Error("port not found");return n}function Ip(r){return r==="IPv4"?4:r==="IPv6"?6:r}function d9(r,e,t){switch(t){case ho.secp256r1_23:return pq({publicKey:r,privateKey:e});case ho.x25519_29:return Buffer.from(c9.default.scalarMult(e,r));default:throw new Error}}function HR(r,e,t){let s=(0,px.createHmac)(r,e);return s.update(t),s.digest()}function Kp(r,e,t,s="sha256"){let n=t,i=[],o=e;do{o=HR(s,r,o);let a=HR(s,r,Buffer.concat([o,e]));i.push(a),t-=a.length}while(t>0);return Buffer.concat(i,n)}function u9(r,e,t){let s=Buffer.concat([Buffer.from("master secret"),e,t]);return Kp(r,s,48)}function f9(r,e){let t=l9("sha256",e);return Kp(r,Buffer.concat([Buffer.from("extended master secret"),t]),48)}function mq(r,e,t,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(r),o,a]);return Kp(t,c,e)}function l9(r,e){return(0,px.createHash)(r).update(e).digest()}function h9(r,e,t,s=12){let n=l9("sha256",e);return Kp(r,Buffer.concat([Buffer.from(t),n]),s)}function gq(r,e){return h9(r,e,"client finished")}function yq(r,e){return h9(r,e,"server finished")}function xq(r,e,t,s,n,i,o="sha256"){let a=s*2+n*2,c=r,d=Buffer.concat([t,e]),u=Kp(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),f=(0,a9.createDecode)(u),h=f.readBuffer(s),y=f.readBuffer(s),v=f.readBuffer(n),S=f.readBuffer(n),C=Buffer.alloc(i,0),O=Buffer.alloc(i,0);return v.copy(C,0),S.copy(O,0),{clientWriteKey:h,serverWriteKey:y,clientNonce:C,serverNonce:O}}function Nq(){let r=new Jp;return r.id=Yp.RSA,r.name="RSA",r.keyType=Xp.RSA,r}function Oq(){let r=new Jp;return r.id=Yp.ECDHE_RSA,r.name="ECDHE_RSA",r.signType=mx.ECDHE,r.keyType=Xp.RSA,r}function Lq(){let r=new Jp;return r.id=Yp.ECDHE_ECDSA,r.name="ECDHE_ECDSA",r.signType=mx.ECDHE,r.keyType=Xp.ECDSA,r}function Dq(){let r=new Jp;return r.id=Yp.PSK,r.name="PSK",r.signType=mx.NULL,r.keyType=Xp.PSK,r}function Mq(){let r=new Jp;return r.id=Yp.ECDHE_PSK,r.name="ECDHE_PSK",r.signType=mx.ECDHE,r.keyType=Xp.PSK,r}function S9(r){switch(r){case mr.TLS_RSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",FR,tp);case mr.TLS_RSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",FR,rp,"sha384");case mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",qR,tp);case mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",qR,rp,"sha384");case mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",zR,tp);case mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",zR,rp,"sha384");case mr.TLS_PSK_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",$R,tp,"sha256");case mr.TLS_PSK_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",$R,rp,"sha384");case mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",VR,tp,"sha256");case mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",VR,rp,"sha384");default:break}return null}function ui(r,e,t,s,n,i="sha256"){let o=new jq;return o.id=r,o.name=e,o.blockAlgorithm=t,o.kx=s,o.hashAlgorithm=i,o.keyLength=n.K_LEN,o.nonceLength=n.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function E9(r){switch(r){case ho.secp256r1_23:{let{privateKey:e,publicKey:t}=hq();return{curve:r,privateKey:e,publicKey:t}}case ho.x25519_29:{let e=_9.default.box.keyPair();return{curve:r,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function Hq(r,e){return Buffer.from((0,P9.encode)(r,e).slice())}function j9(r){let e=0,t=0;for(let s=0;s<8;s++){let n=r.readUInt8(s);if(e|=(n&127)<<s*7,t++,!(n&128))break}return[e,t]}function Gq(r,e,t){let s=n=>{let i=[];for(let c of e){let d=n.deSerialize(c.payload,t);d.fragment?(t??=Buffer.alloc(0),t=d.fragment):d.payload&&(t=void 0),i.push(d)}let o=!!i.find(c=>c.isKeyframe),a=Buffer.concat(i.map(c=>c.payload).filter(c=>c));return{isKeyframe:o,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:t}};switch(r.toUpperCase()){case"AV1":{let n=e.map(a=>l_.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=l_.getFrame(n);return{isKeyframe:i,data:o,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return s(F9);case"VP8":return s(V9);case"VP9":return s(W9);case"OPUS":return s(z9);default:throw new Error}}function Yq(r){return r.map((e,t)=>[t,e])}function h_(r,e){let t=Buffer.alloc(e);return r.copy(t),t}function Np(r){return Number.parseInt(r.toString(),10)}function X9(r){let e=r[0];return e>127&&e<192}function WR(r){return r%4==0?0:4-r%4}function dP(r){return r.length>=2&&r[1]>=192&&r[1]<=208}function uP(r,e){return r.map(t=>{let s=e[t.id];if(!s)return{uri:"unknown",value:t.payload};switch(s){case Yt.sdesMid:case Yt.sdesRTPStreamID:case Yt.repairedRtpStreamId:return{uri:s,value:gP(t.payload)};case Yt.transportWideCC:return{uri:s,value:yP(t.payload)};case Yt.absSendTime:return{uri:s,value:xP(t.payload)};case Yt.audioLevelIndication:return{uri:s,value:bP(t.payload)};case Yt.videoOrientation:return{uri:s,value:vP(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>(s&&(t[s.uri]=s.value),t),{})}function fP(r){return Buffer.from(r)}function lP(r){return Buffer.from(r)}function hP(r){return Buffer.from(r)}function pP(r){return er([2],[r])}function mP(r){let e=Buffer.alloc(3),t=r>>14n&0x00ffffffn;return e.writeUIntBE(Number(t),0,3),e}function rz(r){let e=new ba(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,r),e.uint8Array}function gP(r){return r.toString()}function yP(r){return r.readUInt16BE()}function xP(r){return is(r,[3])[0]}function bP(r){let e=new ba(r);return{v:e.readBits(1)===1,level:e.readBits(7)}}function vP(r){let e=new ba(r);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function TP(r,e,t){return new mo(new po({payloadType:e,marker:r.header.marker,sequenceNumber:A2.jspack.Unpack("!H",r.payload.subarray(0,2))[0],timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2))}function AP(r,e,t,s){return new mo(new po({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([Buffer.from(A2.jspack.Pack("!H",[r.header.sequenceNumber])),r.payload]))}function I2(r,e,t="Failed to authenticate SRTP packet"){let s=r.length-e;jp(r.length>=ZR+e,t);let n=kP(()=>po.deSerialize(r.subarray(0,s)),t);return n.paddingSize=0,jp(n.payloadOffset>=ZR&&n.payloadOffset<=s,t),n}function RP(r,e,t,s="Failed to authenticate SRTCP packet"){return jp(r.length>=iz+e+t,s),kP(()=>go.deSerialize(r.subarray(0,ex)),s)}function jp(r,e){if(!r)throw new nd(e)}function kP(r,e){try{return r()}catch{throw new nd(e)}}function PP(r,e,t="Failed to authenticate SRTP packet"){if(!r.padding)return r.paddingSize=0,r;jp(e.length>r.payloadOffset,t);let s=e[e.length-1];return jp(s>0&&s<=e.length-r.payloadOffset,t),r.paddingSize=s,r}function tk(r,e,t){if(r.length!==e.length||!(0,An.timingSafeEqual)(r,e))throw new nd(t)}function sk(r,e){try{r.final()}catch{throw new nd(`Failed to authenticate ${e} packet`)}}function np(r){return(0,D2.randomBytes)(r).toString("hex").substring(0,r)}function $P(){return(0,D2.randomBytes)(12)}function Vu(r){let[e]=r,t=Hp.default.isV4Format(e)?P2:B2,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(t,1),s.writeUInt16BE(r[1],2),Buffer.concat([s,Hp.default.toBuffer(e)])}function wz(r){if(r.length<4)throw new Error("STUN error code is less than 4 bytes");let e=r.readUInt8(2),t=r.readUInt8(3),s=r.slice(4).toString("utf8");return[e*100+t,s]}function Ku(r){if(r.length<4)throw new Error("STUN address length is less than 4 bytes");let e=r.readUInt8(1),t=r.readUInt16BE(2),s=r.slice(4);switch(e){case P2:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[Hp.default.toString(s),t];case B2:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[Hp.default.toString(s),t];default:throw new Error("STUN address has unknown protocol")}}function VP(r,e){let t=[...M2,...e],s=r.slice(0,2);for(let n=2;n<r.length;n++){let i=r[n]^t[n-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),s=Buffer.concat([s,o])}return s}function Ly(r,e){return Ku(VP(r,e))}function Sz(r){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(r[0]/100),2),e.writeUInt8(r[0]%100,3);let t=Buffer.from(r[1],"utf8");return Buffer.concat([e,t])}function Dy(r,e){return VP(Vu(r),e)}function Sx(r,e){if(r.length<co)return;let t=r.readUint16BE(2);if(r.length!==co+t)return;let s=r.readUint16BE(0),n=Buffer.from(r.slice(co-12,co)),i=new WP;for(let a=co;a<=r.length-4;){let c=r.readUInt16BE(a),d=r.readUInt16BE(a+2),u=r.slice(a+4,a+4+d),f=4*Math.floor((d+3)/4)-d;if(Object.keys(pk).includes(c.toString())){let[,y,,v]=pk[c];if(v.name===Ly.name?i.setAttribute(y,v(u,n)):i.setAttribute(y,v(u)),y==="FINGERPRINT"){let S=GP(r.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==S)return}else if(y==="MESSAGE-INTEGRITY"&&e){let S=Iz(r.slice(0,a),e),C=i.getAttributeValue("MESSAGE-INTEGRITY");if(!S.equals(C))return}}a+=4+d+f}let o=i.getAttributes();return i.clear(),new Qs(s&16111,s&272,n,o)}function GP(r){let e=U2(r,r.length-co+HP);return(Wk(e)^FP)>>>0}function Iz(r,e){let t=U2(r,r.length-co+k2);return Buffer.from((0,L2.createHmac)("sha1",e).update(t).digest("hex"),"hex")}function k_(r){let e=r%4;return e===0?0:4-e}async function nB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=Pz,o??="udp";let a=o==="udp"?await Yy.init("udp4",{portRange:n,interfaceAddresses:i}):await s9.init(r),c=new rB(r,e,t,s,a);return await c.connectionMade(),c}async function B_({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await nB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new eB(a)}function iB(r,e,t){return(0,QP.createHash)("md5").update(Buffer.from([r,e,t].join(":"))).digest()}function gk(r){return(r[0]&192)==64}function rx(r,e,t){let s=`${r}|${e}|${t}`;return(0,oB.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function Ep(r,e=65535){let s=0;return r==="host"?s=126:r==="prflx"?s=110:r==="srflx"?s=100:s=0,(1<<24)*s+256*e+255}function j_(r){if(!["host","relay","srflx"].includes(r.type))throw new Error(`Unexpected candidate type "${r.type}"`);return r}function pB(r,e){return r.sort((t,s)=>sx(t.localCandidate,t.remoteCandidate,e)-sx(s.localCandidate,s.remoteCandidate,e)).reverse()}function sx(r,e,t){let s=t&&r.priority||e.priority,n=t&&e.priority||r.priority;return 1*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}async function mB(r,e){let t=new Qs(1,0);try{let[s]=await r.request(t,e),n=r.localCandidate;if(!n)throw new Error("not exist");return new Sa(rx("srflx","udp",n.host),n.component,n.transport,Ep("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){Oz("error serverReflexiveCandidate",s)}}function H_(r){return r&&Number.isNaN(r[1])?[r[0],443]:r}async function Dz(r,e){let t=new tx;await t.connectionMade(!0,void 0,e);let s=new Qs(1,0),[n]=await t.request(s,r??["stun.l.google.com",19302]);return await t.close(),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function xB(r){return Ip(r.family)===4&&r.address?.startsWith("169.254.")||Ip(r.family)===6&&r.address?.startsWith("fe80::")}function F_(r,{useLinkLocalAddress:e}={}){let t=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=gB.networkInterfaces();Lz(n);let i=Object.keys(n).map(o=>{for(let c of[...t,...s])if(o.startsWith(c))return{nic:o,addresses:[]};let a=n[o].filter(c=>Ip(c.family)===r&&!yB.default.isLoopback(c.address)&&(e?!0:!xB(c)));return{nic:o,addresses:a.map(c=>c.address)}}).filter(o=>!!o);return i.sort((o,a)=>o.nic.localeCompare(a.nic)),Object.values(i).flatMap(o=>o.addresses)}function bB(r,e,t={}){let s=[];return r&&s.push(...F_(4,t)),e&&s.push(...F_(6,t)),s}function xk(r){return r.map((e,t)=>[t,e])}function ao(r,e){let t=r.split(e);return[t[0],t.slice(1).join(e)]}function SB(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}function $z(){return new gi({uri:Yt.sdesMid})}function Vz(){return new gi({uri:Yt.sdesRTPStreamID})}function Kz(){return new gi({uri:Yt.repairedRtpStreamId})}function Wz(){return new gi({uri:Yt.transportWideCC})}function Gz(){return new gi({uri:Yt.absSendTime})}function Xz(){return new gi({uri:Yt.dependencyDescriptor})}function Yz(){return new gi({uri:Yt.audioLevelIndication})}function Jz(){return new gi({uri:Yt.videoOrientation})}function qt(r,...e){let t=e.filter(s=>s!==void 0);return`${r}_${t.join("_")}`}function Ea(){return performance.now()}function Q2(r,e){let t=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,PB.createHash)(e).update(r).digest("hex");return s(t(n))}function Z2(r){return i$[r.trim().toLowerCase()]}function nx(r){return r.replace(/[^0-9a-f]/gi,"").toLowerCase()}function jB(r){let e=r[0];return e>19&&e<64}function o$(r){return r==="recv"?"send":"recv"}function HB(r){return r==="sendonly"?"recvonly":r==="recvonly"?"sendonly":r}function zB(r){let e=a=>{if(!a)return;let[c,d]=a.split(":");return[c,Number.parseInt(d)]},t=e(r.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),s=e(r.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:n,username:i}=r.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:t,turnServer:s,turnUsername:i,turnPassword:n};return n$("iceOptions",o),o}function of(r){let e=new nE(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);return e.relatedAddress=r.relatedAddress,e.relatedPort=r.relatedPort,e.tcpType=r.tcptype,e}function e7(r){return new Sa(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}function r0(r){let e=r%4;return e?4-e:0}function _7(r){let e=Buffer.from(""),t=Buffer.from("");return r.forEach(([s,n])=>{let i=n.length+4,o=Buffer.alloc(4);o.writeUInt16BE(s,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,t,o,n]),t=Buffer.concat([...Array(r0(i))].map(()=>Buffer.from("\0")))}),e}function E7(r){let e=[],t=0;for(;t<=r.length-4;){let s=r.readUInt16BE(t),n=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+n)]),t+=n+r0(n)}return e}function C$(r){if(r.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=r.readUInt16BE(0),t=r.readUInt16BE(2),s=r.readUInt32BE(4),n=r.readUInt32LE(8),i=m2(Buffer.concat([r.slice(0,8),Buffer.from("\0\0\0\0"),r.slice(12)]));if(n!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=r.length;){let c=r.readUInt8(a),d=r.readUInt8(a+1),u=r.readUInt16BE(a+2),f=r.slice(a+4,a+u),h=E$[c.toString()];if(h)o.push(new h(d,f));else throw new Error("unknown");a+=u+r0(u)}return[e,t,s,o]}function T$(r,e,t,s){let n=Buffer.alloc(8);n.writeUInt16BE(r,0),n.writeUInt16BE(e,2),n.writeUInt32BE(t,4);let i=s.bytes,o=m2(Buffer.concat([n,Buffer.from("\0\0\0\0"),i])),a=Buffer.alloc(4);return a.writeUInt32LE(o,0),Buffer.concat([n,a,i])}function A$(r){return r.map((e,t)=>[t,e])}function I$(r){return r.reduce((e,t)=>(e[t]=new Ie,e),{})}function Gc(r){return(r-1)%ax}function Wu(r){return(r+1)%ax}function ZS(r){let e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function i2(r){return`IN IP${(0,WB.isIPv4)(r)?4:6} ${r}`}function cE(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;return r.relatedAddress!=null&&(e+=` raddr ${r.relatedAddress}`),r.relatedPort!=null&&(e+=` rport ${r.relatedPort}`),r.tcpType!=null&&(e+=` tcptype ${r.tcpType}`),r.generation!=null&&(e+=` generation ${r.generation}`),r.ufrag!=null&&(e+=` ufrag ${r.ufrag}`),e}function F$(r){let e=[],t=[],s=r.split(`\r
131
- `);return s.length===1&&(s=r.split(`
132
- `)),s.forEach(n=>{n.startsWith("m=")?t.push([n]):t.length>0?t[t.length-1].push(n):e.push(n)}),[e,t]}function e_(r){if(r.includes(":")){let e=ao(r.slice(2),":");return[e[0],e[1]]}else return[r.slice(2),void 0]}function Gy(r,e,t=s=>s.toString()){let s=e.split(" ");s.length>0&&r.push(new Zu(s[0],s.slice(1).map(t)))}function dE(r){let e=Sa.fromSdp(r);return of(e)}function o2(r,e){let s=new Sy((0,KB.randomBytes)(64)).toString().slice(0,8),n=0;e.origin=`- ${s} ${n} IN IP4 0.0.0.0`,e.msidSemantic.push(new Zu("WMS",["*"])),e.type=r}function Vp(r){let e={};return r.split(";").forEach(t=>{if(t.includes("=")){let[s,n]=ao(t,"=");r$.includes(s)?e[s]=Number(n):e[s]=n}else if(t.includes(":")){let[s,n]=t.split(":");e[s]=Number.isNaN(Number(n))?n:Number(n)}else e[t]=void 0}),e}function q$(r,e="="){let t=Object.entries(r).map(([s,n])=>n?`${s}${e}${n}`:s);if(t.length>0)return t.join(";")}function L7(){return{codecs:{audio:[V2(),K2()],video:[$2()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:Xu}}var l2,h2,g2,Jk,Zk,e9,t9,af,hx,Ju,px,a9,c9,Mr,En,m9,y9,Jc,b9,uo,gx,_9,Zc,va,ed,cf,wa,td,Cn,Tn,bx,_n,P9,L9,A2,By,Ny,An,sf,id,Xc,MP,pi,hi,od,UP,L2,D2,Hp,QP,P_,ZP,oB,N_,cB,O_,L_,My,dB,uB,gB,yB,wB,kB,Uy,PB,BB,q_,NB,J2,VB,KB,WB,zp,GB,XB,JB,r7,Fy,$p,qy,fo,a2,c2,d2,u2,N7,Tp,ux,rq,sq,ba,iq,oq,r_,aq,s_,cq,Yu,uq,lx,lq,ut,Ie,Qk,jR,Yy,s9,mi,Rp,Jy,i9,ho,x2,b2,n_,o9,v2,hq,pq,lo,bq,i_,kp,Pp,w2,p9,Zs,Qy,vq,g9,wq,Bp,Sq,_q,o_,Eq,Cq,Tq,Aq,S2,Qc,x9,Iq,v9,w9,Wp,c_,Rq,$S,Gp,kq,Pq,Bq,mx,Xp,Yp,Jp,Uq,jq,mr,tp,rp,FR,qR,zR,$R,VR,yx,xx,ef,Zy,C9,T9,A9,u_,I9,R9,k9,B9,df,ad,Fq,N9,O9,qq,l_,M9,H9,zq,F9,ga,$q,Vq,Kq,z9,V9,W9,Wq,Xq,Jq,ex,go,KR,Op,Lp,Qq,tf,rf,vx,J9,Dp,Zq,Mp,Qu,Z9,_p,tP,rP,sP,ez,rd,Up,_2,E2,sd,C2,aP,tz,cP,Yt,sz,T2,E_,_P,nz,EP,ya,GR,XR,YR,JR,QR,po,mo,IP,nd,ZR,iz,oz,ek,az,VS,rk,BP,sp,nk,cz,dz,NP,OP,uz,LP,fz,ns,lz,uf,DP,hz,ik,pz,T_,A_,ok,ak,KS,mz,gz,ck,dk,R2,WS,I_,fi,yz,uk,xz,nf,bz,Qp,Fu,jP,wx,HP,FP,co,k2,P2,B2,qP,zP,vz,N2,O2,fk,R_,M2,ip,op,_z,Ez,lk,hk,GS,XS,YS,JS,Cz,Tz,KP,WP,pk,Az,Qs,U2,XP,YP,Rz,QS,j2,mk,tx,vs,kz,Pz,Bz,eB,rB,Sa,Nz,Oz,D_,M_,vp,fB,U_,lB,hB,Lz,Mz,Ut,vB,Uz,yk,H2,jz,F2,q2,Hz,Zp,ff,e0,_B,_a,gi,Fz,EB,CB,TB,z2,AB,$2,IB,RB,V2,K2,W2,qz,zz,bk,vk,Qz,Ay,wk,Sk,Zz,e$,t$,_k,z_,Ek,r$,OB,Ck,jy,s$,LB,DB,MB,G2,X2,Y2,Hy,Fp,UB,n$,i$,eE,tE,a$,FB,qp,qB,rE,c$,d$,$B,u$,Tk,f$,l$,h$,p$,vn,$_,m$,sE,ix,ox,g$,y$,x$,b$,Ak,Ik,QB,v$,w$,ZB,t7,nE,iE,yi,oE,zy,V_,S$,$y,Vy,K_,W_,t0,G_,Ky,Y_,h7,J_,Q_,y7,b7,w7,_$,E$,Z_,C7,Iy,Wy,Rk,Lt,R$,k$,kk,wn,wp,T7,s2,Pk,P$,Bk,Nk,Ok,B$,N$,ax,O$,L$,Lk,Dk,Mk,Uk,D$,M$,U$,j$,qu,Xu,A7,aE,H$,Cp,cx,Zu,k7,dx,Ry,uE,ap,P7,z$,zu,$$,V$,t_,jk,Hk,B7,K$,W$,O7,cp,G$,X$,Sn,Y$,f2,J$,Q$,D7,Z$,eV,U7=A(()=>{"use strict";l2=require("crypto"),h2=Ge(wo(),1),g2=require("dgram"),Jk=Ge(p6(),1),Zk=require("dgram"),e9=Ge(require("net"),1),t9=require("net"),af=require("crypto"),hx=Ge(Jb(),1);TA();Ju=Ge(Zt(),1),px=require("crypto"),a9=Ge(Zt(),1),c9=Ge(Z0(),1);dR();Mr=Ge(Zt(),1),En=Ge(Zt(),1),m9=Ge(Zt(),1),y9=require("crypto"),Jc=Ge(Zt(),1),b9=require("timers/promises"),uo=Ge(Zt(),1),gx=require("crypto"),_9=Ge(Z0(),1),Zc=Ge(Zt(),1),va=Ge(Zt(),1),ed=Ge(Zt(),1),cf=Ge(Zt(),1),wa=Ge(Zt(),1),td=Ge(Zt(),1),Cn=Ge(Zt(),1),Tn=Ge(Zt(),1),bx=Ge(Zt(),1),_n=Ge(Zt(),1),P9=Ge(Zt(),1),L9=Ge(fR(),1),A2=Ge(wo(),1),By=require("crypto"),Ny=Ge(hR(),1),An=require("crypto"),sf=require("crypto"),id=Ge(Zt(),1),Xc=Ge(Zt(),1),MP=require("timers/promises"),pi=Ge(Zt(),1),hi=Ge(Zt(),1),od=Ge(Zt(),1),UP=require("crypto"),L2=require("crypto"),D2=require("crypto");_y();Hp=Ge(PS(),1),QP=require("crypto"),P_=Ge(wo(),1),ZP=require("timers/promises"),oB=require("crypto"),N_=require("net"),cB=require("crypto"),O_=require("net");_y();L_=Ge(require("timers/promises"),1),My=Ge(wR(),1),dB=Ge(UR(),1),uB=require("crypto"),gB=Ge(require("os"),1),yB=Ge(PS(),1),wB=require("events"),kB=require("crypto"),Uy=require("timers/promises"),PB=require("crypto"),BB=require("dgram"),q_=require("perf_hooks"),NB=require("crypto"),J2=require("crypto"),VB=require("timers/promises"),KB=require("crypto"),WB=require("net");_y();zp=Ge(Jb(),1),GB=require("crypto"),XB=require("timers/promises"),JB=require("crypto"),r7=require("crypto"),Fy=Ge(wo(),1),$p=require("crypto"),qy=Ge(wo(),1),fo=Ge(wo(),1),a2=require("crypto"),c2=Ge(wo(),1),d2=require("crypto"),u2=require("timers/promises"),N7=require("crypto");Tp=class{constructor(r){this.bitLength=r}value=0;set(r,e,t){return t&=(1<<r)-1,this.value|=t<<this.bitLength-r-e,this}get buffer(){let r=Math.ceil(this.bitLength/8),e=Buffer.alloc(r);return e.writeUIntBE(this.value,0,r),e}},ux=class{constructor(r){if(this.bitLength=r,r>32)throw new Error}_value=0n;offset=0n;set(r,e=1){let t=BigInt(r),s=BigInt(e);return t&=(1n<<s)-1n,this._value|=t<<BigInt(this.bitLength)-s-this.offset,this.offset+=s,this}get value(){return Number(this._value)}get buffer(){let r=Math.ceil(this.bitLength/8),e=Buffer.alloc(r);return e.writeUIntBE(this.value,0,r),e}};rq=class{buffer;constructor(r){this.buffer=Buffer.alloc(r)}writeInt16BE(r,e){return this.buffer.writeInt16BE(r,e),this}writeUInt8(r,e){return this.buffer.writeUInt8(r,e),this}},sq=r=>"0x"+r.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");ba=class{constructor(r){this.uint8Array=r}position=0;bitsPending=0;writeBits(r,e){if(r==0)return this;e&=4294967295>>>32-r;let t;return this.bitsPending>0?this.bitsPending>r?(this.uint8Array[this.position-1]|=e<<this.bitsPending-r,t=r,this.bitsPending-=r):this.bitsPending==r?(this.uint8Array[this.position-1]|=e,t=r,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>r-this.bitsPending,t=this.bitsPending,this.bitsPending=0):(t=Math.min(8,r),this.bitsPending=8-t,this.uint8Array[this.position++]=e>>r-t<<this.bitsPending),r-=t,r>0&&this.writeBits(r,e),this}readBits(r){return this._readBits(r)}_readBits(r,e){if(typeof e>"u"&&(e=0),r==0)return e;let t,s;if(this.bitsPending>0){let n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;s=Math.min(this.bitsPending,r),this.bitsPending-=s,t=n>>this.bitsPending}else s=Math.min(8,r),this.bitsPending=8-s,t=this.uint8Array[this.position++]>>this.bitsPending;return r-=s,e=e<<s|t,r>0?this._readBits(r,e):e}seekTo(r){this.position=r/8|0,this.bitsPending=r%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},iq=3988292384,oq=2197175160;r_=zk(iq),aq=$k(r_),s_=zk(oq),cq=$k(s_);Yu=r=>Number.parseInt(r,10),uq=class{queue=[];running=!1;push=r=>new Promise((e,t)=>{this.queue.push({promise:r,done:e,failed:t}),this.running||this.run()});async run(){let r=this.queue.shift();if(r){this.running=!0;try{let e=await r.promise();r.done(e)}catch(e){r.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},lx=(r,e)=>e?e[r]:void 0;lq=class extends Error{message;payload;path;constructor(r){super(r.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},ut=Jk.default.debug,Ie=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=r=>{};execute=(...r)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...r);(async()=>{for(let e of this.event.promiseStack)await e.execute(...r)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let r of this.event.stack)r.complete&&r.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=r=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(r);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(r,e,t)=>{let s=this.event.eventId;this.event.stack.push({execute:r,id:s,complete:e,error:t}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};pipe(r){this.subscribe((...e)=>{r.execute(...e)})}queuingSubscribe=(r,e,t)=>{if(this.ended)throw new Error("event completed");let s=this.event.eventId;this.event.promiseStack.push({execute:r,id:s,complete:e,error:t}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};once=(r,e,t)=>{let s=this.subscribe((...n)=>{s.unSubscribe(),r(...n)},e,t)};watch=(r,e)=>new Promise((t,s)=>{let n=e&&setTimeout(()=>{s("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{r(...o)&&(n&&clearTimeout(n),i(),t(o))})});asPromise=r=>new Promise((e,t)=>{let s=r&&setTimeout(()=>{t("Event asPromise timeout")},r);this.once((...n)=>{s&&clearTimeout(s),e(n)},()=>{s&&clearTimeout(s),e([])},n=>{s&&clearTimeout(s),t(n)})});get returnTrigger(){let{execute:r,error:e,complete:t}=this;return{execute:r,error:e,complete:t}}get returnListener(){let{subscribe:r,once:e,asPromise:t}=this;return{subscribe:r,once:e,asPromise:t}}get length(){return this.event.stack.length}},Qk=class{_disposer=[];push(r){this._disposer.push(r)}dispose(){this._disposer.forEach(r=>r()),this._disposer=[]}},jR=ut("werift-ice:packages/ice/src/transport.ts"),Yy=class r9{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=(0,Zk.createSocket)(e),this.socket.on("message",(s,n)=>{Ip(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){jR("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,t={}){let s=new r9(e,t);return await s.init(),s}async init(){let e=lx(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let t=await Yk(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else this.socket.bind({address:e});await new Promise(t=>this.socket.once("listening",t))}send=async(e,t)=>{if(t&&!e9.isIP(t[0]))return new Promise((s,n)=>{this.socket.send(e,t[1],t[0],i=>{i?(jR("send error",t,e),n(i)):s()})});t=t??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,t[1],t[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},s9=class n9{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,t)=>{try{this.client=(0,t9.connect)({port:this.addr[1],host:this.addr[0]},e)}catch(s){t(s)}}),this.client.on("data",e=>{let t=[this.client.remoteAddress,this.client.remotePort];this.onData(e,t)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{console.log("error",e)}))}async init(){await this.connecting}static async init(e){let t=new n9(e);return await t.init(),t}get address(){return{}}send=async(e,t)=>{await this.connecting,this.client.write(e,s=>{s&&console.log("err",s)})};close=async()=>{this.closed=!0,this.client.destroy()}},mi={rsa_1:1,ecdsa_3:3},Rp={sha256_4:4},Jy={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},i9=Object.values(Jy),ho={x25519_29:29,secp256r1_23:23},x2=Object.values(ho),b2={named_curve_3:3},n_={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},o9=[1,64],v2=[{hash:Rp.sha256_4,signature:mi.rsa_1},{hash:Rp.sha256_4,signature:mi.ecdsa_3}],hq=()=>{let r=by.utils.randomPrivateKey(),e=by.getPublicKey(r,!1),t=Buffer.from(r),s=Buffer.from(e);return{privateKey:t,publicKey:s}},pq=({publicKey:r,privateKey:e})=>{let t=by.getSharedSecret(e,r);return Buffer.from(t).subarray(1)};lo={CLIENT:1,SERVER:2},bq=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...r){throw new Error("not implemented")}encrypt(...r){throw new Error("not implemented")}decrypt(...r){throw new Error("not implemented")}toString(){return this.name}},i_=af.webcrypto;pr.set(i_);kp=class{constructor(r,e,t,s){this.sessionType=r,this.certPem=e,this.keyPem=t,e&&t&&s&&this.parseX509(e,t,s)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(r,e)=>{let t=(()=>{switch(r.signature){case mi.rsa_1:return"RSASSA-PKCS1-v1_5";case mi.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(r.hash===Rp.sha256_4)return"SHA-256"})(),n=(()=>{switch(e){case ho.secp256r1_23:return"P-256";case ho.x25519_29:return t==="ECDSA"?"P-256":"X25519";default:{if(t==="ECDSA")return"P-256";if(t==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(t){case"ECDSA":return{name:t,hash:s,namedCurve:n};case"RSASSA-PKCS1-v1_5":return{name:t,hash:s,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await i_.subtle.generateKey(i,!0,["sign","verify"]),c=(await Vg.createSelfSigned({serialNumber:(0,af.randomBytes)(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:i,keys:o})).toString("pem"),d=Nr.encode(await i_.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:d,signatureHash:r}};encryptPacket(r){let e=r.recordLayerHeader,t=e.protocolVersion.major<<8|e.protocolVersion.minor,s=this.cipher.encrypt(this.sessionType,r.fragment,{type:e.contentType,version:t,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return r.fragment=s,r.recordLayerHeader.contentLen=s.length,r}decryptPacket(r){let e=r.recordLayerHeader,t=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,r.fragment,{type:e.contentType,version:t,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(r){return this.sessionType===lo.CLIENT?gq(this.masterSecret,r):yq(this.masterSecret,r)}signatureData(r,e){let t=(0,af.createSign)(e).update(r),s=this.localPrivateKey.toPEM().toString();return t.sign(s)}generateKeySignature(r){let e=this.sessionType===lo.CLIENT?this.localRandom:this.remoteRandom,t=this.sessionType===lo.SERVER?this.localRandom:this.remoteRandom,s=this.valueKeySignature(e.serialize(),t.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(s,r)}parseX509(r,e,t){let s=hx.Certificate.fromPEM(Buffer.from(r)),n=hx.PrivateKey.fromPEM(Buffer.from(e));this.localCert=s.raw,this.localPrivateKey=n,this.signatureHashAlgorithm=t}valueKeySignature(r,e,t,s){let n=Buffer.from((0,Ju.encode)({type:b2.named_curve_3,curve:s,len:t.length},{type:Ju.types.uint8,curve:Ju.types.uint16be,len:Ju.types.uint8}).slice());return Buffer.concat([r,e,n,t])}},Pp=class{srtpProfile;static findMatchingSRTPProfile(r,e){for(let t of e)if(r.includes(t))return t}},w2=r=>"0x"+r.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),p9=r=>Object.entries({...r}).reduce((e,[t,s])=>((typeof s=="number"||typeof s=="string")&&(e[t]=s),Buffer.isBuffer(s)&&(e[t]=w2(s)),e),{}),Zs=class ha{constructor(e,t,s,n,i,o){this.msg_type=e,this.length=t,this.message_seq=s,this.fragment_offset=n,this.fragment_length=i,this.fragment=o}static spec={msg_type:En.types.uint8,length:En.types.uint24be,message_seq:En.types.uint16be,fragment_offset:En.types.uint24be,fragment_length:En.types.uint24be,fragment:En.types.buffer(e=>e.current.fragment_length)};get summary(){return p9(this)}static createEmpty(){return new ha(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ha(...Object.values((0,En.decode)(e,ha.spec)))}serialize(){let e=(0,En.encode)(this,ha.spec).slice();return Buffer.from(e)}chunk(e){let t=0,s=this.fragment.length;if(s===0)return[new ha(this.msg_type,s,this.message_seq,t,0,this.fragment)];let n=[];for(e||(e=1240);t<s;){let i=Math.min(e,s-t),o=Buffer.from(this.fragment.slice(t,t+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");n.push(new ha(this.msg_type,s,this.message_seq,t,o.length,o)),t+=o.length}return n}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);let t=Buffer.alloc(e[0].length);for(let s of e)s.fragment.copy(t,s.fragment_offset);return new ha(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){let s=e.find(n=>n.msg_type===t);return s?e?.length?e.filter(n=>n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length):[]:[]}},{uint16be:Qy,uint24be:vq,buffer:g9,array:wq,uint8:Bp,string:Sq}=m9.types,_q={type:Qy,data:g9(Qy)},o_=wq(_q,Qy,"bytes"),Eq=g9(vq),Cq=Bp,Tq=Sq(Qy),Aq={hash:Bp,signature:Bp},S2={major:Bp,minor:Bp},Qc=class dp{constructor(e=Math.floor(Date.now()/1e3),t=(0,y9.randomBytes)(28)){this.gmt_unix_time=e,this.random_bytes=t}static spec={gmt_unix_time:Jc.types.uint32be,random_bytes:Jc.types.buffer(28)};static deSerialize(e){return new dp(...Object.values((0,Jc.decode)(e,dp.spec)))}static from(e){return new dp(...Object.values(e))}serialize(){let e=(0,Jc.encode)(this,dp.spec).slice();return Buffer.from(e)}},x9=class up{constructor(e,t,s,n,i,o,a){this.clientVersion=e,this.random=t,this.sessionId=s,this.cookie=n,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Mr.types.uint8,minor:Mr.types.uint8},random:Qc.spec,sessionId:Mr.types.buffer(Mr.types.uint8),cookie:Mr.types.buffer(Mr.types.uint8),cipherSuites:Mr.types.array(Mr.types.uint16be,Mr.types.uint16be,"bytes"),compressionMethods:Mr.types.array(Mr.types.uint8,Mr.types.uint8,"bytes"),extensions:o_};static createEmpty(){return new up(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new up(...Object.values((0,Mr.decode)(e,up.spec)))}serialize(){let e=(0,Mr.encode)(this,up.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Iq=class fp{constructor(e,t,s,n,i){this.epoch=e,this.sequenceNumber=t,this.contentType=s,this.protocolVersion=n,this.contentLen=i}static spec={epoch:uo.types.uint16be,sequenceNumber:uo.types.uint48be,contentType:uo.types.uint8,protocolVersion:S2,contentLen:uo.types.uint16be};static createEmpty(){return new fp(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new fp(...Object.values((0,uo.decode)(e,fp.spec)))}serialize(){let e=(0,uo.encode)(this,fp.spec).slice();return Buffer.from(e)}},v9=class a_{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:w2(this.fragment)}}static createEmpty(){return new a_(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let t=e.readUInt8(0),s=e.readUInt8(1),n=e.readUInt8(2),i=e.readUInt16BE(3),o=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new a_({contentType:t,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,t=13+e,s=Buffer.alloc(t);return s.writeUInt8(this.recordLayerHeader.contentType,0),s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),s.writeUInt16BE(this.recordLayerHeader.epoch,3),s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),s.writeUInt16BE(e,11),this.fragment.copy(s,13),s}computeMACHeader(){return new Iq(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},w9=r=>e=>(r.lastFlight=e,e.flatMap(t=>(t.messageSeq=r.sequenceNumber++,t.toFragment().chunk()))),Wp=r=>(e,t)=>e.map(s=>new v9({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment)),c_=(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",r))(c_||{}),Rq=ut("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),$S=ut("werift-dtls : packages/dtls/src/flight/flight.ts : err"),Gp=class d_{constructor(e,t,s,n){this.transport=e,this.dtls=t,this.flight=s,this.nextFlight=n}state="PREPARING";static RetransmitCount=10;createPacket(e){let t=w9(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),Wp(this.dtls)(t.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let t=0;for(;t<=d_.RetransmitCount;t++){if(this.setState("SENDING"),this.send(e).catch(s=>{$S("fail to send",$S)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,b9.setTimeout)(1e3*((t+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else Rq(this.dtls.sessionId,"retransmit",t,this.dtls.flight)}if(t>d_.RetransmitCount)throw $S(this.dtls.sessionId,"retransmit failed",t),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(t=>this.transport.send(t)));setState(e){this.state=e}},kq=class extends Gp{constructor(r,e,t){super(r,e,1,3),this.cipher=t}async exec(r){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new x9({major:254,minor:253},new Qc,Buffer.from([]),Buffer.from([]),i9,[0],r);this.dtls.version=e.clientVersion,this.cipher.localRandom=Qc.from(e.random);let t=this.createPacket([e]),s=Buffer.concat(t.map(n=>n.serialize()));await this.transmit([s])}},Pq=ut("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),Bq=class extends Gp{constructor(r,e){super(r,e,3,5)}async exec(r){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;Pq("dtls version",e.clientVersion),e.cookie=r.cookie,this.dtls.cookie=r.cookie;let t=this.createPacket([e]),s=Buffer.concat(t.map(n=>n.serialize()));await this.transmit([s])}},mx={NULL:0,ECDHE:1},Xp={NULL:0,RSA:1,ECDSA:2,PSK:3},Yp={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},Jp=class{id=0;name;signType;keyType;toString(){return this.name}};Uq=ut("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),jq=class extends bq{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return p9(this)}init(r,e,t){let s=xq(r,t,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=s.clientWriteKey,this.serverWriteKey=s.serverWriteKey,this.clientNonce=s.clientNonce,this.serverNonce=s.serverNonce}encrypt(r,e,t){let s=r===lo.CLIENT,n=s?this.clientNonce:this.serverNonce,i=s?this.clientWriteKey:this.serverWriteKey;if(!n||!i)throw new Error;n.writeUInt16BE(t.epoch,this.nonceImplicitLength),n.writeUIntBE(t.sequenceNumber,this.nonceImplicitLength+2,6);let o=n.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(t,e.length),c=(0,gx.createCipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let d=c.update(e),u=c.final(),f=c.getAuthTag();return Buffer.concat([o,d,u,f])}encodeAdditionalBuffer(r,e){let t=Buffer.alloc(13);return t.writeUInt16BE(r.epoch,0),t.writeUintBE(r.sequenceNumber,2,6),t.writeUInt8(r.type,8),t.writeUInt16BE(r.version,9),t.writeUInt16BE(e,11),t}decrypt(r,e,t){let s=r===lo.CLIENT,n=s?this.serverNonce:this.clientNonce,i=s?this.serverWriteKey:this.clientWriteKey;if(!n||!i)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(n,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),d=this.encodeAdditionalBuffer(t,a.length),u=(0,gx.createDecipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(d,{plaintextLength:a.length});let f=u.update(a);try{let h=u.final();return h.length>0?Buffer.concat([f,h]):f}catch(h){throw Uq("decrypt failed",h,r,w2(e),t,this.summary),h}}},mr={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},tp={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},rp={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},FR=Nq(),qR=Oq(),zR=Lq(),$R=Dq(),VR=Mq();yx=class{static type=23},xx=class $u{static type=65281;static spec={type:Zc.types.uint16be,data:Zc.types.uint8};type=$u.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new $u}static deSerialize(e){return new $u((0,Zc.decode)(e,$u.spec))}serialize(){let e=(0,Zc.encode)(this,$u.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},ef=class pa{static type=14;static spec={type:va.types.uint16be,data:va.types.buffer(va.types.uint16be)};type=pa.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,t){return new pa({profiles:e,mki:t})}static deSerialize(e){let t=new pa((0,va.decode)(e,pa.spec)),s=t.data.readUInt16BE(),n=new Array(s/2);for(let i=0;i<n.length;i++)n[i]=t.data.readUInt16BE(i*2+2);return t.profiles=n,t.mki=t.data.slice(s+2),t}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let t=Buffer.concat([e,...this.profiles.map(n=>{let i=Buffer.alloc(2);return i.writeUInt16BE(n),i}),this.mki]);this.data=t;let s=(0,va.encode)(this,pa.spec).slice();return Buffer.from(s)}static fromData(e){let t=Buffer.alloc(4);return t.writeUInt16BE(pa.type),t.writeUInt16BE(e.length,2),pa.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},Zy=class lp{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:ed.types.array(Eq,ed.types.uint24be,"bytes")};static createEmpty(){return new lp(void 0)}static deSerialize(e){return new lp(...Object.values((0,ed.decode)(e,lp.spec)))}serialize(){let e=(0,ed.encode)(this,lp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},C9=class hp{constructor(e=1){this.type=e}static spec={type:cf.types.uint8};static createEmpty(){return new hp}static deSerialize(e){return new hp(...Object.values((0,cf.decode)(e,hp.spec)))}serialize(){let e=(0,cf.encode)(this,hp.spec).slice();return Buffer.from(e)}},T9=class pp{constructor(e,t){this.algorithm=e,this.signature=t}msgType=15;messageSeq;static spec={algorithm:wa.types.uint16be,signature:wa.types.buffer(wa.types.uint16be)};static createEmpty(){return new pp(void 0,void 0)}static deSerialize(e){let t=(0,wa.decode)(e,pp.spec);return new pp(...Object.values(t))}serialize(){let e=(0,wa.encode)(this,pp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},A9=class mp{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:td.types.buffer(td.types.uint8)};static createEmpty(){return new mp(void 0)}static deSerialize(e){let t=(0,td.decode)(e,mp.spec);return new mp(...Object.values(t))}serialize(){let e=(0,td.encode)(this,mp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},u_=class f_{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new f_(void 0)}static deSerialize(e){return new f_(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},I9=class gp{constructor(e,t,s){this.certificateTypes=e,this.signatures=t,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:Cn.types.array(Cq,Cn.types.uint8,"bytes"),signatures:Cn.types.array(Aq,Cn.types.uint16be,"bytes"),authorities:Cn.types.array(Tq,Cn.types.uint16be,"bytes")};static createEmpty(){return new gp(void 0,void 0,void 0)}static deSerialize(e){return new gp(...Object.values((0,Cn.decode)(e,gp.spec)))}serialize(){let e=(0,Cn.encode)(this,gp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},R9=class ma{constructor(e,t,s,n,i,o){this.serverVersion=e,this.random=t,this.sessionId=s,this.cipherSuite=n,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:S2,random:Qc.spec,sessionId:Tn.types.buffer(Tn.types.uint8),cipherSuite:Tn.types.uint16be,compressionMethod:Tn.types.uint8};static createEmpty(){return new ma(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let t=(0,Tn.decode)(e,ma.spec),s=new ma(...Object.values(t));return s.serialize().length<e.length?new ma(...Object.values((0,Tn.decode)(e,{...ma.spec,extensions:o_}))):s}serialize(){let e=this.extensions===void 0?(0,Tn.encode)(this,ma.spec).slice():(0,Tn.encode)(this,{...ma.spec,extensions:o_}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},k9=class yp{msgType=14;messageSeq;static spec={};static createEmpty(){return new yp}static deSerialize(e){return new yp(...Object.values((0,bx.decode)(e,yp.spec)))}serialize(){let e=(0,bx.encode)(this,yp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}};B9=class xp{constructor(e,t,s,n,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=t,this.publicKeyLength=s,this.publicKey=n,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:_n.types.uint8,namedCurve:_n.types.uint16be,publicKeyLength:_n.types.uint8,publicKey:_n.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:_n.types.uint8,signatureAlgorithm:_n.types.uint8,signatureLength:_n.types.uint16be,signature:_n.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new xp(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let t=(0,_n.decode)(e,xp.spec);return new xp(...Object.values(t))}serialize(){return Hq(this,xp.spec)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},df=1,ad=7,Fq=[df,ad],N9=r=>{switch(r){case df:case ad:return 16}},O9=r=>{switch(r){case df:return 14;case ad:return 12}},qq=ut("werift-rtp : packages/rtp/src/codec/av1.ts"),l_=class D9{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let t=new D9,s=0;if(t.zBit_RtpStartsWithFragment=xe(e[s],0),t.yBit_RtpEndsWithFragment=xe(e[s],1),t.w_RtpNumObus=xe(e[s],2,2),t.nBit_RtpStartsNewCodedVideoSequence=xe(e[s],4),s++,t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment)throw new Error;[...Array(t.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=j9(e.subarray(s)),c=s+a,d=c+o,u=!1;t.zBit_RtpStartsWithFragment&&i===0&&(u=!0),t.obu_or_fragment.push({data:e.subarray(c,d),isFragment:u}),s+=a+o});let n=!1;return(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment)&&(n=!0),t.obu_or_fragment.push({data:e.subarray(s),isFragment:n}),t};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let t=[],s=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,d)=>(a[d]=c,a),{}),n=Object.keys(s).length;for(let a of Object.keys(s).map(Number)){let c=s[a];if(!c)continue;let{data:d,isFragment:u}=c;if(u){let f=[];for(let h=a;h<n;h++){let y=s[h];if(y.isFragment)f.push(y.data),delete s[h];else break}f.length<=1&&(qq("fragment lost, maybe packet lost"),f=[]),t.push(Buffer.concat(f))}else t.push(d)}let i=t.map(a=>M9.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},M9=class U9{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let t=new U9,s=0;return t.obu_forbidden_bit=xe(e[s],0),t.obu_type=H9[xe(e[s],1,4)],t.obu_extension_flag=xe(e[s],5),t.obu_has_size_field=xe(e[s],6),t.obu_reserved_1bit=xe(e[s],7),s++,t.payload=e.subarray(s),t}serialize(){let e=new ux(8).set(this.obu_forbidden_bit).set(zq[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,t=Buffer.alloc(0);return this.obu_has_size_field&&(t=L9.LEB128.encode(this.payload.length)),Buffer.concat([e,t,this.payload])}};H9={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"},zq=Object.entries(H9).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),F9=class q9{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,t){let s=new q9,n=0,i=e[n];if(s.f=xe(i,0),s.nri=xe(i,1,2),s.nalUnitType=xe(i,3,5),n++,s.s=xe(e[n],0),s.e=xe(e[n],1),s.r=xe(e[n],2),s.nalUnitPayloadType=xe(e[n],3,5),n++,0<s.nalUnitType&&s.nalUnitType<ga.stap_a)s.payload=this.packaging(e);else if(s.nalUnitType===ga.stap_a){let o=Vq,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=Kq,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}s.payload=a}else if(s.nalUnitType===ga.fu_a){t||(t=Buffer.alloc(0));let o=e.subarray(n);if(s.fragment=Buffer.concat([t,o]),s.e){let a=new ba(Buffer.alloc(1)).writeBits(1,0).writeBits(2,s.nri).writeBits(5,s.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,s.fragment]);s.fragment=void 0,s.payload=this.packaging(c)}}return s}static packaging(e){return Buffer.concat([$q,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===ga.idrSlice||this.nalUnitPayloadType===ga.idrSlice}get isPartitionHead(){return this.nalUnitType===ga.fu_a||this.nalUnitType===ga.fu_b?this.s!==0:!0}},ga={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},$q=Buffer.from([0,0,0,1]),Vq=1,Kq=2,z9=class $9{payload;static deSerialize(e){let t=new $9;return t.payload=e,t}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),er([1,1],[1,2]),Fk([2,4,2,1],[312,e,0,0])])}},V9=class K9{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let t=new K9,s=0;if(t.xBit=xe(e[s],0),t.nBit=xe(e[s],2),t.sBit=xe(e[s],3),t.pid=xe(e[s],5,3),s++,t.xBit&&(t.iBit=xe(e[s],0),t.lBit=xe(e[s],1),t.tBit=xe(e[s],2),t.kBit=xe(e[s],3),s++),t.iBit)if(t.mBit=xe(e[s],0),t.mBit){let n=Ap(xe(e[s],1,7)),i=Ap(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=xe(e[s],1,7),s++;return t.lBit&&s++,(t.lBit||t.kBit)&&(t.tBit,t.kBit,s++),t.payload=e.subarray(s),t.payloadHeaderExist&&(t.size0=xe(e[s],0,3),t.hBit=xe(e[s],3),t.ver=xe(e[s],4,3),t.pBit=xe(e[s],7),s++,t.size1=e[s],s++,t.size2=e[s]),t}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},W9=class G9{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:t,offset:s}=this.parseRtpPayload(e);return t.payload=e.subarray(s),t}static parseRtpPayload(e){let t=new G9,s=0;if(t.iBit=xe(e[s],0),t.pBit=xe(e[s],1),t.lBit=xe(e[s],2),t.fBit=xe(e[s],3),t.bBit=xe(e[s],4),t.eBit=xe(e[s],5),t.vBit=xe(e[s],6),t.zBit=xe(e[s],7),s++,t.iBit)if(t.m=xe(e[s],0),t.m){let n=Ap(xe(e[s],1,7)),i=Ap(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=xe(e[s],1,7),s++;if(t.lBit&&(t.tid=xe(e[s],0,3),t.u=xe(e[s],3),t.sid=xe(e[s],4,3),t.d=xe(e[s],7),s++,t.fBit===0&&(t.tl0PicIdx=e[s],s++)),t.fBit&&t.pBit)for(;;){t.pDiff=[...t.pDiff,xe(e[s],0,7)];let n=xe(e[s],7);if(s++,n===0)break}return t.vBit&&(t.n_s=xe(e[s],0,3),t.y=xe(e[s],3),t.g=xe(e[s],4),s++,t.y&&[...Array(t.n_s+1)].forEach(()=>{t.width.push(e.readUInt16BE(s)),s+=2,t.height.push(e.readUInt16BE(s)),s+=2}),t.g&&(t.n_g=e[s],s++),t.n_g>0&&[...Array(t.n_g).keys()].forEach(n=>{t.pgT.push(xe(e[s],0,3)),t.pgU.push(xe(e[s],3));let i=xe(e[s],4,2);s++,t.pgP_Diff[n]=[],i>0&&[...Array(i)].forEach(()=>{t.pgP_Diff[n].push(e[s]),s++})})),{offset:s,p:t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},Wq=class{payload;fragment;static deSerialize(r,e){return{}}static isDetectedFinalPacketInSequence(r){return!0}get isKeyframe(){return!0}};Xq=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];Jq={setTimeout:(...r)=>{let e=setTimeout(...r);return()=>clearTimeout(e)},setInterval:(...r)=>{let e=setInterval(()=>{r[0]()},...r.slice(1));return()=>clearInterval(e)}};ex=4,go=class p_{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,t,s,n){let o=new p_({type:e,count:t,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new Tp(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),er([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[t,s,n]=is(e,[1,1,2]),i=xe(t,0,2),o=xe(t,2,1)>0,a=xe(t,3,5);return new p_({version:i,padding:o,count:a,type:s,length:n})}},KR=class m_{static count=4;count=m_.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[t,s]=is(e,[4,4]),n=[];for(let i=8;i<e.length;i+=8)n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]});return new m_({senderSsrc:t,mediaSsrc:s,fir:n})}serialize(){let e=er([4,4],[this.senderSsrc,this.mediaSsrc]),t=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{t.writeUInt32BE(s,i*8),t[i*8+4]=n}),Buffer.concat([e,t])}},Op=class g_{static count=1;count=g_.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[t,s]=is(e,[4,4]);return new g_({senderSsrc:t,mediaSsrc:s})}serialize(){return er([4,4],[this.senderSsrc,this.mediaSsrc])}},Lp=class y_{static count=15;length;count=y_.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[t,s,n,i,o]=is(e,[4,4,4,1,1]),a=xe(o,0,6),c=(xe(o,6,2)<<16)+(e[14]<<8)+e[15],d=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),u=[];for(let f=16;f<e.length;f+=4){let h=e.slice(f).readUIntBE(0,4);u.push(h)}return new y_({senderSsrc:t,mediaSsrc:s,uniqueID:er([4],[n]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:u,bitrate:d})}serialize(){let e=Buffer.concat([er([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),er([1],[this.ssrcNum])]),t=new Tp(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let s=Buffer.concat(this.ssrcFeedbacks.map(i=>er([4],[i]))),n=Buffer.concat([e,er([3],[t.value]),s]);return this.length=n.length/4,n}},Qq=ut("werift-rtp: /rtcp/psfb/index"),tf=class x_{static type=206;type=x_.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return go.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case KR.count:s=KR.deSerialize(e);break;case Op.count:s=Op.deSerialize(e);break;case Lp.count:s=Lp.deSerialize(e);break;default:Qq("unknown psfb packet",t.count);break}return new x_({feedback:s})}},rf=class ky{ssrc=0;reports=[];static type=201;type=ky.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=er([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]),go.serialize(ky.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){let[s]=is(e,[4]),n=4,i=[];for(let o=0;o<t;o++)i.push(vx.deSerialize(e.slice(n,n+24))),n+=24;return new ky({ssrc:s,reports:i})}},vx=class Y9{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return er([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[t,s,n,i,o,a,c]=is(e,[4,1,3,4,4,4,4]);return new Y9({ssrc:t,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},J9=205,Dp=class b_{static count=1;count=b_.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new go({type:J9,count:this.count,version:2}))}static deSerialize(e,t){let[s,n]=is(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=is(e.subarray(o),[2,2]);i.push(a);for(let d=0;d<16;d++)c>>d&1&&i.push(a+d+1)}return new b_({header:t,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){let e=er([4,4],[this.senderSsrc,this.mediaSourceSsrc]),t=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{let a=o-n-1;a>=0&&a<16?i|=1<<a:(t.push(er([2,2],[n,i])),n=o,i=0)}),t.push(er([2,2],[n,i]))}let s=Buffer.concat([e,Buffer.concat(t)]);return this.header.length=s.length/4,Buffer.concat([this.header.serialize(),s])}},Zq=ut("werift/rtp/rtcp/rtpfb/twcc"),Mp=class v_{static count=15;count=v_.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new go({type:205,count:this.count,version:2}))}static deSerialize(e,t){let[s,n,i,o,a,c]=is(e,[4,4,2,2,3,1]),d=[],u=[],f=16;for(let y=0;y<o;){let v=xe(e.slice(f,f+1)[0],0,1),S;switch(v){case 0:{let C=Qu.deSerialize(e.slice(f,f+2));S=C;let O=Math.min(o-y,C.runLength);if(C.packetStatus===1||C.packetStatus===2)for(let K=0;K<O;K++)u.push(new _p({type:C.packetStatus}));y+=O}break;case 1:{let C=Z9.deSerialize(e.slice(f,f+2));S=C,C.symbolSize===0&&C.symbolList.forEach(O=>{O===1&&u.push(new _p({type:1}))}),C.symbolSize===1&&C.symbolList.forEach(O=>{(O===1||O===2)&&u.push(new _p({type:O}))}),y+=C.symbolList.length}break}if(!S)throw new Error;f+=2,d.push(S)}let h=f;return u.forEach(y=>{y.type===1&&(y.deSerialize(e.slice(h,h+1)),h++),y.type===2&&(y.deSerialize(e.slice(h,h+2)),h+=2)}),new v_({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:u,packetChunks:d,header:t})}serialize(){let e=er([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),t=Buffer.concat(this.packetChunks.map(i=>i.serialize())),s=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){Zq(o?.message);return}}).filter(i=>i)),n=Buffer.concat([e,t,s]);if(this.header.padding&&n.length%4!==0){let i=4-n.length%4,o=Buffer.alloc(i);return o[o.length-1]=o.length,this.header.length=Math.floor((n.length+o.length)/4),Buffer.concat([this.header.serialize(),n,o])}return this.header.length=Math.floor(n.length/4),Buffer.concat([this.header.serialize(),n])}get packetResults(){let e=this.baseSequenceNumber-1,t=this.packetChunks.filter(o=>o instanceof Qu).flatMap(o=>o.results(e)),s=0,i=BigInt(this.referenceTime)*64n;for(let o of t){let a=this.recvDeltas[s];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),s++)}return t}},Qu=class Q9{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let t=xe(e[0],1,2),s=(xe(e[0],3,5)<<8)+e[1];return new Q9({type:0,packetStatus:t,runLength:s})}serialize(){return new ux(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let t=this.packetStatus===1||this.packetStatus===2,s=[];for(let n=0;n<=this.runLength;++n)s.push(new sP({sequenceNumber:++e,received:t}));return s}},Z9=class eP{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=xe(e[0],1,1),n=[];function i(o,a){for(let c=0;c<o;c++)a(c)}switch(s){case 0:i(6,o=>n.push(xe(e[0],2+o,1))),i(8,o=>n.push(xe(e[1],o,1)));break;case 1:i(3,o=>n.push(xe(e[0],2+o*2,2))),i(4,o=>n.push(xe(e[1],o*2,2)));break;default:s=(xe(e[0],2,6)<<8)+e[1]}return new eP({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),t=new ux(16).set(1).set(this.symbolSize),s=this.symbolSize===0?1:2;return this.symbolList.forEach(n=>{t.set(n,s)}),e.writeUInt16BE(t.value),e}},_p=class w_{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let t,s;if(e.length===1?(t=1,s=250*e[0]):e.length===2&&(t=2,s=250*e.readInt16BE()),t===void 0||s===void 0)throw new Error;return new w_({type:t,delta:s})}deSerialize(e){let t=w_.deSerialize(e);this.delta=t.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},tP=(r=>(r[r.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",r[r.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",r[r.packetStatusChunkLength=2]="packetStatusChunkLength",r))(tP||{}),rP=(r=>(r[r.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",r[r.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",r[r.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",r[r.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",r))(rP||{}),sP=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(r){Object.assign(this,r)}},ez=ut("werift-rtp:packages/rtp/rtcp/rtpfb/index"),rd=class S_{static type=J9;type=S_.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,t){let s;switch(t.count){case Dp.count:s=Dp.deSerialize(e,t);break;case Mp.count:s=Mp.deSerialize(e,t);break;default:ez("unknown rtpfb packet",t.count);break}return new S_({feedback:s,header:t})}},Up=class __{static type=202;type=__.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(t=>e+=t.length),e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return go.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){let s=[];for(let n=0;n<e.length;){let i=_2.deSerialize(e.slice(n));s.push(i),n+=i.length}return new __({chunks:s})}},_2=class nP{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(t=>e+=t.length),e+=1,e+=WR(e),e}serialize(){let e=Buffer.concat([er([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);return Buffer.concat([e,Buffer.alloc(WR(e.length))])}static deSerialize(e){let t=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=E2.deSerialize(e.slice(n));s.push(o),n+=o.length}return new nP({source:t,items:s})}},E2=class iP{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){let e=Buffer.from(this.text);return Buffer.concat([er([1,1],[this.type,e.length]),e])}static deSerialize(e){let t=e[0],s=e[1],n=e.slice(2,2+s).toString();return new iP({type:t,text:n})}};sd=class Py{ssrc=0;senderInfo;reports=[];static type=200;type=Py.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]),go.serialize(Py.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){let s=e.readUInt32BE(),n=C2.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<t;c++)o.push(vx.deSerialize(e.subarray(i,i+24))),i+=24;return new Py({ssrc:s,senderInfo:n,reports:o})}},C2=class oP{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:aP(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return er([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[t,s,n,i]=is(e,[8,4,4,4]);return new oP({ntpTimestamp:t,rtpTimestamp:s,packetCount:n,octetCount:i})}},aP=r=>{let[e,t]=is(er([8],[r]),[4,4]);return+`${e}.${t}`},tz=ut("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),cP=class{static deSerialize(r){let e=0,t=[];for(;e<r.length;){let s=go.deSerialize(r.subarray(e,e+ex));e+=ex;let n=r.subarray(e);e+=s.length*4,s.padding&&(n=n.subarray(0,n.length-n.subarray(-1)[0]));try{switch(s.type){case sd.type:t.push(sd.deSerialize(n,s.count));break;case rf.type:t.push(rf.deSerialize(n,s.count));break;case Up.type:t.push(Up.deSerialize(n,s));break;case rd.type:t.push(rd.deSerialize(n,s));break;case tf.type:t.push(tf.deSerialize(n,s));break;default:break}}catch(i){tz("deSerialize RTCP",i)}}return t}};Yt={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"};sz=ut("packages/rtp/src/rtp/red/packet.ts"),T2=class wP{header;blocks=[];static deSerialize(e){let t=e instanceof ArrayBuffer?Buffer.from(e):e,s=new wP,n=0;return[s.header,n]=E_.deSerialize(t),s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=t.subarray(n,n+i);s.blocks.push({block:c,blockPT:a,timestampOffset:o}),n+=i}else{let c=t.subarray(n);s.blocks.push({block:c,blockPT:a})}}),s}serialize(){this.header=new E_;for(let{timestampOffset:t,blockPT:s,block:n}of this.blocks)t?this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:t}):this.header.fields.push({fBit:0,blockPT:s});let e=this.header.serialize();for(let{block:t}of this.blocks)e=Buffer.concat([e,t]);return e}},E_=class SP{fields=[];static deSerialize(e){let t=0,s=new SP;for(;;){let n={};s.fields.push(n);let i=new ba(e.subarray(t));if(n.fBit=i.readBits(1),n.blockPT=i.readBits(7),t++,n.fBit===0)break;n.timestampOffset=i.readBits(14),n.blockLength=i.readBits(10),t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(let t of this.fields)try{if(t.timestampOffset&&t.blockLength){let s=new ba(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{let s=new ba(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){sz(s?.message)}return e}},_P=class{constructor(r=1){this.distance=r}cache=[];cacheSize=10;push(r){this.cache.push(r),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let r=new T2,e=this.cache.slice(-(this.distance+1)),t=e.pop();return t&&(e.forEach(s=>{let n=Yc(t.timestamp,-s.timestamp);n>nz||r.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),r.blocks.push({block:t.block,blockPT:t.blockPT})),r}},nz=16383,EP=class{size=150;sequenceNumbers=[];push(r,e){let t=[];return r.blocks.forEach(({blockPT:n,timestampOffset:i,block:o},a)=>{let c=Ur(e.header.sequenceNumber,-(r.blocks.length-(a+1)));i?t.push(new mo(new po({timestamp:Yc(e.header.timestamp,-i),payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):t.push(new mo(new po({timestamp:e.header.timestamp,payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),t.filter(n=>this.sequenceNumbers.includes(n.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(n.header.sequenceNumber),!0))}},ya={OneByte:48862,TwoByte:4096},GR=2,XR=4,YR=8,JR=12,QR=4,po=class CP{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=ya.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let t=new CP,s=0,n=e[s++];t.version=xe(n,0,2),t.padding=xe(n,2)>0,t.extension=xe(n,3)>0,t.csrcLength=xe(n,4,4),t.csrc=[...Array(t.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=JR-1;let i=e[1];t.marker=xe(i,0)>0,t.payloadType=xe(i,1,7),t.sequenceNumber=e.readUInt16BE(GR),t.timestamp=e.readUInt32BE(XR),t.ssrc=e.readUInt32BE(YR);for(let o=0;o<t.csrc.length;o++){let a=JR+o*QR;t.csrc[o]=e.subarray(a).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE(),s+=2;let o=e.subarray(s).readUInt16BE()*4;switch(t.extensionLength=o,s+=2,t.extensionProfile){case ya.OneByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s]>>4,d=(e[s]&(e[s]^240))+1;if(s++,c===15)break;let u={id:c,payload:e.subarray(s,s+d)};t.extensions=[...t.extensions,u],s+=d}}break;case ya.TwoByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s];s++;let d=e[s];s++;let u={id:c,payload:e.subarray(s,s+d)};t.extensions=[...t.extensions,u],s+=d}}break;default:{let a={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,a],s+=t.extensions[0].payload.length}break}}return t.payloadOffset=s,t.padding&&(t.paddingSize=e[e.length-1]),t}get serializeSize(){let{csrc:e,extensionProfile:t,extensions:s}=this,n=12+e.length*QR;if(s.length>0||this.extension===!0){let i=4;switch(t){case ya.OneByte:for(let o of s)i+=1+o.payload.length;break;case ya.TwoByte:for(let o of s)i+=2+o.payload.length;break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){let t=Buffer.alloc(e),s=0,n=new Tp(8);n.set(2,0,this.version),this.padding&&n.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&n.set(1,3,1),n.set(4,4,this.csrc.length),t.writeUInt8(n.value,s++);let i=new Tp(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,s++),t.writeUInt16BE(this.sequenceNumber,GR),s+=2,t.writeUInt32BE(this.timestamp,XR),s+=4,t.writeUInt32BE(this.ssrc,YR),s+=4;for(let o of this.csrc)t.writeUInt32BE(o,s),s+=4;if(this.extension){let o=s;t.writeUInt16BE(this.extensionProfile,s),s+=4;let a=s;switch(this.extensionProfile){case ya.OneByte:for(let u of this.extensions)t.writeUInt8(u.id<<4|u.payload.length-1,s++),u.payload.copy(t,s),s+=u.payload.length;break;case ya.TwoByte:for(let u of this.extensions)t.writeUInt8(u.id,s++),t.writeUInt8(u.payload.length,s++),u.payload.copy(t,s),s+=u.payload.length;break;default:{let u=this.extensions[0].payload.length;if(u%4!=0)throw new Error;this.extensions[0].payload.copy(t,s),s+=u}}let c=s-a,d=Math.trunc((c+3)/4)*4;t.writeUInt16BE(Math.trunc(d/4),o+2);for(let u=0;u<d-c;u++)t.writeUInt8(0,s),s++}return this.payloadOffset=s,t}},mo=class C_{constructor(e,t){this.header=e,this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new C_(new po({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:t}=this.header;if(this.payload.copy(e,t),this.header.padding){let s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,s])}return e}static deSerialize(e){let t=po.deSerialize(e);return new C_(t,e.subarray(t.payloadOffset,e.length-t.paddingSize))}clear(){this.payload=null}};IP=class{constructor(r,e,t,s){this.srtpSessionKey=r,this.srtpSessionSalt=e,this.srtcpSessionKey=t,this.srtcpSessionSalt=s}encryptRtp(r,e,t){return Buffer.from([])}decryptRtp(r,e,t){return[]}encryptRTCP(r,e){return Buffer.from([])}decryptRTCP(r){return[]}},nd=class extends Error{constructor(r){super(r),this.name="SrtpAuthenticationError"}},ZR=12,iz=8;oz=class extends IP{constructor(r,e,t,s,n,i){super(r,e,t,s),this.srtpSessionAuthTag=n,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(r,e,t){let s=r.serialize(r.serializeSize),n=this.generateCounter(r.sequenceNumber,t,r.ssrc,this.srtpSessionSalt),o=(0,An.createCipheriv)("aes-128-ctr",this.srtpSessionKey,n).update(e),a=this.generateSrtpAuthTag(t,s,o);return Buffer.concat([s,o,a])}decryptRtp(r,e,t=I2(r,this.authTagLength)){let s=r.length-this.authTagLength,n=r.subarray(0,s),i=r.subarray(s),o=this.generateSrtpAuthTag(e,n.subarray(0,t.payloadOffset),n.subarray(t.payloadOffset));tk(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(t.sequenceNumber,e,t.ssrc,this.srtpSessionSalt),c=(0,An.createDecipheriv)("aes-128-ctr",this.srtpSessionKey,a),d=n.subarray(t.payloadOffset),u=c.update(d),f=Buffer.concat([n.subarray(0,t.payloadOffset),u]);return[f,PP(t,f,"Failed to authenticate SRTP packet")]}encryptRTCP(r,e){let t=Buffer.from(r),s=t.readUInt32BE(4),n=this.generateCounter(e&65535,e>>16,s,this.srtcpSessionSalt);(0,An.createCipheriv)("aes-128-ctr",this.srtcpSessionKey,n).update(t.slice(8)).copy(t,8),t=Buffer.concat([t,Buffer.alloc(4)]),t.writeUInt32BE(e,t.length-4),t[t.length-4]|=128;let a=this.generateSrtcpAuthTag(t);return t=Buffer.concat([t,a]),t}decryptRTCP(r){let e=RP(r,this.authTagLength,ek),t=r.length-(this.authTagLength+ek),s=r.subarray(0,r.length-this.authTagLength),n=r.subarray(r.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);tk(n,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(r).slice(0,t);if(r[t]>>>7===0)return[o,e];let c=r.readUInt32BE(t);c&=~(1<<31);let d=r.readUInt32BE(4),u=this.generateCounter(c&65535,c>>16,d,this.srtcpSessionSalt);return(0,An.createDecipheriv)("aes-128-ctr",this.srtcpSessionKey,u).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(r){return(0,An.createHmac)("sha1",this.srtcpSessionAuthTag).update(r).digest().slice(0,10)}generateCounter(r,e,t,s){let n=Buffer.alloc(16);n.writeUInt32BE(t,4),n.writeUInt32BE(e,8),n.writeUInt32BE(Number(BigInt(r)<<16n),12);for(let i=0;i<s.length;i++)n[i]^=s[i];return n}generateSrtpAuthTag(r,...e){let t=(0,An.createHmac)("sha1",this.srtpSessionAuthTag),s=Buffer.alloc(4);s.writeUInt32BE(r);for(let n of e)t.update(n);return t.update(s).digest().subarray(0,10)}},ek=4;az=class extends IP{aeadAuthTagLen=16;rtpIvWriter=Sp([2,4,4,2],!0);rtcpIvWriter=Sp([2,4,2,4],!0);aadWriter=Sp([4],!0);constructor(r,e,t,s){super(r,e,t,s)}encryptRtp(r,e,t){let s=r.serialize(r.serializeSize),n=this.rtpInitializationVector(r,t),i=(0,sf.createCipheriv)("aes-128-gcm",this.srtpSessionKey,n);i.setAAD(s);let o=i.update(e);i.final();let a=i.getAuthTag();return Buffer.concat([s,o,a])}decryptRtp(r,e,t=I2(r,this.aeadAuthTagLen)){let s=r.subarray(0,t.payloadOffset),n=r.length-this.aeadAuthTagLen,i=r.subarray(n),o=Buffer.from([]);o=h_(o,r.length-this.aeadAuthTagLen),s.copy(o);let a=this.rtpInitializationVector(t,e),c=r.slice(t.payloadOffset,n),d=(0,sf.createDecipheriv)("aes-128-gcm",this.srtpSessionKey,a);d.setAAD(s),d.setAuthTag(i);let u=d.update(c);return sk(d,"SRTP"),u.copy(o,t.payloadOffset),[o,PP(t,o,"Failed to authenticate SRTP packet")]}encryptRTCP(r,e){let t=r.readUInt32BE(4),s=r.length+this.aeadAuthTagLen,n=Buffer.from([]);n=h_(n,s+VS),r.slice(0,8).copy(n);let i=this.rtcpInitializationVector(t,e),o=this.rtcpAdditionalAuthenticatedData(r,e),a=(0,sf.createCipheriv)("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(r.slice(8));return a.final(),c.copy(n,8),a.getAuthTag().copy(n,8+c.length),o.slice(8,12).copy(n,s),n}decryptRTCP(r){let e=RP(r,this.aeadAuthTagLen,VS),t=r.length-VS,s=t-this.aeadAuthTagLen,n=r.readUInt32BE(4),i=r.readUInt32BE(t),o=i>>>31===1,a=i&~(rk<<24),c=this.rtcpInitializationVector(n,a),d=o?Buffer.concat([r.subarray(0,8),r.subarray(t)]):Buffer.concat([r.subarray(0,s),r.subarray(t)]),u=o?r.slice(8,s):Buffer.alloc(0),f=o?Buffer.alloc(s):Buffer.from(r.subarray(0,s));o&&r.slice(0,8).copy(f);let h=(0,sf.createDecipheriv)("aes-128-gcm",this.srtcpSessionKey,c);h.setAAD(d),h.setAuthTag(r.subarray(s,t));let y=h.update(u);return sk(h,"SRTCP"),o&&y.copy(f,8),[f,e]}rtpInitializationVector(r,e){let t=this.rtpIvWriter([0,r.ssrc,e,r.sequenceNumber]);for(let s=0;s<t.length;s++)t[s]^=this.srtpSessionSalt[s];return t}rtcpInitializationVector(r,e){let t=this.rtcpIvWriter([0,r,0,e]);for(let s=0;s<t.length;s++)t[s]^=this.srtcpSessionSalt[s];return t}rtcpAdditionalAuthenticatedData(r,e){let t=Buffer.concat([r.subarray(0,8),this.aadWriter([e])]);return t[8]|=rk,t}},VS=4,rk=128;BP=class{constructor(r,e,t){this.masterKey=r,this.masterSalt=e,this.profile=t;{let s=14-e.length;s>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(s)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=(0,By.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,By.createHmac)("sha1",this.srtcpSessionAuthTag),t){case df:this.cipher=new oz(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case ad:this.cipher=new az(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let n=t.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^t[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Ny.default.AES(this.masterKey);return Buffer.from(s.encrypt(e))}generateSessionSalt(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let n=t.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^t[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Ny.default.AES(this.masterKey);return e=Buffer.from(s.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let o=t.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^t[o];let s=Buffer.concat([e,Buffer.from([0,0])]),n=Buffer.concat([e,Buffer.from([0,1])]),i=new Ny.default.AES(this.masterKey);return s=Buffer.from(i.encrypt(s)),n=Buffer.from(i.encrypt(n)),Buffer.concat([s,n.subarray(0,4)])}getSrtpSsrcState(r){let e=this.srtpSSRCStates[r];return e||(e={ssrc:r,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[r]=e,e)}getSrtcpSsrcState(r){let e=this.srtcpSSRCStates[r];return e||(e={srtcpIndex:0,ssrc:r},this.srtcpSSRCStates[r]=e,e)}updateRolloverCount(r,e){e.rolloverHasProcessed?r===0?e.lastSequenceNumber>sp&&e.rolloverCounter++:e.lastSequenceNumber<sp&&r>nk-sp?e.rolloverCounter>0&&e.rolloverCounter--:r<sp&&e.lastSequenceNumber>nk-sp&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=r}generateSrtpAuthTag(r,e){this.srtpSessionAuth=(0,By.createHmac)("sha1",this.srtpSessionAuthTag);let t=Buffer.alloc(4);return t.writeUInt32BE(e),this.srtpSessionAuth.update(r).update(t).digest().slice(0,10)}index(r){let e=this.srtcpSSRCStates[r];return e?e.srtcpIndex:0}setIndex(r,e){let t=this.getSrtcpSsrcState(r);t.srtcpIndex=e%2147483647}},sp=100,nk=65535,cz=class extends BP{constructor(r,e,t){super(r,e,t)}encryptRTCP(r){let e=r.readUInt32BE(4),t=this.getSrtcpSsrcState(e);return t.srtcpIndex++,t.srtcpIndex>>dz&&(t.srtcpIndex=0),this.cipher.encryptRTCP(r,t.srtcpIndex)}decryptRTCP(r){return this.cipher.decryptRTCP(r)}},dz=2147483647,NP=class{constructor(r){this.ContextCls=r}localContext;remoteContext;onData;start(r,e,t,s,n){this.localContext=new this.ContextCls(r,e,n),this.remoteContext=new this.ContextCls(t,s,n)}},OP=class extends NP{constructor(r){super(cz),this.config=r,this.start(r.keys.localMasterKey,r.keys.localMasterSalt,r.keys.remoteMasterKey,r.keys.remoteMasterSalt,r.profile)}decrypt=r=>{let[e]=this.remoteContext.decryptRTCP(r);return e};encrypt(r){return this.localContext.encryptRTCP(r)}},uz=class extends BP{constructor(r,e,t){super(r,e,t)}encryptRtp(r,e){let t=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,t),this.cipher.encryptRtp(e,r,t.rolloverCounter)}decryptRtp(r){let e=I2(r,this.rtpAuthTagLength),t=this.srtpSSRCStates[e.ssrc],s=t?{...t}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,s);let n=this.cipher.decryptRtp(r,s.rolloverCounter,e);return t?Object.assign(t,s):this.srtpSSRCStates[e.ssrc]=s,n}get rtpAuthTagLength(){return this.profile===ad?16:10}},LP=class extends NP{constructor(r){super(uz),this.config=r,this.start(r.keys.localMasterKey,r.keys.localMasterSalt,r.keys.remoteMasterKey,r.keys.remoteMasterSalt,r.profile)}decrypt=r=>{let[e]=this.remoteContext.decryptRtp(r);return e};encrypt(r,e){return this.localContext.encryptRtp(r,e)}},fz=class{constructor(r){this.props=r}sequenceNumber=p2();timestamp=Xy();create(r){this.sequenceNumber=Ur(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=Yc(this.timestamp,e);let t=new po({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new mo(t,r)}},ns=ut("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),lz=class extends Gp{constructor(r,e,t,s){super(r,e,5,7),this.cipher=t,this.srtp=s}handleHandshake(r){this.dtls.bufferHandshakeCache([r],!1,4);let e=(()=>{switch(r.msg_type){case 2:return R9.deSerialize(r.fragment);case 11:return Zy.deSerialize(r.fragment);case 12:return B9.deSerialize(r.fragment);case 13:return I9.deSerialize(r.fragment);case 14:return k9.deSerialize(r.fragment)}})();e&&uf[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){ns(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let r=this.dtls.requestedCertificateTypes.length>0;ns(this.dtls.sessionId,"send flight5",r);let e=[r&&this.sendCertificate(),this.sendClientKeyExchange(),r&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(t=>t);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let r=new Zy([Buffer.from(this.cipher.localCert)]),e=this.createPacket([r]);return Buffer.concat(e.map(s=>s.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let r=new A9(this.cipher.localKeyPair.publicKey),e=this.createPacket([r]),t=Buffer.concat(e.map(a=>a.serialize())),s=this.cipher.localKeyPair,n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error("not exist");let i=d9(n.publicKey,s.privateKey,s.curve);ns(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?f9(i,o):u9(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=S9(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),ns(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),t}sendCertificateVerify(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(r,"sha256"),t=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case mi.ecdsa_3:return n_.ecdsa_secp256r1_sha256;case mi.rsa_1:return n_.rsa_pkcs1_sha256}})();if(!t)throw new Error;ns(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,t);let s=new T9(t,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let r=C9.createEmpty().serialize(),e=Wp(this.dtls)([{type:20,fragment:r}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(r),t=new u_(e);this.dtls.epoch=1;let[s]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;let n=this.cipher.encryptPacket(s).serialize();return ns(this.dtls.sessionId,"finished",this.cipher.cipher.summary),n}},uf={};uf[2]=({cipher:r,srtp:e,dtls:t})=>s=>{ns(t.sessionId,"serverHello",s.cipherSuite),r.remoteRandom=Qc.from(s.random),r.cipherSuite=s.cipherSuite,ns(t.sessionId,"selected cipherSuite",r.cipherSuite),s.extensions&&s.extensions.forEach(n=>{switch(n.type){case ef.type:{let i=ef.fromData(n.data),o=Pp.findMatchingSRTPProfile(i.profiles,t.options.srtpProfiles||[]);if(ns(t.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case yx.type:t.remoteExtendedMasterSecret=!0;break;case xx.type:ns(t.sessionId,"RenegotiationIndication");break}})};uf[11]=({cipher:r,dtls:e})=>t=>{ns(e.sessionId,"handshake certificate",t),r.remoteCertificate=t.certificateList[0]};uf[12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;ns(e.sessionId,"ServerKeyExchange",t),ns(e.sessionId,"selected curve",t.namedCurve),r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey},r.localKeyPair=E9(t.namedCurve)};uf[13]=({dtls:r})=>e=>{ns(r.sessionId,"certificate_request",e),r.requestedCertificateTypes=e.certificateTypes,r.requestedSignatureAlgorithms=e.signatures};uf[14]=({dtls:r})=>e=>{ns(r.sessionId,"server_hello_done",e)};DP=class bp{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:S2,cookie:id.types.buffer(id.types.uint8)};static createEmpty(){return new bp(void 0,void 0)}static deSerialize(e){return new bp(...Object.values((0,id.decode)(e,bp.spec)))}serialize(){let e=(0,id.encode)(this,bp.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},hz=ut("werift-dtls : packages/dtls/src/context/dtls.ts : log"),ik=class{constructor(r,e){this.options=r,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([r],[e])=>Number(r)-Number(e)).flatMap(([,{data:r}])=>r.sort((e,t)=>e.message_seq-t.message_seq))}checkHandshakesExist=r=>!r.find(e=>this.sortedHandshakeCache.find(t=>t.msg_type===e)==null);bufferHandshakeCache(r,e,t){this.handshakeCache[t]||(this.handshakeCache[t]={data:[],isLocal:e,flight:t});let s=r.filter(n=>{let i=this.handshakeCache[t].data.find(o=>o.msg_type===n.msg_type);return i?(hz(this.sessionId,"exist",i.summary,e,t),!1):!0});this.handshakeCache[t].data=[...this.handshakeCache[t].data,...s]}},pz=class{constructor(r){this.socket=r}send=r=>this.socket.send(r)},T_=class oo{static type=10;static spec={type:pi.types.uint16be,data:pi.types.array(pi.types.uint16be,pi.types.uint16be,"bytes")};type=oo.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new oo}static fromData(e){return new oo({type:oo.type,data:(0,pi.decode)(e,oo.spec.data)})}static deSerialize(e){return new oo((0,pi.decode)(e,oo.spec))}serialize(){return Buffer.from((0,pi.encode)(this,oo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},A_=class xa{static type=13;static spec={type:hi.types.uint16be,data:hi.types.array({hash:hi.types.uint8,signature:hi.types.uint8},hi.types.uint16be,"bytes")};type=xa.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new xa}static deSerialize(e){return new xa((0,hi.decode)(e,xa.spec))}serialize(){let e=(0,hi.encode)(this,xa.spec).slice();return Buffer.from(e)}static fromData(e){let t=Buffer.alloc(2);return t.writeUInt16BE(xa.type),xa.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},ok=class Oy{constructor(e,t){this.level=e,this.description=t}static spec={level:od.types.uint8,description:od.types.uint8};static deSerialize(e){return new Oy(...Object.values((0,od.decode)(e,Oy.spec)))}serialize(){let e=(0,od.encode)(this,Oy.spec).slice();return Buffer.from(e)}},ak=ut("werift-dtls : packages/dtls/record/receive.ts : log"),KS=ut("werift-dtls : packages/dtls/record/receive.ts : err"),mz=r=>{let e=0,t=[];for(;r.length>e;){let s=r.readUInt16BE(e+11);if(r.length<e+(12+s))break;let n=v9.deSerialize(r.subarray(e));t.push(n),e+=13+s}return t},gz=(r,e)=>t=>{switch(t.recordLayerHeader.contentType){case 20:return ak(r.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=t.fragment;try{t.recordLayerHeader.epoch>0&&(ak(r.sessionId,"decrypt handshake"),n=e.decryptPacket(t))}catch(i){throw KS(r.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;n.length>i;){let a=Zs.deSerialize(n.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw KS(r.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(t)}];case 21:{let n=ok.deSerialize(t.fragment);if(c_[n.description]==null){let i=e.decryptPacket(t);n=ok.deSerialize(i)}if(KS(r.sessionId,"ContentType.alert",n,c_[n.description],"flight",r.flight,"lastFlight",r.lastFlight),n.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},ck=ut("werift-dtls : packages/dtls/src/socket.ts : log"),dk=ut("werift-dtls : packages/dtls/src/socket.ts : err"),R2=class{constructor(r,e){this.options=r,this.sessionType=e,this.dtls=new ik(this.options,this.sessionType),this.cipher=new kp(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new pz(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Ie;onData=new Ie;onError=new Ie;onClose=new Ie;transport;cipher;dtls;srtp=new Pp;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){ck("renegotiation",this.sessionType),this.connected=!1,this.cipher=new kp(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new ik(this.options,this.sessionType),this.srtp=new Pp,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=r=>{let e=mz(r);for(let t of e)try{let s=gz(this.dtls,this.cipher)(t);for(let n of s)switch(n.type){case 22:{let i=n.data,o=this.handleFragmentHandshake([i]),a=Object.values(o.reduce((c,d)=>(c[d.msg_type]||(c[d.msg_type]=[]),c[d.msg_type].push(d),c),{})).map(c=>Zs.assemble(c)).sort((c,d)=>c.msg_type-d.msg_type);this.onHandleHandshakes(a).catch(c=>{dk(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(n.data);break;case 21:this.onClose.execute();break}}catch(s){dk(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(ck(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let r=ef.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(r.extension)}{let r=T_.createEmpty();r.data=x2,this.extensions.push(r.extension)}{let r=A_.createEmpty();r.data=v2,this.extensions.push(r.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:yx.type,data:Buffer.alloc(0)});{let r=xx.createEmpty();this.extensions.push(r.extension)}}waitForReady=r=>new Promise(async(e,t)=>{for(let s=0;s<10;s++)if(r()){e();break}else await(0,MP.setTimeout)(100*s);t("waitForReady timeout")});handleFragmentHandshake(r){let e=r.filter(t=>t.fragment_length!==t.length?(this.bufferFragmentedHandshakes.push(t),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[t]=this.bufferFragmentedHandshakes.slice(-1);t.fragment_offset+t.fragment_length===t.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async r=>{let e=Wp(this.dtls)([{type:23,fragment:r}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(r,e){let t=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",r*2+e*2),{clientKey:s,serverKey:n,clientSalt:i,serverSalt:o}=(0,Xc.decode)(t,{clientKey:Xc.types.buffer(r),serverKey:Xc.types.buffer(r),clientSalt:Xc.types.buffer(e),serverSalt:Xc.types.buffer(e)});return this.sessionType===lo.CLIENT?{localKey:s,localSalt:i,remoteKey:n,remoteSalt:o}:{localKey:n,localSalt:o,remoteKey:s,remoteSalt:i}}exportKeyingMaterial(r,e){return mq(r,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===lo.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},WS=ut("werift-dtls : packages/dtls/src/client.ts : log"),I_=class extends R2{constructor(r){super(r,lo.CLIENT),this.onHandleHandshakes=this.handleHandshakes,WS(this.dtls.sessionId,"start client")}async connect(){await new kq(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async r=>{WS(this.dtls.sessionId,"handleHandshakes",r.map(e=>e.msg_type));for(let e of r)switch(e.msg_type){case 3:{let t=DP.deSerialize(e.fragment);await new Bq(this.transport,this.dtls).exec(t)}break;case 2:{if(this.connected)return;this.flight5=new lz(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let t=[11,12,this.options.certificateRequest&&13].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(t)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),WS(this.dtls.sessionId,"dtls connected");break}}},fi=ut("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),yz=(r,e,t,s)=>n=>{fi("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(f=>{switch(f.type){case T_.type:{let h=T_.fromData(f.data).data;fi(e.sessionId,"curves",h);let y=h.filter(v=>x2.includes(v))[0];t.namedCurve=y,fi(e.sessionId,"curve selected",t.namedCurve)}break;case A_.type:{if(!t.signatureHashAlgorithm)throw new Error("need to set certificate");let h=A_.fromData(f.data).data;fi(e.sessionId,"hash,signature",h);let y=h.find(S=>S.signature===t.signatureHashAlgorithm?.signature)?.signature,v=h.find(S=>S.hash===t.signatureHashAlgorithm?.hash)?.hash;if(y==null||v==null)throw new Error("invalid signatureHash")}break;case ef.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let h=ef.fromData(f.data);fi(e.sessionId,"srtp profiles",h.profiles);let y=Pp.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!y)throw new Error;s.srtpProfile=y,fi(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case yx.type:e.remoteExtendedMasterSecret=!0;break;case xx.type:fi(e.sessionId,"RenegotiationIndication",f.data);break;case 43:{let y=[...f.data.subarray(1)].map(v=>v.toString(10));fi("dtls supported version",y)}break}}),t.localRandom=new Qc,t.remoteRandom=Qc.from(n.random);let i=n.cipherSuites;fi(e.sessionId,"cipher suites",i);let o=(()=>{switch(t.signatureHashAlgorithm?.signature){case mi.ecdsa_3:return Jy.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case mi.rsa_1:return Jy.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");t.cipherSuite=o,fi(e.sessionId,"selected cipherSuite",t.cipherSuite),t.localKeyPair=E9(t.namedCurve),e.cookie||=(0,UP.randomBytes)(20);let a=new DP({major:254,minor:253},e.cookie),c=w9(e)([a]),u=Wp(e)(c.map(f=>({type:22,fragment:f.serialize()})),++e.recordSequenceNumber).map(f=>f.serialize());for(let f of u)r.send(f)},uk=ut("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),xz=class extends Gp{constructor(r,e,t,s){super(r,e,4,6),this.cipher=t,this.srtp=s}async exec(r,e=!1){if(this.dtls.flight===4){uk(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([r],!1,4);let t=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(s=>s);this.dtls.lastMessage=t,await this.transmit(t)}sendServerHello(){let r=[];this.srtp.srtpProfile&&r.push(ef.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&r.push({type:yx.type,data:Buffer.alloc(0)});let e=xx.createEmpty();r.push(e.extension);let t=new R9(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,r),s=this.createPacket([t]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificate(){let r=new Zy([Buffer.from(this.cipher.localCert)]),e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}sendServerKeyExchange(){let r=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new B9(b2.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,r.length,r),t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendCertificateRequest(){let r=new I9(o9,v2,[]);uk(this.dtls.sessionId,"sendCertificateRequest",r);let e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}sendServerHelloDone(){let r=new k9,e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}},nf=ut("werift-dtls : packages/dtls/flight/server/flight6.ts"),bz=class extends Gp{constructor(r,e,t){super(r,e,6),this.cipher=t}handleHandshake(r){this.dtls.bufferHandshakeCache([r],!1,5);let e=(()=>{switch(r.msg_type){case 11:return Zy.deSerialize(r.fragment);case 15:return T9.deSerialize(r.fragment);case 16:return A9.deSerialize(r.fragment);case 20:return u_.deSerialize(r.fragment)}})();if(e){let t=Qp[e.msgType];if(!t)return;t({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){nf(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let r=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=r,await this.transmit(r)}sendChangeCipherSpec(){let r=C9.createEmpty().serialize(),e=Wp(this.dtls)([{type:20,fragment:r}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(r),t=new u_(e);this.dtls.epoch=1;let[s]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},Qp={};Qp[16]=({cipher:r,dtls:e})=>t=>{if(r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey},!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error("not exist");let s=d9(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);nf(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?f9(s,n):u9(s,r.remoteRandom.serialize(),r.localRandom.serialize()),r.cipher=S9(r.cipherSuite),r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize()),nf(e.sessionId,"setup cipher",r.cipher.summary)};Qp[11]=({cipher:r,dtls:e})=>t=>{nf(e.sessionId,"handshake certificate",t),r.remoteCertificate=t.certificateList[0]};Qp[15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate)throw new Error("client certificate missing before certificate verify");nf(e.sessionId,"certificate_verify",t.algorithm)};Qp[20]=({dtls:r})=>e=>{nf(r.sessionId,"finished",e)};Fu=ut("werift-dtls : packages/dtls/src/server.ts : log"),jP=class extends R2{constructor(r){super(r,lo.SERVER),this.onHandleHandshakes=this.handleHandshakes,Fu(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async r=>{Fu(this.dtls.sessionId,"handleHandshakes",r.map(e=>e.msg_type));for(let e of r)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let t=x9.deSerialize(e.fragment);t.cookie.length===0?(Fu(this.dtls.sessionId,"send flight2"),yz(this.transport,this.dtls,this.cipher,this.srtp)(t)):this.dtls.cookie&&t.cookie.equals(this.dtls.cookie)?(Fu(this.dtls.sessionId,"send flight4"),await new xz(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):Fu("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:t.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new bz(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let t=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(t)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),Fu(this.dtls.sessionId,"dtls connected")}break}}},wx=554869826,HP=8,FP=1398035790,co=20,k2=24,P2=1,B2=2,qP=6,zP=50,vz=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],N2=(r=>(r[r.REQUEST=0]="REQUEST",r[r.INDICATION=16]="INDICATION",r[r.RESPONSE=256]="RESPONSE",r[r.ERROR=272]="ERROR",r))(N2||{}),O2=(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",r))(O2||{});fk=class{queue=[];wait=new Ie;put(r){this.queue.push(r),this.queue.length===1&&this.wait.execute(r)}get(){let r=this.queue.shift();return r||new Promise(e=>{this.wait.subscribe(t=>{this.queue.shift(),e(t)})})}},R_=r=>{let e,t,s=new Promise((i,o)=>{e=i,t=o});s.then(()=>{n.execute(void 0),n.complete()}).catch(i=>{n.execute(i??new Error),n.complete()});let n=new Ie;return r(e,t,n).catch(()=>{}),{awaitable:s,resolve:e,reject:t}};M2=Buffer.alloc(6);M2.writeUInt16BE(wx>>16,0);M2.writeUInt32BE(wx,2);ip=r=>{let e=Buffer.alloc(4);return e.writeUInt32BE(r,0),e},op=r=>r.readUInt32BE(0),_z=r=>{let e=Buffer.alloc(4);return e.writeUInt16BE(r,0),e},Ez=r=>r.readUInt16BE(0),lk=r=>new RS(r.toString()).toBuffer(),hk=r=>{let e=new RS(r);return BigInt(e.toString())},GS=r=>Buffer.from(r,"utf8"),XS=r=>r.toString("utf8"),YS=r=>r,JS=r=>r,Cz=r=>Buffer.from([]),Tz=r=>null,KP=[[1,"MAPPED-ADDRESS",Vu,Ku],[3,"CHANGE-REQUEST",ip,op],[4,"SOURCE-ADDRESS",Vu,Ku],[5,"CHANGED-ADDRESS",Vu,Ku],[6,"USERNAME",GS,XS],[8,"MESSAGE-INTEGRITY",YS,JS],[9,"ERROR-CODE",Sz,wz],[12,"CHANNEL-NUMBER",_z,Ez],[13,"LIFETIME",ip,op],[18,"XOR-PEER-ADDRESS",Dy,Ly],[19,"DATA",YS,JS],[20,"REALM",GS,XS],[21,"NONCE",YS,JS],[22,"XOR-RELAYED-ADDRESS",Dy,Ly],[25,"REQUESTED-TRANSPORT",ip,op],[32,"XOR-MAPPED-ADDRESS",Dy,Ly],[36,"PRIORITY",ip,op],[37,"USE-CANDIDATE",Cz,Tz],[32802,"SOFTWARE",GS,XS],[32808,"FINGERPRINT",ip,op],[32809,"ICE-CONTROLLED",lk,hk],[32810,"ICE-CONTROLLING",lk,hk],[32811,"RESPONSE-ORIGIN",Vu,Ku],[32812,"OTHER-ADDRESS",Vu,Ku]],WP=class{constructor(r=[]){this.attributes=r}getAttributes(){return this.attributes}setAttribute(r,e){let t=this.attributes.find(s=>s[0]===r);return t?t[1]=e:this.attributes.push([r,e]),this}getAttributeValue(r){let e=this.attributes.find(t=>t[0]===r);if(e)return e[1]}get attributesKeys(){return this.attributes.map(r=>r[0])}clear(){this.attributes=[]}},pk=KP.reduce((r,e)=>(r[e[0]]=e,r),{}),Az=KP.reduce((r,e)=>(r[e[1]]=e,r),{});Qs=class extends WP{constructor(r,e,t=$P(),s=[]){super(s),this.messageMethod=r,this.messageClass=e,this.transactionId=t}toJSON(){return this.json}get json(){return{messageMethod:O2[this.messageMethod],messageClass:N2[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let r=Buffer.from([]);for(let t of this.attributesKeys){let s=this.getAttributeValue(t),[n,,i]=Az[t],o=i.name===Dy.name?i(s,this.transactionId):i(s),a=o.length,c=4*Math.floor((a+3)/4)-a,d=Buffer.alloc(4);d.writeUInt16BE(n,0),d.writeUInt16BE(a,2),r=Buffer.concat([r,d,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(r.length,2),e.writeUInt32BE(wx,4),Buffer.concat([e,this.transactionId,r])}addMessageIntegrity(r){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(r)),this}messageIntegrity(r){let e=U2(this.bytes,this.bytes.length-co+k2);return Buffer.from((0,L2.createHmac)("sha1",r).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",GP(this.bytes))}},U2=(r,e)=>{let t=Buffer.alloc(r.length);return r.copy(t,0,0,2),t.writeUInt16BE(e,2),r.copy(t,4,4),t};XP=class extends Error{response;addr},YP=class extends XP{constructor(r,e){super(),this.response=r,this.addr=e}get str(){let r="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[t,s]=e;r+=` (${t} - ${s})`}return r}},Rz=class extends XP{get str(){return"STUN transaction timed out"}},QS=ut("werift-ice:packages/ice/src/stun/transaction.ts"),j2=class{constructor(r,e,t,s){this.request=r,this.addr=e,this.protocol=t,this.retransmissions=s,this.triesMax=1+(this.retransmissions?this.retransmissions:qP)}timeoutDelay=zP;ended=!1;tries=0;triesMax;onResponse=new Ie;responseReceived=(r,e)=>{this.onResponse.length>0&&(r.messageClass===256?(this.onResponse.execute(r,e),this.onResponse.complete()):this.onResponse.error(new YP(r,e)))};run=async()=>{try{return this.retry().catch(e=>{QS("retry failed",e)}),await this.onResponse.asPromise()}catch(r){throw r}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(r=>{QS("send stun failed",r)}),await new Promise(r=>setTimeout(r,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(QS(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Rz))};cancel(){this.ended=!0}},mk=ut("werift-ice : packages/ice/src/stun/protocol.ts"),tx=class JP{static type="stun";type=JP.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Ie;onDataReceived=new Ie;constructor(){}connectionMade=async(e,t,s)=>{e?this.transport=await Yy.init("udp4",{portRange:t,interfaceAddresses:s}):this.transport=await Yy.init("udp6",{portRange:t,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,t){try{let s=Sx(e);if(!s){this.localCandidate&&this.onDataReceived.execute(e);return}(s.messageClass===256||s.messageClass===272)&&this.transactionsKeys.includes(s.transactionIdHex)?this.transactions[s.transactionIdHex].responseReceived(s,t):s.messageClass===0&&this.onRequestReceived.execute(s,t,e)}catch(s){mk("datagramReceived error",s)}}getExtraInfo(){let{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed)return;let s=e.bytes;await this.transport.send(s,t).catch(()=>{mk("sendStun failed",t,e)})}async sendData(e,t){this.transport.closed||await this.transport.send(e,t)}async request(e,t,s,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");s&&(e.addMessageIntegrity(s),e.addFingerprint());let i=new j2(e,t,this,n);this.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},vs=ut("werift-ice:packages/ice/src/turn/protocol.ts"),kz=500,Pz=600,Bz=285212672,eB=class tB{constructor(e){this.turn=e,e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}static type="turn";type=tB.type;localCandidate;disposer=new Qk;onRequestReceived=new Ie;onDataReceived=new Ie;handleStunMessage=(e,t)=>{try{let s=Sx(e);if(!s){this.onDataReceived.execute(e);return}if(s.messageClass===256||s.messageClass===272){let n=this.turn.transactions[s.transactionIdHex];n&&n.responseReceived(s,t)}else s.messageClass===0&&this.onRequestReceived.execute(s,t,e)}catch(s){vs("datagramReceived error",s)}};async request(e,t,s){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");s&&(e.addMessageIntegrity(s),e.addFingerprint());let n=new j2(e,t,this);this.turn.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(i){throw i}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){return this.disposer.dispose(),this.turn.close()}},rB=class sB{constructor(e,t,s,n,i,o={}){this.server=e,this.username=t,this.password=s,this.lifetime=n,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??kz}static type="turn";type=sB.type;onData=new Ie;onRequestReceived=new Ie;onDataReceived=new Ie;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};let e=new Qs(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",Bz);let[t]=await this.requestWithRetry(e,this.server).catch(n=>{throw vs("connect error",n),n});this.relayedAddress=t.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=t.getAttributeValue("XOR-MAPPED-ADDRESS");let s=t.getAttributeValue("LIFETIME");vs("connect",this.relayedAddress,this.mappedAddress,{exp:s}),this.refresh(s)}handleChannelData(e){let[t,s]=P_.jspack.Unpack("!HH",e.slice(0,4)),n=this.addrByChannel[t];if(n){let i=e.subarray(4,4+s);this.onData.execute(i,n)}}handleSTUNMessage(e,t){try{let s=Sx(e);if(!s)throw new Error("not stun message");if(s.messageClass===256||s.messageClass===272){let n=this.transactions[s.transactionIdHex];n&&n.responseReceived(s,t)}else s.messageClass===0&&this.onData.execute(e,t);if(s.getAttributeValue("DATA")){let n=s.getAttributeValue("DATA");this.onData.execute(n,t)}}catch{vs("parse error",e.toString())}}dataReceived(e,t){let s=(n,i)=>{n.length>=4&&gk(n)?this.handleChannelData(n):this.handleSTUNMessage(n,i)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,n]=is(this.tcpBuffer.subarray(0,4),[2,2]);n+=k_(n);let i=gk(this.tcpBuffer)?4+n:20+n;if(this.tcpBuffer.length<i)break;s(this.tcpBuffer.subarray(0,i),t),this.tcpBuffer=this.tcpBuffer.subarray(i)}else s(e,t)}async send(e,t){if(!this.transport.closed)if(this.transport.type==="tcp"){let s=k_(e.length);await this.transport.send(s>0?Buffer.concat([e,Buffer.alloc(s)]):e,t)}else await this.transport.send(e,t)}async createPermission(e){let t=new Qs(8,0);t.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(t,this.server).catch(s=>{throw s})}refresh=e=>{this.refreshHandle=R_(async(t,s,n)=>{let i=!0;for(n.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;vs("refresh delay",o,{exp:e}),await(0,ZP.setTimeout)(o);let a=new Qs(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),vs("refresh",{exp:e})}catch(c){vs("refresh error",c)}}})};async request(e,t){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let s=new j2(e,t,this);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(n){throw n}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,t){let s,n;try{[s,n]=await this.request(e,t)}catch(i){if(!(i instanceof YP))throw vs("requestWithRetry error",i),i;this.server=i.addr;let[o]=i.response.getAttributeValue("ERROR-CODE"),a=i.response.getAttributeValue("NONCE"),c=i.response.getAttributeValue("REALM");if((o===401&&c||o===438&&this.realm)&&a)vs("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=iB(this.username,this.realm,this.password),e.transactionId=$P(),[s,n]=await this.request(e,this.server);else throw i}return[s,n]}async sendData(e,t){let s=await this.getChannel(t).catch(i=>new Error("channelBind error"));if(s instanceof Error){await this.getPermission(t);let i=new Qs(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",t);await this.sendStun(i,this.server);return}let n=P_.jspack.Pack("!HH",[s.number,e.length]);await this.send(Buffer.concat([Buffer.from(n),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(s=>{throw vs("createPermission error",s),s}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let t=this.channelByAddr[e.join(":")];return t?this.channelRefreshAt<Yu(Date.now()/1e3)&&(this.channelBinding=this.channelBind(t.number,e),this.channelRefreshAt=Yu(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(s=>{throw vs("channelBind error",s),s}),this.channelBinding=void 0,vs("channelBind refresh",t)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},t=this.channelByAddr[e.join(":")],this.addrByChannel[t.number]=e,this.channelBinding=this.channelBind(t.number,e),await this.channelBinding.catch(s=>{throw vs("channelBind error",s),s}),this.channelRefreshAt=Yu(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,vs("channelBind",t)),t}async channelBind(e,t){let s=new Qs(9,0);s.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",t);let[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,t){await this.send(e.bytes,t)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};Sa=class aB{constructor(e,t,s,n,i,o,a,c,d,u,f,h){this.foundation=e,this.component=t,this.transport=s,this.priority=n,this.host=i,this.port=o,this.type=a,this.relatedAddress=c,this.relatedPort=d,this.tcptype=u,this.generation=f,this.ufrag=h}static fromSdp(e){let t=e.split(" ");if(t.length<8)throw new Error("SDP does not have enough properties");let 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 f=8,h=t.length-1;f<h;f+=2)t[f]==="raddr"?s.related_address=t[f+1]:t[f]==="rport"?s.related_port=Number(t[f+1]):t[f]==="tcptype"?s.tcptype=t[f+1]:t[f]==="generation"?s.generation=Number(t[f+1]):t[f]==="ufrag"&&(s.ufrag=t[f+1]);let{foundation:n,component:i,transport:o,priority:a,host:c,port:d,type:u}=s;return new aB(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let t=(0,N_.isIPv4)(this.host),s=(0,N_.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&t===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;return this.relatedAddress&&(e+=` raddr ${this.relatedAddress}`),this.relatedPort!=null&&(e+=` rport ${this.relatedPort}`),this.tcptype&&(e+=` tcptype ${this.tcptype}`),this.generation!=null&&(e+=` generation ${this.generation}`),this.ufrag!=null&&(e+=` ufrag ${this.ufrag}`),e}};Nz=class{cache=new Map;mdnsInstance=(0,dB.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(r){return new Promise((e,t)=>{let s=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(n)},n=setTimeout(()=>{s(),t(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===r&&(s(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(r,"A")})}close(){this.mdnsInstance.destroy()}},Oz=ut("werift-ice : packages/ice/src/ice.ts : log"),D_=class{constructor(r,e,t){this.protocol=r,this.remoteCandidate=e,this.iceControlling=t}id=(0,uB.randomUUID)().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(r){this._state=r}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 sx(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},M_=1,vp=2,fB=5,U_=6,lB=(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",r))(lB||{}),hB={useIpv4:!0,useIpv6:!0};Lz=ut("werift-ice : packages/ice/src/utils.ts");Mz=r=>{if(!r)return;let[e,t]=r.split(":");return[e,Number.parseInt(t)]},Ut=ut("werift-ice : packages/ice/src/ice.ts : log"),vB=class{constructor(r,e){this._iceControlling=r,this.options={...hB,...e};let{stunServer:t,turnServer:s}=this.options;this.stunServer=H_(t)??["stun.l.google.com",19302],this.turnServer=H_(s),this.restart(),Ut("new Connection",this.options)}localUsername=np(4);localPassword=np(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new Sy((0,cB.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new fk;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Ie;stateChanged=new Ie;onIceCandidate=new Ie;get iceControlling(){return this._iceControlling}set iceControlling(r){if(!(this.generation>0||this.nominated)){this._iceControlling=r;for(let e of this.checkList)e.iceControlling=r}}async restart(){this.generation++,this.localUsername=np(4),this.localPassword=np(22),this.options.localPasswordPrefix&&(this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)),this.userHistory[this.localUsername]=this.localPassword,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.localCandidatesEnd=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.checkList=[],this.checkListDone=!1,this.checkListState=new fk,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let r of this.protocols)r.localCandidate&&(r.localCandidate.generation=this.generation,r.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){Ut("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:r,usernameFragment:e,password:t}){Ut("setRemoteParams",{iceLite:r,usernameFragment:e,password:t}),this.remoteIsLite=r,this.remoteUsername=e,this.remotePassword=t}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let r=bB(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let s=r.filter(n=>Object.values(e).includes(n));s.length&&(r=s)}this.options.additionalHostAddresses&&(r=Array.from(new Set([...this.options.additionalHostAddresses,...r])));let t=this.getCandidatePromises(r,5);await Promise.allSettled(t),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(r){this.localCandidates.push(r),this.onIceCandidate.execute(r)}ensureProtocol(r){r.onRequestReceived.subscribe((e,t,s)=>{if(e.messageMethod!==1){this.respondError(e,t,r,[400,"Bad Request"]);return}let n=e.getAttributeValue("USERNAME"),{remoteUsername:i}=yk(n),o=this.userHistory[i]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,t,r,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,t,r,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,t,r))return;let c=new Qs(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",t).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),r.sendStun(c,t).catch(d=>{Ut("sendStun error",d)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,t,r]):this.checkIncoming(e,t,r)}),r.onDataReceived.subscribe(e=>{try{let t=this.nominated;t&&t.protocol===r&&(t.packetsReceived++,t.bytesReceived+=e.length),this.onData.execute(e)}catch(t){Ut("dataReceived",t)}})}getCandidatePromises(r,e=5){let t=[];r=r.filter(c=>!this.protocols.find(d=>d.localIp===c));let s=r.map(async c=>{let d=new tx;this.ensureProtocol(d);try{await d.connectionMade((0,O_.isIPv4)(c),this.options.portRange,this.options.interfaceAddresses),d.localIp=c,this.protocols.push(d),Ut("protocol",d.localIp);let u=[c,d.getExtraInfo()[1]];return d.localCandidate=new Sa(rx("host","udp",u[0]),1,"udp",Ep("host"),u[0],u[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(d),this.appendLocalCandidate(d.localCandidate),d}catch(u){Ut("error protocol STUN",u)}});t.push(...s.map(c=>c.then(d=>d?.localCandidate)));let{stunServer:n,turnServer:i}=this;if(n){let c=s.map(async d=>{let u=await d;return u?new Promise(async(h,y)=>{let v=setTimeout(y,e*1e3);if(u.localCandidate?.host&&(0,O_.isIPv4)(u.localCandidate?.host)){let S=await mB(u,n).catch(C=>{Ut("error",C)});S&&this.appendLocalCandidate(S),clearTimeout(v),h(S)}else clearTimeout(v),h()}).catch(h=>{Ut("query STUN server",h)}):void 0});t.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let d=await B_({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async h=>{if(this.options.turnTransport!=="tcp")return await B_({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw h});this.ensureProtocol(d),this.protocols.push(d);let u=d.turn.relayedAddress,f=d.turn.mappedAddress;return Ut("turn candidateAddress",u),d.localCandidate=new Sa(rx("relay","udp",u[0]),1,"udp",Ep("relay"),u[0],u[1],"relay",f[0],f[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(d.localCandidate),d.localCandidate})().catch(d=>{Ut("query TURN server",d)});this.options.forceTurn&&(t=[]),t.push(c)}return t}async connect(){if(Ut("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),Ut("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await L_.setTimeout(20);let r=vp;for(;this.checkList.length>0&&r===vp;)r=await this.checkListState.get(),Ut("checkListState",r);for(let e of this.checkList)e.handle?.resolve?.();if(r!==M_)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[r]=this.checkList;if(!r)return;r.state===0&&r.updateState(1);let e=new Set(r.localCandidate.foundation);for(let t of this.checkList)t.component===r.component&&!e.has(t.localCandidate.foundation)&&t.state===0&&(t.updateState(1),e.add(t.localCandidate.foundation))}schedulingChecks(){{let r=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===tx.type)).find(e=>e.state===1);if(r)return r.handle=this.checkStart(r),!0}{let r=this.checkList.find(e=>e.state===0);if(r)return r.handle=this.checkStart(r),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=R_(async(r,e,t)=>{let s=0,n=!1,i=new AbortController;t.once(()=>{n=!0,s+=U_,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await L_.setTimeout(fB*(.8+.4*Math.random())*1e3,void 0,{signal:i.signal});let d=this.nominated;if(!d||n)break;let u=this.buildRequest({nominate:!1,localUsername:o,remoteUsername:a,iceControlling:c});try{await d.protocol.request(u,d.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),s=0,this.state==="disconnected"&&this.setState("connected")}catch{if(d.id===this.nominated?.id){Ut("no stun response"),s++,this.setState("disconnected");break}}if(s>=U_){Ut("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(r=>{r(vp)})),this.nominated=void 0;for(let r of this.protocols)r.close&&await r.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(r){this.state=r,this.stateChanged.execute(r)}async addRemoteCandidate(r){if(!r){this.remoteCandidatesEnd=!0;return}if(r.host.includes(".local"))try{this.lookup||(this.lookup=new Nz);let e=await this.lookup.lookup(r.host);r.host=e}catch{return}try{j_(r)}catch{return}Ut("addRemoteCandidate",r),this._remoteCandidates.push(r),this.pairRemoteCandidate(r),this.sortCheckList()}send=async r=>{let e=this.nominated;if(e)await e.protocol.sendData(r,e.remoteAddr),e.packetsSent++,e.bytesSent+=r.length;else return};getDefaultCandidate(){let r=this.localCandidates.sort((t,s)=>t.priority-s.priority),[e]=r;return e}set remoteCandidates(r){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of r){try{j_(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){pB(this.checkList,this.iceControlling)}findPair(r,e){return this.checkList.find(s=>(0,My.default)(s.protocol,r)&&(0,My.default)(s.remoteCandidate,e))}switchRole(r){Ut("switch role",r),this.iceControlling=r,this.sortCheckList()}checkComplete(r){if(r.handle=void 0,r.state===3){if(r.nominated&&(r.remoteCandidate.generation==null||r.remoteCandidate.generation===this.generation)&&this.nominated==null){Ut("nominated",r.toJSON()),this.nominated=r,this.nominating=!1;for(let e of this.checkList)e.component===r.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(Ut("ICE completed"),this.checkListState.put(new Promise(e=>e(M_))),this.checkListDone=!0);return}Ut("not completed",r.toJSON());for(let e of this.checkList)e.localCandidate.foundation===r.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:t})=>!e.includes(t)))return}!this.iceControlling&&this.checkList.find(({state:t})=>t===3)||this.checkListDone||(Ut("ICE failed"),this.checkListState.put(new Promise(e=>{e(vp)})))}checkStart=r=>R_(async e=>{Ut("check start",r.toJSON()),r.updateState(2);let t={},{remotePassword:s,remoteUsername:n,generation:i}=this,o=r.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling}),d=performance.now();try{let[u,f]=await r.protocol.request(c,r.remoteAddr,Buffer.from(s,"utf8"),4),y=(performance.now()-d)/1e3;r.rtt=y,r.totalRoundTripTime+=y,r.roundTripTimeMeasurements++,Ut("response received",c.toJSON(),u.toJSON(),f,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i,rtt:y}),t.response=u,t.addr=f}catch(u){let f=u;if(Ut("failure case",c.toJSON(),f.response?JSON.stringify(f.response.toJSON(),null,2):u,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i},r.remoteAddr),f.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(r).awaitable,e();return}if(f.response?.getAttributeValue("ERROR-CODE")[0]===401){Ut("retry 401",r.toJSON()),await this.checkStart(r).awaitable,e();return}else{Ut("checkStart CandidatePairState.FAILED",r.toJSON()),r.updateState(4),this.checkComplete(r),e();return}}if(!(0,My.default)(t.addr,r.remoteAddr)){r.updateState(4),this.checkComplete(r),e();return}if(a||r.remoteNominated)r.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let u=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling});try{await r.protocol.request(u,r.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{r.updateState(4),this.checkComplete(r);return}r.nominated=!0}r.updateState(3),this.checkComplete(r),e()});addPair(r){this.checkList.push(r),this.sortCheckList()}checkIncoming(r,e,t){let s=r.getAttributeValue("USERNAME"),{remoteUsername:n}=yk(s),i,[o,a]=e;for(let d of this.remoteCandidates)if(d.host===o&&d.port===a){i=d;break}i||(i=new Sa(np(10),1,"udp",r.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(t,i);c||(c=new D_(t,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=n,Ut("Triggered Checks",r.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),r.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(r,e){if(r.localCandidate?.canPairWith(e)&&!this.findPair(r,e)){let t=new D_(r,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(t))return;t.updateState(1),this.addPair(t)}}pairLocalProtocol(r){for(let e of this.remoteCandidates)this.tryPair(r,e)}pairRemoteCandidate=r=>{for(let e of this.protocols)this.tryPair(e,r)};buildRequest({nominate:r,remoteUsername:e,localUsername:t,iceControlling:s}){let n=Uz({remoteUsername:e,localUsername:t}),i=new Qs(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",Ep("prflx")),s?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),r&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(r,e,t,s){let n=new Qs(r.messageMethod,272,r.transactionId);n.setAttribute("ERROR-CODE",s).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),t.sendStun(n,e).catch(i=>{Ut("sendStun error",i)})}},Uz=({remoteUsername:r,localUsername:e})=>`${r}:${e}`,yk=r=>{let[e,t]=r.split(":");return{remoteUsername:e,localUsername:t}};H2=class extends wB.EventEmitter{addEventListener=(r,e)=>{this.addListener(r,e)};removeEventListener=(r,e)=>{this.removeListener(r,e)}},jz=ut("werift:packages/webrtc/src/dataChannel.ts");F2=class extends H2{constructor(r,e,t=!0){if(super(),this.sctp=r,this.parameters=e,this.sendOpen=t,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else t&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Ie;stateChanged=new Ie;onMessage=new Ie;error=new Ie;bufferedAmountLow=new Ie;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(r){if(r<0||r>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=r}setId(r){this.id=r}setReadyState(r){if(r!==this.readyState){switch(this.readyState=r,this.stateChange.execute(r),this.stateChanged.execute(r),r){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}jz("change state",r)}}addBufferedAmount(r){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+r<=this.bufferedAmountLowThreshold;this.bufferedAmount+=r,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(r){let e=this.sctp.datachannelSend(this,r);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},q2=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(r={}){Object.assign(this,r)}},Hz=()=>({type:"ccm",parameter:"fir"}),Zp=()=>({type:"nack"}),ff=()=>({type:"nack",parameter:"pli"}),e0=()=>({type:"goog-remb"}),_B=()=>({type:"transport-cc"}),_a=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(r){Object.assign(this,r)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let r=`${this.name}/${this.clockRate}`;return this.channels===2&&(r+="/2"),r}},gi=class{id;uri;constructor(r){Object.assign(this,r)}},Fz=class{cname;mux=!1;ssrc;constructor(r={}){Object.assign(this,r)}},EB=class{type;parameter;constructor(r={}){Object.assign(this,r)}},CB=class{ssrc;constructor(r={}){Object.assign(this,r)}},TB=class{ssrc;payloadType;rtx;constructor(r){Object.assign(this,r)}},z2=class{rid;direction;constructor(r){Object.assign(this,r)}},AB=(r={})=>new _a({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[Zp(),ff(),e0()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...r}),$2=(r={})=>new _a({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[Zp(),ff(),e0()],...r}),IB=(r={})=>new _a({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[Zp(),ff(),e0()],...r}),RB=(r={})=>new _a({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[Zp(),ff(),e0()],...r}),V2=(r={})=>new _a({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...r}),K2=(r={})=>new _a({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...r}),W2=[RB(),IB(),$2(),AB(),V2(),K2()].map(r=>r.mimeType),qz=W2.filter(r=>r.toLowerCase().startsWith("video/")),zz=W2.filter(r=>r.toLowerCase().startsWith("audio/"));bk=2,vk=3,Qz=0,Ay=50,wk=51,Sk=53,Zz=56,e$=57,t$="0.0.0.0",_k=9,z_={auto:"actpass",client:"active",server:"passive"},Ek=Object.keys(z_).reduce((r,e)=>{let t=z_[e];return r[t]=e,r},{}),r$=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],OB=["cname","msid","mslabel","label"],Ck={SRTP_AES128_CM_HMAC_SHA1_80:df,SRTP_AEAD_AES_128_GCM:ad},jy=["sendonly","sendrecv"],s$=["sendrecv","recvonly"],LB=class extends Map{constructor(r){if(super(),r)for(let e of r)this.set(e.id,e)}};DB=class{constructor(r,e,t,s,n){this.kind=r,this.receiver=t,this.sender=s,this._direction=n,e&&this.setDtlsTransport(e)}id=(0,NB.randomUUID)().toString();onTrack=new Ie;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(r){this._codecs=r}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(r){this._direction=r,jy.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(r){this._currentDirection=r}setDtlsTransport(r){this.receiver.setDtlsTransport(r),this.sender.setDtlsTransport(r)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(r){this.receiver.addTrack(r)&&this.onTrack.execute(r,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(r){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(r.toLowerCase()))?.payloadType}getCodecStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("transport",this.dtlsTransport.id);for(let s of this.codecs){let n={type:"codec",id:qt("codec",s.payloadType,t),timestamp:r,payloadType:s.payloadType,transportId:t,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,sdpFmtpLine:s.parameters};e.push(n)}return e}},MB="inactive",G2="sendonly",X2="recvonly",Y2="sendrecv",Hy=[MB,G2,X2,Y2],Fp=class extends H2{uuid=(0,J2.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Ie;onReceiveRtcp=new Ie;onSourceChanged=new Ie;stopped=!1;muted=!0;constructor(r){super(),Object.assign(this,r),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=r=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(r)?mo.deSerialize(r):r;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},UB=class{id;tracks=[];constructor(r){Array.isArray(r)?this.tracks=r:Object.assign(this,r),this.id??=(0,J2.randomUUID)().toString()}addTrack(r){r.streamId=this.id,this.tracks.push(r)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(r=>r.kind==="audio")}getVideoTracks(){return this.tracks.filter(r=>r.kind==="video")}},n$=ut("werift:packages/webrtc/src/utils.ts");i$={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"};eE=(r,e)=>Hy[Hy.indexOf(r)&Hy.indexOf(e)];tE=Date.now,a$=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,FB=()=>a$+process.hrtime.bigint()/1000n,qp=()=>Date.now()/1e3,qB=()=>{let e=(q_.performance.timeOrigin+q_.performance.now()-Date.UTC(1900,0,1))/1e3,[t,s]=e.toString().split(".").map(Number);return er([4,4],[t,s]).readBigUInt64BE()},rE=r=>{let e=er([8],[r]),[,t,s]=is(e,[2,2,2,2]);return er([2,2],[t,s]).readUInt32BE()};c$=kp.createSelfSignedCertificateWithKey,d$=class{static async rtpSource({port:r,kind:e,cb:t}){r??=await y2();let s=new Fp({kind:e}),n=(0,BB.createSocket)("udp4");n.bind(r);let i=a=>{t&&(a=t(a)),s.writeRtp(a)};return n.addListener("message",i),[s,r,()=>{n.removeListener("message",i);try{n.close()}catch{}}]}},$B=(r,e)=>{if(!r||typeof r!="object")return e!==null&&typeof e=="object"?e:r;if(!e||typeof e!="object")return e??r;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s=e[t];s!=null&&(r[t]=s)}return r},u$=ut("werift:packages/webrtc/src/media/receiver/nack.ts"),Tk=150,f$=class{constructor(r){this.receiver=r}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Ie;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(r){return this._lost[r]}setLost(r,e){this._lost[r]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(t){u$("failed to send nack",t)}},5))}removeLost(r){delete this._lost[r]}addPacket(r){let{sequenceNumber:e,ssrc:t}=r.header;if(this.mediaSourceSsrc=t,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===Ur(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>Ur(this.newEstSeqNum,1)){for(let s=Ur(this.newEstSeqNum,1);s<e;s=Ur(s,1))this.setLost(s,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>Tk&&(this._lost=Object.entries(this._lost).slice(-Tk).reduce((r,[e,t])=>(r[e]=t,r),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(r=>{if(this._lost[r]++>this.retryCount)return this.removeLost(r),r})}sendNack=()=>new Promise((r,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let t=new Dp({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),s=new rd({feedback:t});this.receiver.dtlsTransport.sendRtcp([s]).then(r).catch(e),this.updateRetryCount(),this.onPacketLost.execute(t)}})},l$=ut("werift:packages/webrtc/media/receiver/receiverTwcc"),h$=class{constructor(r,e,t){this.dtlsTransport=r,this.rtcpSsrc=e,this.mediaSourceSsrc=t,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(r){this.extensionInfo[r]={tsn:r,timestamp:FB()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,VB.setTimeout)(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let r=Object.values(this.extensionInfo).sort((u,f)=>u.tsn-f.tsn),e=r[0].tsn,t=r.slice(-1)[0].tsn,s=[],n=r[0].tsn,i=Ur(t-e,1),o,a,c=[];for(let u=e;u<=t;u++){let f=this.extensionInfo[u]?.timestamp;if(f){this.lastTimestamp||(this.lastTimestamp=f),o||(o=this.lastTimestamp);let h=f-this.lastTimestamp;this.lastTimestamp=f;let y=new _p({delta:Number(h)});y.parseDelta(),c.push(y),a!=null&&a.status!==y.type&&(s.push(new Qu({packetStatus:a.status,runLength:u-a.minTSN})),a={minTSN:u,status:y.type}),u===t&&(a!=null?s.push(new Qu({packetStatus:a.status,runLength:u-a.minTSN+1})):s.push(new Qu({packetStatus:y.type,runLength:1}))),a==null&&(a={minTSN:u,status:y.type})}}if(!o)return;let d=new rd({feedback:new Mp({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:Xk(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{l$(u)}),this.extensionInfo={},this.fbPktCount=Gk(this.fbPktCount,1)}},p$=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(r){this.clockRate=r}add(r,e=Date.now()/1e3){let t=this.max_seq==null||fx(r.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=r.header.sequenceNumber),t){let s=Yu(e*this.clockRate);if(this.max_seq!=null&&r.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=r.header.sequenceNumber,r.header.timestamp!==this.last_timestamp&&this.packets_received>1){let n=Math.abs(s-(this.last_arrival??0)-(r.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=s,this.last_timestamp=r.header.timestamp}}get fraction_lost(){let r=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let t=r-e;return r==0||t<=0?0:Math.floor((t<<8)/r)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let r=this.packets_expected-this.packets_received;return r<0?0:r}},vn=ut("werift:packages/webrtc/src/transport/dtls.ts"),$_=class YB{constructor(e,t,s,n=[]){this.config=e,this.iceTransport=t,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=YB.localCertificate}id=(0,GB.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Ie;onRtcp=new Ie;onRtp=new Ie;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new ox(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:t,signatureHash:s}=await kp.createSelfSignedCertificateWithKey({signature:mi.ecdsa_3,hash:Rp.sha256_4},ho.secp256r1_23);return this.localCertificate=new sE(t,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=g$([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new ox(t,s)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,t)=>{this.role==="server"?this.dtls=new jP({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ak(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new I_({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ak(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(s=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(s)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(s=>{this.setState("failed"),vn("dtls failed",s),t(s)}),this.dtls instanceof I_&&(await(0,XB.setTimeout)(100),this.dtls.connect().catch(s=>{this.setState("failed"),vn("dtls connect failed",s),t(s)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),vn("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let t=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let d=Z2(a);if(!d)return[];let u=nx(c);if(!u)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:d,normalizedValue:u}]});if(t.length===0)throw new Error("no supported remote fingerprint algorithms");let s=x$(t),n=t.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,nx(Q2(e,c))),a),new Map);if(!n.some(({normalizedAlgorithm:a,normalizedValue:c})=>i.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");vn("selected SRTP Profile",e);let{localKey:t,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(N9(e),O9(e)),o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new LP(o),this.srtcp=new OP(o)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&X9(e))if(this.bytesReceived+=e.length,this.packetsReceived++,dP(e)){let t;try{t=this.srtcp.decrypt(e)}catch(n){if(n instanceof nd){vn("dropping invalid SRTCP packet",n);return}throw n}let s;try{s=cP.deSerialize(t)}catch(n){vn("dropping malformed SRTCP packet",n);return}for(let n of s)try{this.onRtcp.execute(n)}catch(i){vn("RTCP error",i)}}else{let t;try{t=this.srtp.decrypt(e)}catch(n){if(n instanceof nd){vn("dropping invalid SRTP packet",n);return}throw n}let s;try{s=mo.deSerialize(t)}catch(n){vn("dropping malformed SRTP packet",n);return}try{this.onRtp.execute(s)}catch(n){vn("RTP error",n)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,t){try{let s=this.srtp.encrypt(e,t);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})),s.length}catch(s){return vn("failed to send",s),0}}async sendRtcp(e){let t=Buffer.concat(e.map(n=>n.serialize())),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){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=Ea(),t=[],n={type:"transport",id:qt("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?qt("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?qt("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?qt("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(t.push(n),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:qt("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};t.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:qt("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};t.push(o)}let i=await this.iceTransport.getStats();return t.push(...i),t}},m$=["new","connecting","connected","closed","failed"],sE=class{constructor(r,e,t){this.certPem=e,this.signatureHash=t;let s=zp.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=zp.PrivateKey.fromPEM(Buffer.from(r)).toPEM()}publicKey;privateKey;getFingerprints(){return[new ix("sha-256",Q2(zp.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},ix=class{constructor(r,e){this.algorithm=r,this.value=e}},ox=class{constructor(r=[],e){this.fingerprints=r,this.role=e}},g$=r=>{let e=new Set;return r.filter(({algorithm:t,value:s})=>{let n=`${Z2(t)??t.trim().toLowerCase()}:${nx(s)}`;return e.has(n)?!1:(e.add(n),!0)})},y$=["sha512","sha384","sha256","sha224","sha1"],x$=r=>y$.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm,b$=class{constructor(r){this.ice=r,r.onData.subscribe(e=>{jB(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=r=>this.ice.send(r);async close(){this.closed=!0,this.ice.close()}},Ak=r=>new b$(r),Ik=ut("werift:packages/webrtc/src/transport/ice.ts"),QB=class{constructor(r){this.iceGather=r,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=(0,JB.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Ie;onIceCandidate=new Ie;onNegotiationNeeded=new Ie;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(r){r!==this.state&&(this.state=r,this.onStateChange.execute(r))}gather(){return this.iceGather.gather()}addRemoteCandidate=r=>{if(!this.connection.remoteCandidatesEnd)return r?this.connection.addRemoteCandidate(e7(r)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(r,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==r.usernameFragment||this.connection.remotePassword!==r.password)&&(this.renominating?(Ik("renomination",r),this.connection.resetNominatedPair(),this.renominating=!1):(Ik("restart",r),this.restart())),this.connection.setRemoteParams(r)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new Ie,this.setState("checking");try{await this.connection.connect()}catch(r){throw this.setState("failed"),r}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let r=Ea(),e=[];for(let s of this.localCandidates){let n={type:"local-candidate",id:qt("local-candidate",s.foundation),timestamp:r,transportId:qt("transport",this.id),address:s.ip,port:s.port,protocol:s.protocol,candidateType:s.type,priority:s.priority,foundation:s.foundation};e.push(n)}for(let s of this.connection.remoteCandidates){let n=of(s),i={type:"remote-candidate",id:qt("remote-candidate",n.foundation),timestamp:r,transportId:qt("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(i)}let t=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(s=>s.nominated),...this.connection.candidatePairs.filter(s=>!s.nominated)]:[];for(let s of t){let n={type:"candidate-pair",id:qt("candidate-pair",s.foundation),timestamp:r,transportId:qt("transport",this.id),localCandidateId:qt("local-candidate",s.localCandidate.foundation),remoteCandidateId:qt("remote-candidate",s.remoteCandidate.foundation),state:s.state,nominated:s.nominated,packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived,currentRoundTripTime:s.rtt};e.push(n)}return e}},v$=["new","checking","connected","completed","disconnected","failed","closed"],w$=["new","gathering","complete"],ZB=class{constructor(r={}){this.options=r,this.connection=new vB(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(of(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Ie;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(of)}get localParameters(){return new iE({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(r){r!==this.gatheringState&&(this.gatheringState=r,this.onGatheringStateChange.execute(r))}};t7=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(r){Object.assign(this,r)}static fromSdp(r){let e=Sa.fromSdp(r);return of(e).toJSON()}static isThis(r){if(typeof r?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},nE=class{constructor(r,e,t,s,n,i,o,a,c){this.component=r,this.foundation=e,this.ip=t,this.port=s,this.priority=n,this.protocol=i,this.type=o,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new t7({candidate:cE(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(r){try{if(!r.candidate)throw new Error("candidate is required");let e=dE(r.candidate);return e.sdpMLineIndex=r.sdpMLineIndex??void 0,e.sdpMid=r.sdpMid??void 0,e}catch{}}},iE=class{iceLite=!1;usernameFragment;password;constructor(r={}){Object.assign(this,r)}},yi=class s7{constructor(e=0,t=Buffer.from("")){this.flags=e,this._body=t}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return s7.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(r0(this.body.length))].map(()=>Buffer.from("\0"))])}},oE=class extends yi{constructor(r=0,e){super(r,e),this.flags=r,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=E7(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let r=Buffer.alloc(16);return r.writeUInt32BE(this.initiateTag,0),r.writeUInt32BE(this.advertisedRwnd,4),r.writeUInt16BE(this.outboundStreams,8),r.writeUInt16BE(this.inboundStreams,10),r.writeUInt32BE(this.initialTsn,12),Buffer.concat([r,_7(this.params)])}},zy=class n7 extends oE{static type=1;get type(){return n7.type}},V_=class i7 extends oE{static type=2;get type(){return i7.type}},S$=class o7 extends oE{static type=130;get type(){return o7.type}},$y=class a7 extends yi{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;for(;s<t.length;)this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]),s+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return a7.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([t,s])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(t,0),n.writeUInt16BE(s,2),n})])}},Vy=class c7 extends yi{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.tsn=t.readUInt32BE(0),this.streamId=t.readUInt16BE(4),this.streamSeqNum=t.readUInt16BE(6),this.protocol=t.readUInt32BE(8),this.userData=t.slice(12))}static type=0;get type(){return c7.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.tsn,4),t.writeUInt16BE(this.streamId,8),t.writeUInt16BE(this.streamSeqNum,10),t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);return e%4&&(s=Buffer.concat([s,...[...Array(r0(e))].map(()=>Buffer.from("\0"))])),s}},K_=class d7 extends yi{static type=10;get type(){return d7.type}},W_=class u7 extends yi{static type=11;get type(){return u7.type}},t0=class extends yi{constructor(r=0,e=void 0){super(r,e),this.flags=r,e&&(this.params=E7(e))}params=[];get body(){return _7(this.params)}},G_=class f7 extends t0{static type=6;get type(){return f7.type}},Ky=class X_ extends t0{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return X_.type}get descriptions(){return this.params.map(([e,t])=>({name:(Object.entries(X_.CODE).find(([,n])=>n===e)||[])[0],body:t}))}},Y_=class l7 extends t0{static type=4;get type(){return l7.type}},h7=class p7 extends t0{static type=5;get type(){return p7.type}},J_=class m7 extends t0{static type=130;get type(){return m7.type}},Q_=class g7 extends yi{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4);let s=t.readUInt16BE(8),n=t.readUInt16BE(10),i=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(i),t.readUInt16BE(i+2)]),i+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(i)),i+=4})}}static type=3;get type(){return g7.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.cumulativeTsn,4),t.writeUInt32BE(this.advertisedRwnd,8),t.writeUInt16BE(this.gaps.length,12),t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...this.gaps.map(n=>{let i=Buffer.alloc(4);return i.writeUInt16BE(n[0],0),i.writeUInt16BE(n[1],2),i})]);return s=Buffer.concat([s,...this.duplicates.map(n=>{let i=Buffer.alloc(4);return i.writeUInt32BE(n,0),i})]),s}},y7=class x7 extends yi{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.cumulativeTsn=t.readUInt32BE(0))}static type=7;get type(){return x7.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},b7=class v7 extends yi{static type=8;get type(){return v7.type}},w7=class S7 extends yi{static type=14;get type(){return S7.type}},_$=[Vy,zy,V_,Q_,Y_,h7,G_,y7,b7,Ky,K_,W_,w7,J_,$y],E$=_$.reduce((r,e)=>(r[e.type]=e,r),{});Z_=class e2{constructor(e,t,s,n){this.requestSequence=e,this.responseSequence=t,this.lastTsn=s,this.streams=n}static type=13;get type(){return e2.type}get bytes(){let e=Buffer.from(fo.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(t=>Buffer.from(fo.jspack.Pack("!H",[t])))])}static parse(e){let[t,s,n]=fo.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(fo.jspack.Unpack("!H",e.slice(o))[0]);return new e2(t,s,n,i)}},C7=class t2{constructor(e,t){this.requestSequence=e,this.newStreams=t}static type=17;get type(){return t2.type}get bytes(){return Buffer.from(fo.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[t,s]=fo.jspack.Unpack("!LHH",e);return new t2(t,s)}},Iy={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Wy=class r2{constructor(e,t){this.responseSequence=e,this.result=t}static type=16;get type(){return r2.type}get bytes(){return Buffer.from(fo.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[t,s]=fo.jspack.Unpack("!LL",e);return new r2(t,s)}},Rk={13:Z_,16:Wy,17:C7},Lt=ut("werift/sctp/sctp"),R$=24,k$=60,kk=65535,wn=1200,wp=1,T7=2,s2=4,Pk=10,P$=8,Bk=1/8,Nk=1/4,Ok=3,B$=1,N$=60,ax=2**32,O$=200,L$=30,Lk=135,Dk=7,Mk=32776,Uk=49152,D$=["new","closed","connected","connecting"],M$=class n2{constructor(e,t=5e3){this.transport=e,this.port=t,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Ie;stateChanged=I$(D$);onReconfigStreams=new Ie;onReceive=new Ie;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,$p.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Xy();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=kk;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*wn;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=kk;localTsn=Number(Xy());lastSackedTsn=Gc(this.localTsn);advancedPeerAckTsn=Gc(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=Ok;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=L$;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,t=5e3){let s=new n2(e,t);return s.isServer=!1,s}static server(e,t=5e3){let s=new n2(e,t);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let t,[,,s,n]=C$(e);if(n.filter(o=>o.type===zy.type).length>0){if(n.length!=1)throw new Error;t=0}else t=this.localVerificationTag;if(s===t){this.sackHasNewDataInPacket=!1;for(let o of n)await this.receiveChunk(o);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{Lt("send delayed sack failed",e.message)})},O$))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%ax;n===t?e[e.length-1][1]=i:e.push([i,i]),t=Wu(n)});let s=new Q_(0,void 0);s.cumulativeTsn=this.lastReceivedTsn,s.advertisedRwnd=Math.max(0,this.advertisedRwnd),s.duplicates=[...this.sackDuplicates],s.gaps=e,await this.sendChunk(s).catch(n=>{Lt("send sack failed",n.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Vy.type:this.receiveDataChunk(e);break;case zy.type:{if(!this.isServer)return;let t=e;Lt("receive init",t),this.lastReceivedTsn=Gc(t.initialTsn),this.reconfigResponseSeq=Gc(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let s=new V_;s.initiateTag=this.localVerificationTag,s.advertisedRwnd=this.advertisedRwnd,s.outboundStreams=this._outboundStreamsCount,s.inboundStreams=this._inboundStreamsCount,s.initialTsn=this.localTsn,this.setExtensions(s.params);let n=Date.now()/1e3,i=Buffer.from(qy.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,$p.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([Dk,i]),Lt("send initAck",s),await this.sendChunk(s).catch(o=>{Lt("send initAck failed",o.message)})}break;case V_.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=Gc(t.initialTsn),this.reconfigResponseSeq=Gc(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let s=new K_;for(let[n,i]of t.params)if(n===Dk){s.body=i;break}await this.sendChunk(s).catch(n=>{Lt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case Q_.type:await this.receiveSackChunk(e);break;case Y_.type:{let t=new h7;t.params=e.params,await this.sendChunk(t).catch(s=>{Lt("send heartbeat ack failed",s.message)})}break;case G_.type:this.setState(1);break;case y7.type:{this.timer2Cancel(),this.setState(7);let t=new b7;await this.sendChunk(t).catch(s=>{Lt("send shutdown ack failed",s.message)}),this.t2Start(t),this.setState(6)}break;case Ky.type:Lt("ErrorChunk",e.descriptions);break;case K_.type:{if(!this.isServer)return;let s=e.body,n=(0,$p.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=R$||!s.slice(4).equals(n)){Lt("x State cookie is invalid");return}let i=Date.now()/1e3,o=qy.jspack.Unpack("!L",s)[0];if(o<i-k$||o>i){let c=new Ky(0,void 0);c.params.push([Ky.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(d=>{Lt("send errorChunk failed",d.message)});return}let a=new W_;await this.sendChunk(a).catch(c=>{Lt("send cookieAck failed",c.message)}),this.setState(4)}break;case W_.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case w7.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case J_.type:{if(this.associationState!=4)return;let t=e;for(let[s,n]of t.params){let i=Rk[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case $y.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[t,s]of e)t===Uk?this.remotePartialReliability=!0:t===Mk&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Lt("receiveReconfigParam",Rk[e.type]),e.type){case Z_.type:{let t=e,s=new Wy(t.requestSequence,Iy.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(s),await Promise.all(t.streams.map(async n=>{delete this.inboundStreams[n],this.outboundStreamSeq[n]&&(this.reconfigQueue.includes(n)||this.reconfigQueue.push(n))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(t.streams)}break;case Wy.type:{let t=e;if(t.result!==Iy.ReconfigResultSuccessPerformed)Lt("OutgoingSSNResetRequestParam failed",Object.keys(Iy).find(s=>Iy[s]===t.result));else if(t.responseSequence===this.reconfigRequest?.requestSequence){let s=this.reconfigRequest.streams.map(n=>(delete this.outboundStreamSeq[n],n));this.onReconfigStreams.execute(s),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=Ok,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case C7.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let s=new Wy(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(s)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&wp)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let t=this.getInboundStream(e.streamId);t.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let s of t.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}async receiveSackChunk(e){if(li(this.lastSackedTsn,e.cumulativeTsn))return;let t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let s=this.flightSize>=this.cwnd,n=0,i=0;for(;this.sentQueue.length>0&&Gu(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();n++,a?.acked||(i+=a.bookSize,this.flightSizeDecrease(a)),n===1&&a.sentCount===1&&this.updateRto(t-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let o=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(u=>{for(let f=u[0];f<u[1]+1;f++)c=(e.cumulativeTsn+f)%ax,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(li(u.tsn,c))break;a.has(u.tsn)&&!u.acked&&(i+=u.bookSize,u.acked=!0,this.flightSizeDecrease(u),d=u.tsn)}for(let u of this.sentQueue){if(li(u.tsn,d))break;a.has(u.tsn)||(u.misses++,u.misses===3&&(u.misses=0,this.maybeAbandon(u)||(u.retransmit=!0),u.acked=!1,this.flightSizeDecrease(u),o=!0))}}this.fastRecoveryExit===void 0?(n&&s&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,wn):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=wn))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*wn),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Gu(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():n>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,Gu(this.lastReceivedTsn,e.cumulativeTsn))return;let t=s=>li(s,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let s of[...this.sackMisOrdered].sort())if(s===Wu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let[s,n]of e.streams){let i=this.getInboundStream(s);i.streamSequenceNumber=Ur(n,1);for(let o of i.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-Nk)*this.rttvar+Nk*Math.abs(this.srtt-e),this.srtt=(1-Bk)*this.srtt+Bk*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(B$,Math.min(this.srtt+4*this.rttvar,N$))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new U$),this.inboundStreams[e]}markReceived(e){if(Gu(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let s of[...this.sackMisOrdered].sort())if(s===Wu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;let t=s=>li(s,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t)),!1}send=async(e,t,s,{expiry:n,maxRetransmits:i,ordered:o}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=o&&this.outboundStreamSeq[e]||0,c=Math.ceil(s.length/wn),d=0,u=[];for(let f=0;f<c;f++){let h=new Vy(0,void 0);h.flags=0,o||(h.flags=s2),f===0&&(h.flags|=T7),f===c-1&&(h.flags|=wp),h.tsn=this.localTsn,h.streamId=e,h.streamSeqNum=a,h.protocol=t,h.userData=s.slice(d,d+wn),h.bookSize=h.userData.length,h.expiry=n,h.maxRetransmits=i,d+=wn,this.localTsn=Wu(this.localTsn),u.push(h)}for(u.forEach(f=>{this.outboundQueue.push(f)}),o&&(this.outboundStreamSeq[e]=Ur(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(n=>{Lt("send forwardTsn failed",n.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*wn:4*wn,t=Math.min(this.flightSize+e,this.cwnd),s=!0;for(let n of this.sentQueue){if(n.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=t)break;this.flightSizeIncrease(n),n.misses=0,n.retransmit=!1,n.sentCount++,await this.sendChunk(n).catch(i=>{Lt("send data failed",i.message)}),s&&this.timer3Restart()}s=!1}for(;this.outboundQueue.length>0&&this.flightSize<t&&this.peerRwnd>0;){let n=this.outboundQueue.shift();if(!n)break;if(n.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(n);break}this.sentQueue.push(n),this.flightSizeIncrease(n),n.sentCount++,n.sentTime=Date.now()/1e3,await this.sendChunk(n).catch(i=>{Lt("send data outboundQueue failed",i.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],t=e.slice(0,Lk);this.reconfigQueue=e.slice(Lk);let s=new Z_(this.reconfigRequestSeq,this.reconfigResponseSeq,Gc(this.localTsn),t);this.reconfigRequestSeq=Wu(this.reconfigRequestSeq),this.reconfigRequest=s,await this.sendReconfigParam(s),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Lt("sendReconfigParam",e);let t=new J_;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(s=>{Lt("send reconfig failed",s.message)})}async sendResetRequest(e){Lt("sendResetRequest",e);let t=new Vy(0,void 0);t.streamId=e,this.outboundQueue.push(t),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>P$)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Lt("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>Pk)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Lt("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*wn),this.cwnd=wn,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(Lt("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>Pk)Lt("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Lt("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Lt("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new Y_;e.params.push([1,Buffer.from(qy.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(t=>{Lt("send heartbeat failed",t.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){li(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,t={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn,e++,s.flags&s2||(t[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new $y(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(t).map(([s,n])=>[Number(s),n]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let s=this.sentQueue.findIndex(n=>n.type===e.type);for(let n=s;n>=0;n--){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&wp)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&wp)break}return!0}static getCapabilities(){return new j$(65536)}setRemotePort(e){this.remotePort=e}async start(e){this.started||(this.started=!0,this.setConnectionState("connecting"),e&&this.setRemotePort(e),this.isServer||await this.init())}async init(){let e=new zy;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Lt("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(t){Lt("send init failed",t.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([Uk,Buffer.from("")]),t.push($y.type)),t.push(S$.type),e.push([Mk,Buffer.from(t)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let t=T$(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,Lt("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new G_;await this.sendChunk(e).catch(t=>{Lt("send abort failed",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},U$=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(r){if(this.reassembly.length===0||li(r.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(r);return}for(let[e,t]of A$(this.reassembly)){if(t.tsn===r.tsn)throw new Error("duplicate chunk in reassembly");if(li(t.tsn,r.tsn)){this.reassembly.splice(e,0,r);break}}}*popMessages(){let r=0,e,t,s;for(;r<this.reassembly.length;){let n=this.reassembly[r];if(e===void 0){if(s=!(n.flags&s2),!(n.flags&T7)){if(s)break;r++;continue}if(s&&fx(n.streamSeqNum,this.streamSequenceNumber))break;t=n.tsn,e=r}else if(n.tsn!==t){if(s)break;e=void 0,r++;continue}if(n.flags&wp){let i=this.reassembly.slice(e,r+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);i.pop();let o=Buffer.concat(i);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(r+1)],s&&n.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Ur(this.streamSequenceNumber,1)),r=e,yield[n.streamId,n.protocol,o]}else r++;t=Wu(t)}}pruneChunks(r){let e=-1,t=0;for(let[s,n]of this.reassembly.entries())if(Gu(r,n.tsn))e=s,t+=n.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),t}},j$=class{constructor(r){this.maxMessageSize=r}};qu=ut("werift:packages/webrtc/src/transport/sctp.ts"),Xu=65536,A7=class I7{constructor(e=5e3,t=Xu){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new Ie;id=(0,r7.randomUUID)().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=Xu;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(t=>t()),this.dtlsTransport=e,this.sctp=new M$(new H$(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(t=>{t.forEach(s=>{let n=this.dataChannels[s];n&&(n.setReadyState("closing"),n.setReadyState("closed"),delete this.dataChannels[s])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.negotiated&&t.readyState!=="open"&&t.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{t==="closed"&&this.sctp.setState(1)})].map(t=>t.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}datachannelReceive=async(e,t,s)=>{if(t===Ay&&s.length>0)switch(qu("DCEP",e,t,s),s[0]){case vk:{if(s.length<12){qu("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))qu("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=Fy.jspack.Unpack("!BBHLHH",s),d=12,u=s.slice(d,d+a).toString("utf8");d+=a;let f=s.slice(d,d+c).toString("utf8");qu("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:u,protocol:f});let h=(i&3)===1?o:void 0,y=(i&3)===2?o:void 0,v=new q2({label:u,ordered:(i&128)===0,maxPacketLifeTime:y,maxRetransmits:h,protocol:f,id:e}),S=new F2(this,v,!1);S.isCreatedByRemote=!0,this.dataChannels[e]=S,this.onDataChannel.execute(S),S.setReadyState("open")}let n=this.dataChannels[e];this.dataChannelQueue.push([n,Ay,Buffer.from(Fy.jspack.Pack("!B",[bk]))]),await this.dataChannelFlush()}break;case bk:{qu("DATA_CHANNEL_ACK",e,t);let n=this.dataChannels[e];if(!n)throw new Error("channel not found");n.setReadyState("open")}break}else{let n=this.dataChannels[e];if(n){let i=(()=>{switch(t){case wk:return s.toString("utf8");case Zz:return"";case Sk:return s;case e$:return Buffer.from([]);default:throw new Error}})();n.messagesReceived++,n.bytesReceived+=s.length,n.onMessage.execute(i),n.emit("message",{data:i}),n.onmessage&&n.onmessage({data:i})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=Qz,s=0,n=0;e.ordered||(t=128),e.maxRetransmits?(t=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(t=2,n=e.maxPacketLifeTime);let i=Fy.jspack.Pack("!BBHLHH",[vk,t,s,n,e.label.length,e.protocol.length]),o=Buffer.concat([Buffer.from(i),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,Ay,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,t,s]=this.dataChannelQueue.shift(),n=e.id;if(n===void 0){for(n=this.dataChannelId;Object.keys(this.dataChannels).includes(n.toString());)n+=2;this.dataChannels[n]=e,e.setId(n)}if(t===Ay)await this.sctp.send(n,t,s,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(n,t,s,{expiry:i,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-s.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,t)=>{let s=Buffer.isBuffer(t)?t:Buffer.from(t),n=SB(t);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof t=="string"?[e,wk,s]:[e,Sk,s]),this.sctp.associationState!==4&&qu("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return I7.getCapabilities(this.maxMessageSize)}static getCapabilities(e=Xu){return new aE(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??Xu}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},aE=class{constructor(r){this.maxMessageSize=r}},H$=class{constructor(r){this.dtls=r}set onData(r){this.dtls.dataReceiver=r}send=r=>this.dtls.sendData(r);close(){}},Cp=class R7{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[t,s]=F$(e),n=new R7;t.forEach(o=>{if(o.startsWith("v="))n.version=Number.parseInt(o.slice(2),10);else if(o.startsWith("o="))n.origin=o.slice(2);else if(o.startsWith("s="))n.name=o.slice(2);else if(o.startsWith("c="))n.host=ZS(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=e_(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new ix(d,u))}break;case"ice-lite":n.iceLite=!0;break;case"ice-options":n.iceOptions=c;break;case"ice-pwd":n.icePassword=c;break;case"ice-ufrag":n.iceUsernameFragment=c;break;case"group":Gy(n.group,c);break;case"msid-semantic":Gy(n.msidSemantic,c);break;case"setup":n.dtlsRole=Ek[c];break;case"extmap-allow-mixed":n.extMapAllowMixed=!0;break}}});let i=n.group.find(o=>o.semantic==="BUNDLE");return s.forEach(o=>{let c=o[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let d=c[1],u=c[4].split(" "),f=["audio","video"].includes(d)?u.map(v=>Number(v)):void 0,h=new cx(d,Number.parseInt(c[2]),c[3],f||u);if(h.dtlsParams=new ox([...n.dtlsFingerprints],n.dtlsRole),h.iceParams=new iE({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword}),h.iceOptions=n.iceOptions,n.media.push(h),o.slice(1).forEach(v=>{if(v.startsWith("c="))h.host=ZS(v.slice(2));else if(v.startsWith("a=")){let[S,C]=e_(v);switch(S){case"candidate":if(!C)throw new Error;h.iceCandidates.push(dE(C));break;case"end-of-candidates":h.iceCandidatesComplete=!0;break;case"extmap":{let[O,K]=C.split(" ");O.includes("/")&&([O]=O.split("/")),h.rtp.headerExtensions.push(new gi({id:Number.parseInt(O),uri:K}))}break;case"fingerprint":{if(!C)throw new Error;let[O,K]=C.split(" ");h.dtlsParams?.fingerprints.push(new ix(O,K))}break;case"ice-options":h.iceOptions=C;break;case"ice-pwd":h.iceParams.password=C;break;case"ice-ufrag":h.iceParams.usernameFragment=C;break;case"ice-lite":h.iceParams.iceLite=!0;break;case"max-message-size":h.sctpCapabilities=new aE(Number.parseInt(C,10));break;case"mid":h.rtp.muxId=C;break;case"msid":h.msid=C;break;case"rtcp":{let[O,K]=ao(C," ");h.rtcpPort=Number.parseInt(O),h.rtcpHost=ZS(K)}break;case"rtcp-mux":h.rtcpMux=!0;break;case"setup":h.dtlsParams.role=Ek[C];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":h.direction=S;break;case"rtpmap":{let[O,K]=ao(C," "),[z,Q,oe]=K.split("/"),te;h.kind==="audio"&&(te=oe?Number.parseInt(oe):1);let Ee=new _a({mimeType:h.kind+"/"+z,channels:te,clockRate:Number.parseInt(Q),payloadType:Number.parseInt(O)});h.rtp.codecs.push(Ee)}break;case"sctpmap":{if(!C)throw new Error;let[O,K]=ao(C," ");h.sctpMap[Number.parseInt(O)]=K,h.sctpPort=Number.parseInt(O)}break;case"sctp-port":if(!C)throw new Error;h.sctpPort=Number.parseInt(C);break;case"ssrc":{let[O,K]=ao(C," "),z=Number.parseInt(O),[Q,oe]=ao(K,":"),te=h.ssrc.find(Ee=>Ee.ssrc===z);te||(te=new dx({ssrc:z}),h.ssrc.push(te)),OB.includes(Q)&&(te[Q]=oe)}break;case"ssrc-group":Gy(h.ssrcGroup,C);break;case"rid":{let[O,K]=ao(C," ");h.simulcastParameters.push(new z2({rid:O,direction:K}))}break}}}),(!h.iceParams.usernameFragment||!h.iceParams.password)&&h.rtp.muxId&&i&&i.items.includes(h.rtp.muxId))for(let v=0;v<i.items.length;v++){if(!i.items.includes(v.toString()))continue;let S=n.media[v];if(S.iceParams?.usernameFragment&&S.iceParams.password){h.iceParams={...S.iceParams};break}}h.dtlsParams.role||(h.dtlsParams=void 0);let y=v=>h.rtp.codecs.find(S=>S.payloadType===v);o.slice(1).forEach(v=>{if(v.startsWith("a=")){let[S,C]=e_(v);if(S==="fmtp"){let[O,K]=ao(C," "),z=y(Number(O));z.parameters=K}else if(S==="rtcp-fb"){let[O,K,z]=C.split(" ");h.rtp.codecs.forEach(Q=>{["*",Q.payloadType.toString()].includes(O)&&Q.rtcpFeedback.push(new EB({type:K,parameter:z}))})}}})}),n}webrtcTrackId(e){if(e.msid?.includes(" ")){let t=e.msid.split(" ");for(let s of this.msidSemantic)if(s.semantic==="WMS"&&(s.items.includes(t[0])||s.items.includes("*")))return t[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${i2(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(n=>e.push(`a=group:${n.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));let t=this.media.map(n=>n.toString()).join("");return e.join(`\r
133
- `)+`\r
134
- `+t}toJSON(){return new k7(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},cx=class{constructor(r,e,t,s){this.kind=r,this.port=e,this.profile=t,this.fmt=s}host;direction;msid;rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];toString(){let r=[];if(r.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&r.push(`c=${i2(this.host)}`),this.iceCandidates.forEach(e=>{r.push(`a=candidate:${cE(e)}`)}),this.iceCandidatesComplete&&r.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&r.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&r.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&r.push("a=ice-lite"),this.iceOptions&&r.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{r.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),r.push(`a=setup:${z_[this.dtlsParams.role]}`)),this.direction&&r.push(`a=${this.direction}`),this.rtp.muxId&&r.push(`a=mid:${this.rtp.muxId}`),this.msid&&r.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(r.push(`a=rtcp:${this.rtcpPort} ${i2(this.rtcpHost)}`),this.rtcpMux&&r.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{r.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{OB.forEach(t=>{let s=e[t];s!==void 0&&r.push(`a=ssrc:${e.ssrc} ${t}:${s}`)})}),this.rtp.codecs.forEach(e=>{r.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(t=>{let s=t.type;t.parameter&&(s+=` ${t.parameter}`),r.push(`a=rtcp-fb:${e.payloadType} ${s}`)}),e.parameters&&r.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let t=this.sctpMap[Number(e)];r.push(`a=sctpmap:${e} ${t}`)}),this.sctpPort&&r.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&r.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>r.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{r.push(`a=rid:${n.rid} ${n.direction}`)});let e="a=simulcast:",t=this.simulcastParameters.filter(n=>n.direction==="recv");t.length&&(e+=`recv ${t.map(n=>n.rid).join(";")} `);let s=this.simulcastParameters.filter(n=>n.direction==="send");s.length&&(e+=`send ${s.map(n=>n.rid).join(";")}`),r.push(e)}return r.join(`\r
135
- `)+`\r
136
- `}},Zu=class{constructor(r,e){this.semantic=r,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};k7=class{constructor(r,e){this.sdp=r,this.type=e}static isThis(r){if(typeof r?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};dx=class{ssrc;cname;msid;msLabel;label;constructor(r){Object.assign(this,r)}},Ry=ut("werift:packages/webrtc/src/media/rtpReceiver.ts"),uE=class{constructor(r,e,t){this.config=r,this.kind=e,this.rtcpSsrc=t}codecs={};get codecArray(){return Object.values(this.codecs).sort((r,e)=>r.payloadType-e.payloadType)}ssrcByRtx={};nack=new f$(this);audioRedHandler=new EP;type="receiver";uuid=(0,kB.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Ie;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(r){this.dtlsTransport=r}get track(){return this.tracks[0]??new Fp({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type===_B().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type===ff().type)}prepareReceive(r){r.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),r.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(r){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new h$(this.dtlsTransport,this.rtcpSsrc,r))}addTrack(r){return this.tracks.find(t=>{if(t.rid)return t.rid===r.rid;if(t.ssrc)return t.ssrc===r.ssrc})?!1:(this.tracks.push(r),r.ssrc&&(this.trackBySSRC[r.ssrc]=r),r.rid&&(this.trackByRID[r.rid]=r),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,Uy.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let r=Object.entries(this.remoteStreams).map(([t,s])=>{let n=0,i=0;if(this.lastSRtimestamp[t]){n=this.lastSRtimestamp[t];let o=qp()-this.receiveLastSRTimestamp[t];o>0&&o<65536&&(i=Yu(o*65536))}return new vx({ssrc:Number(t),fractionLost:s.fraction_lost,packetsLost:s.packets_lost,highestSequence:s.max_seq,jitter:s.jitter,lsr:n,dlsr:i})}),e=new rf({ssrc:this.rtcpSsrc,reports:r});try{this.config.debug.receiverReportDelay&&await(0,Uy.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(t){Ry("sendRtcp failed",t),await(0,Uy.setTimeout)(500+Math.random()*1e3)}}}catch{}}}async getStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("transport",this.dtlsTransport.id);for(let s of this.tracks){if(!s.ssrc)continue;let n=this.remoteStreams[s.ssrc];if(!n)continue;let i={type:"inbound-rtp",id:qt("inbound-rtp",s.ssrc),timestamp:r,ssrc:s.ssrc,kind:this.kind,transportId:t,codecId:this.codecs[0]?qt("codec",this.codecs[0].payloadType,t):void 0,mid:this.sdesMid,trackIdentifier:s.id,packetsReceived:n.packets_received,packetsLost:n.packets_lost,jitter:n.jitter};if(e.push(i),this.lastSRtimestamp[s.ssrc]){let o={type:"remote-outbound-rtp",id:qt("remote-outbound-rtp",s.ssrc),timestamp:r,ssrc:s.ssrc,kind:this.kind,transportId:t,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[s.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(r){if(!this.pliEnabled){Ry("pli not supported",{mediaSsrc:r});return}if(this.stopped)return;Ry("sendRtcpPLI",{mediaSsrc:r});let e=new tf({feedback:new Op({senderSsrc:this.rtcpSsrc,mediaSsrc:r})});try{await this.dtlsTransport.sendRtcp([e])}catch(t){Ry(t)}}handleRtcpPacket(r){switch(r.type){case sd.type:{let e=r;this.lastSRtimestamp[e.ssrc]=rE(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=qp();let t=this.trackBySSRC[r.ssrc];t&&t.onReceiveRtcp.execute(r)}break}this.onRtcp.execute(r)}handleRtpBySsrc=(r,e)=>{let t=this.trackBySSRC[r.header.ssrc];this.handleRTP(r,e,t)};handleRtpByRid=(r,e,t)=>{let s=this.trackByRID[e];this.trackBySSRC[r.header.ssrc]||(this.trackBySSRC[r.header.ssrc]=s),this.handleRTP(r,t,s)};handleRTP(r,e,t){if(this.stopped)return;let s=this.codecs[r.header.payloadType];if(!s)return;if(this.remoteStreams[r.header.ssrc]=this.remoteStreams[r.header.ssrc]??new p$(s.clockRate),this.remoteStreams[r.header.ssrc].add(r),this.receiverTWCC){let i=e[Yt.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(r.header.ssrc);if(s.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[r.header.ssrc],o=Vp(s.parameters??""),a=this.codecs[o.apt];if(r.payload.length<2)return;r=TP(r,a.payloadType,i),t=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=T2.deSerialize(r.payload),!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())))){if(t?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(r),t)if(n){if(t.kind==="audio"){let i=this.audioRedHandler.push(n,r);for(let o of i)t.onReceiveRtp.execute(o.clone(),e)}}else t.onReceiveRtp.execute(r.clone(),e);this.runRtcp()}}},ap=ut("werift:packages/webrtc/src/media/router.ts"),P7=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(r){this.ssrcTable[r.ssrc]=r}registerRtpReceiver(r,e){ap("registerRtpReceiver",e),this.ssrcTable[e]=r}registerRtpReceiverBySsrc(r,e){ap("registerRtpReceiverBySsrc",e),e.encodings.filter(t=>t.ssrc!=null).forEach((t,s)=>{this.registerRtpReceiver(r.receiver,t.ssrc),r.addTrack(new Fp({ssrc:t.ssrc,kind:r.kind,id:r.sender.trackId,remote:!0,codec:e.codecs[s]})),t.rtx&&this.registerRtpReceiver(r.receiver,t.rtx.ssrc)}),e.headerExtensions.forEach(t=>{this.extIdUriMap[t.id]=t.uri})}registerRtpReceiverByRid(r,e,t){let[s]=t.codecs;ap("registerRtpReceiverByRid",e),r.addTrack(new Fp({rid:e.rid,kind:r.kind,id:r.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=r.receiver}routeRtp=r=>{let e=uP(r.header.extensions,this.extIdUriMap),t=this.ssrcTable[r.header.ssrc],s=e[Yt.sdesRTPStreamID];if(typeof s=="string"?(t=this.ridTable[s],t.latestRid=s,t.handleRtpByRid(r,s,e)):t?t.handleRtpBySsrc(r,e):(t=Object.values(this.ridTable).filter(o=>o instanceof uE).find(o=>o.trackBySSRC[r.header.ssrc]),t&&(ap("simulcast register receiver by ssrc",r.header.ssrc),this.registerRtpReceiver(t,r.header.ssrc),t.handleRtpBySsrc(r,e))),!t){ap("ssrcReceiver not found");return}let n=e[Yt.sdesMid];typeof n=="string"&&(t.sdesMid=n);let i=e[Yt.repairedRtpStreamId];typeof i=="string"&&(t.latestRepairedRid=i)};routeRtcp=r=>{let e=[];switch(r.type){case sd.type:r=r,e.push(this.ssrcTable[r.ssrc]);break;case rf.type:r=r,r.reports.forEach(t=>{e.push(this.ssrcTable[t.ssrc])});break;case Up.type:{let t=r}break;case rd.type:{let t=r;t.feedback&&e.push(this.ssrcTable[t.feedback.mediaSourceSsrc])}break;case tf.type:{let t=r;switch(t.feedback.count){case Lp.count:{let s=t.feedback;e.push(this.ssrcTable[s.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[t.feedback.senderSsrc]||this.ssrcTable[t.feedback.mediaSsrc])}}break}e.filter(t=>t).forEach(t=>t.handleRtcpPacket(r))}},z$=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(r,e,t){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=t,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=t):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),t<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=t),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),t>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=t)),this.numPackets++,this.totalSize+=r}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let r=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/r*8*1e3;return Np(e)}get sendBitrate(){let r=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/r*8*1e3;return Np(e)}},zu=20,$$=10,V$=class{congestion=!1;onAvailableBitrate=new Ie;onCongestion=new Ie;onCongestionScore=new Ie;congestionCounter=0;cumulativeResult=new z$;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(r){this._congestionScore=r,this.onCongestionScore.execute(r)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(r){this._availableBitrate=r,this.onAvailableBitrate.execute(r)}constructor(){}receiveTWCC(r){let t=tE()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<zu?this.congestionCounter++:this.congestionScore<$$&&this.congestionScore++,this.congestionCounter>=zu&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let s of r.packetResults){if(!s.received)continue;let n=s.sequenceNumber,i=this.sentInfos[n];i&&s.receivedAtMs&&this.cumulativeResult.addPacket(i.size,i.sendingAtMs,s.receivedAtMs)}if(t>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-zu){let s=Np(zu/2)+1,n=Np(zu/4)+1,i=s-(s-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-zu&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(r){Object.keys(r).map(e=>Number(e)).sort().filter(e=>e<r.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[r.wideSeq]=r}},t_=ut("werift:packages/webrtc/src/media/rtpSender.ts"),jk=128,Hk=.85,B7=class{constructor(r){this.trackOrKind=r,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof r!="string"&&(r.streamId&&(this.streamId=r.streamId),this.registerTrack(r))}type="sender";kind;ssrc=c2.jspack.Unpack("!L",(0,a2.randomBytes)(4))[0];rtxSsrc=c2.jspack.Unpack("!L",(0,a2.randomBytes)(4))[0];streamId=(0,d2.randomUUID)().toString();trackId=(0,d2.randomUUID)().toString();onReady=new Ie;onRtcp=new Ie;onPictureLossIndication=new Ie;onGenericNack=new Ie;senderBWE=new V$;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=p2();redRedundantPayloadType;_redDistance=2;redEncoder=new _P(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(r){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=r,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(r){this._redDistance=r,this.redEncoder.distance=r}prepareSend(r){this.cname=r.rtcp?.cname,this.mid=r.muxId,this.headerExtensions=r.headerExtensions,this.rtpStreamId=r.rtpStreamId,this.repairedRtpStreamId=r.repairedRtpStreamId,this.codec=r.codecs[0],this.track&&(this.track.codec=this.codec),r.codecs.forEach(e=>{let t=Vp(e.parameters??"");e.name.toLowerCase()==="rtx"&&t.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(r){if(r.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),r.id=this.trackId;let{unSubscribe:e}=r.onReceiveRtp.subscribe(async t=>{await this.sendRtp(t)});this.track=r,this.disposeTrack=e,this.codec&&(r.codec=this.codec),r.onSourceChanged.subscribe(t=>{this.replaceRTP(t)})}async replaceTrack(r){if(r!==null){if(r.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=r.header||(await r.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(r),t_("replaceTrack","ssrc",r.ssrc,"rid",r.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,u2.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let r=[new sd({ssrc:this.ssrc,senderInfo:new C2({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=rE(this.ntpTimestamp),this.lastSentSRTimestamp=qp(),this.cname&&r.push(new Up({chunks:[new _2({source:this.ssrc,items:[new E2({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(r)}catch(e){t_("sendRtcp failed",e),await(0,u2.setTimeout)(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:r,timestamp:e},t=!1){this.sequenceNumber!=null&&(this.seqOffset=Ur(this.sequenceNumber,-r),t&&(this.seqOffset=Ur(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Yc(this.timestamp,-e),t&&(this.timestampOffset=Ur(this.timestampOffset,1))),this.rtpCache=[],t_("replaceRTP",this.sequenceNumber,r,this.seqOffset)}async sendRtp(r){if(this.dtlsTransport.state!=="connected"||!this.codec)return;r=Buffer.isBuffer(r)?mo.deSerialize(r):r;let{header:e,payload:t}=r;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=Yc(e.timestamp,this.timestampOffset),e.sequenceNumber=Ur(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let s=qB(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Yt.sdesMid:return this.mid?fP(this.mid):void 0;case Yt.sdesRTPStreamID:return this.rtpStreamId?lP(this.rtpStreamId):void 0;case Yt.repairedRtpStreamId:return this.repairedRtpStreamId?hP(this.repairedRtpStreamId):void 0;case Yt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Ur(this.dtlsTransport.transportSequenceNumber,1),pP(this.dtlsTransport.transportSequenceNumber);case Yt.absSendTime:return mP(s)}})();if(u)return{id:d.id,payload:u}}).filter(d=>d);for(let d of n){let u=e.extensions.find(f=>f.id===d.id);u?u.payload=d.payload:e.extensions.push(d)}e.extensions=e.extensions.sort((d,u)=>d.id-u.id),this.ntpTimestamp=s,this.rtpTimestamp=e.timestamp,this.octetCount+=t.length,this.packetCount=Yc(this.packetCount,1),this.rtpCache[e.sequenceNumber%jk]=r;let i=t;this.redRedundantPayloadType&&(this.redEncoder.push({block:i,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),i=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(i,e);this.runRtcp();let a=tE(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(r){switch(r.type){case sd.type:case rf.type:r.reports.filter(t=>t.ssrc===this.ssrc).forEach(t=>{if(this.lastSRtimestamp===t.lsr&&t.dlsr&&this.lastSentSRTimestamp){let s=qp()-this.lastSentSRTimestamp-t.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=Hk*this.rtt+(1-Hk)*s}});break;case rd.type:{let e=r;switch(e.feedback.count){case Mp.count:{let t=e.feedback;this.senderBWE.receiveTWCC(t)}break;case Dp.count:{let t=e.feedback;t.lost.forEach(async s=>{let n=this.rtpCache[s%jk];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=AP(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Ur(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(n.payload,n.header))}),this.onGenericNack.execute(t)}break}}break;case tf.type:{let e=r;switch(e.feedback.count){case Lp.count:{let t=e.feedback;this.receiverEstimatedMaxBitrate=t.bitrate}break;case Op.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(r)}getParameters(){return{encodings:[]}}setParameters(r){}async getStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("transport",this.dtlsTransport.id),s={type:"outbound-rtp",id:qt("outbound-rtp",this.ssrc),timestamp:r,ssrc:this.ssrc,kind:this.kind,transportId:t,codecId:this.codec?qt("codec",this.codec.payloadType,t):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(s),this.track){let n={type:"media-source",id:qt("media-source",this.trackId),timestamp:r,trackIdentifier:this.trackId,kind:this.kind};e.push(n)}if(this.rtt!==void 0){let n={type:"remote-inbound-rtp",id:qt("remote-inbound-rtp",this.ssrc),timestamp:r,ssrc:this.ssrc,kind:this.kind,transportId:t,codecId:s.codecId,localId:s.id,roundTripTime:this.rtt};e.push(n)}return e}},K$=ut("werift:packages/webrtc/src/transport/sctpManager.ts"),W$=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Ie;constructor(){}createSctpTransport(r){let e=new A7(5e3,r);return e.mid=void 0,e.onDataChannel.subscribe(t=>{this.dataChannelsOpened++,this.dataChannels.push(t),this.onDataChannel.execute(t)}),this.sctpTransport=e,e}createDataChannel(r,e={}){let s={...{protocol:"",ordered:!0,negotiated:!1},...e};if(s.maxPacketLifeTime&&s.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let n=new q2({id:s.id,label:r,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new F2(this.sctpTransport,n);return this.dataChannelsOpened++,this.dataChannels.push(i),i.stateChange.subscribe(o=>{if(o==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(i);a!==-1&&this.dataChannels.splice(a,1)}}),i}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),K$("sctp connected"))}setRemoteSCTP(r,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(r.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=r.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=r.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let r=Ea(),e=[];for(let t of this.dataChannels){let s={type:"data-channel",id:qt("data-channel",t.id),timestamp:r,label:t.label,protocol:t.protocol,dataChannelIdentifier:t.id,state:t.readyState,messagesSent:t.messagesSent||0,bytesSent:t.bytesSent||0,messagesReceived:t.messagesReceived||0,bytesReceived:t.bytesReceived||0};e.push(s)}return e}},O7=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:r,midSuffix:e,bundlePolicy:t}){this.cname=r,this.midSuffix=e??!1,this.bundlePolicy=t}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(r=>r.direction==="inactive")}createMediaDescriptionForTransceiver(r,e){let t=new cx(r.kind,9,"UDP/TLS/RTP/SAVPF",r.codecs.map(s=>s.payloadType));return t.direction=e,t.msid=r.msid,t.rtp={codecs:r.codecs,headerExtensions:r.headerExtensions,muxId:r.mid},t.rtcpHost="0.0.0.0",t.rtcpPort=9,t.rtcpMux=!0,t.ssrc=[new dx({ssrc:r.sender.ssrc,cname:this.cname})],r.options.simulcast&&(t.simulcastParameters=r.options.simulcast.map(s=>new z2(s))),t.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(t.ssrc.push(new dx({ssrc:r.sender.rtxSsrc,cname:this.cname})),t.ssrcGroup=[new Zu("FID",[r.sender.ssrc.toString(),r.sender.rtxSsrc.toString()])]),this.addTransportDescription(t,r.dtlsTransport),t}createMediaDescriptionForSctp(r){let e=new cx("application",_k,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=r.port,e.rtp.muxId=r.mid,e.sctpCapabilities=r.getCapabilities(),this.addTransportDescription(e,r.dtlsTransport),e}addTransportDescription(r,e){let t=e.iceTransport;r.iceCandidates=t.localCandidates,r.iceCandidatesComplete=t.gatheringState==="complete",r.iceParams=t.localParameters,r.iceOptions="trickle",r.host=t$,r.port=_k,r.direction==="inactive"&&(r.port=0,r.msid=void 0),r.dtlsParams||(r.dtlsParams=e.localParameters,r.dtlsParams.fingerprints||(r.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(r=""){let e="";for(let t=0;e=(t++).toString()+r,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:r,isLocal:e,signalingState:t,type:s}){let n=Cp.parse(r);return this.validateDescription({description:n,isLocal:e,signalingState:t}),n.type=s,n}validateDescription({description:r,isLocal:e,signalingState:t}){if(e){if(r.type==="offer"){if(!["stable","have-local-offer"].includes(t))throw new Error("Cannot handle offer in signaling state")}else if(r.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(t))throw new Error("Cannot handle answer in signaling state")}else if(r.type==="offer"){if(!["stable","have-remote-offer"].includes(t))throw new Error("Cannot handle offer in signaling state")}else if(r.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(t))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(r,e){let t=new Cp;o2("offer",t),(this.currentLocalDescription?.media??[]).forEach((n,i)=>{let o=n.rtp.muxId;if(o)if(n.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=i,t.media.push(this.createMediaDescriptionForSctp(e))}else{let a=r.find(c=>c.mid===o);if(!a){if(n.direction==="inactive"){t.media.push(n);return}throw new Error("transceiver not found")}a.mLineIndex=i,t.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let n of r.filter(i=>!t.media.find(o=>o.rtp.muxId===i.mid))){n.mid==null&&(n.mid=this.allocateMid(this.midSuffix?"av":""));let i=this.createMediaDescriptionForTransceiver(n,n.direction);n.mLineIndex===void 0?(n.mLineIndex=t.media.length,t.media.push(i)):t.media[n.mLineIndex]=i}if(e&&!t.media.find(n=>n.kind==="application")&&(e.mLineIndex=t.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),t.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let n=t.media.map(i=>i.rtp.muxId).filter(i=>i);if(n.length){let i=new Zu("BUNDLE",n);t.group.push(i)}}return t}buildAnswerSdp({transceivers:r,sctpTransport:e,signalingState:t}){if(!["have-remote-offer","have-local-pranswer"].includes(t))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let s=new Cp;o2("answer",s);for(let n of this._remoteDescription.media){let i,o;if(["audio","video"].includes(n.kind)){let a=r.find(c=>c.mid===n.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,eE(a.direction,a.offerDirection)),i=a.dtlsTransport}else if(n.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");o=this.createMediaDescriptionForSctp(e),i=e.dtlsTransport}else throw new Error("invalid kind");o.dtlsParams&&(i.role==="auto"?o.dtlsParams.role="client":o.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(o.simulcastParameters=n.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),s.media.push(o)}if(this.bundlePolicy!=="disable"){let n=new Zu("BUNDLE",[]);for(let i of s.media)i.rtp.muxId&&n.items.push(i.rtp.muxId);s.group.push(n)}return s}setLocalDescription(r){this.currentLocalDescription=r,r.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=r}setRemoteDescription(r,e){if(!r.sdp||!r.type||r.type==="rollback"||r.type==="pranswer")throw new Error("invalid sessionDescription");let t=this.parseSdp({sdp:r.sdp,isLocal:!1,signalingState:e,type:r.type});return t.type==="answer"?(this.currentRemoteDescription=t,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=t,t}registerMid(r){this.seenMid.add(r)}get remoteIsBundled(){let r=this._remoteDescription;return r?r.group.find(t=>t.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(r,e,t){let s=new Map(e.map(o=>[o?.mLineIndex,o])),n=e.find(o=>o?.dtlsTransport)?.dtlsTransport??t?.dtlsTransport;r.media.filter(o=>["audio","video"].includes(o.kind)).forEach((o,a)=>{let d=(s.get(a)??e[a])?.dtlsTransport??n;if(!d)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(o,d)});let i=r.media.find(o=>o.kind==="application");t&&i&&this.addTransportDescription(i,t.dtlsTransport),this.setLocalDescription(r)}},cp=ut("werift:packages/webrtc/src/transport/secureTransportManager.ts"),G$=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Ie;iceConnectionStateChange=new Ie;onIceCandidate=new Ie;connectionStateChange=new Ie;config;transceiverManager;sctpManager;constructor({config:r,transceiverManager:e,sctpManager:t}){if(this.config=r,this.transceiverManager=e,this.sctpManager=t,this.config.dtls){let{keys:s}=this.config.dtls;s&&this.setupCertificate(s)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,t)=>(e.map(s=>s.id).includes(t.id)||e.push(t),e),[])}get iceTransports(){return this.dtlsTransports.map(r=>r.iceTransport)}setupCertificate(r){this.certificate=new sE(r.keyPem,r.certPem,r.signatureHash)}createTransport(){let r=this.iceTransports.find(n=>n.state!=="closed"),e=new ZB({...zB(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});r&&(e.connection.localUsername=r.connection.localUsername,e.connection.localPassword=r.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let t=new QB(e);return t.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new $_(this.config,t,this.certificate,X$)}handleNewIceCandidate({candidate:r,media:e,remoteIsBundled:t,transceiver:s,sctpTransport:n,bundlePolicy:i}){return i==="max-bundle"||t?(r.sdpMLineIndex=0,e&&(r.sdpMid=e.rtp.muxId)):(s&&(r.sdpMLineIndex=s.mLineIndex,r.sdpMid=s.mid),n&&(r.sdpMLineIndex=n.mLineIndex,r.sdpMid=n.mid)),r.foundation&&!r.foundation.startsWith("candidate:")&&(r.foundation="candidate:"+r.foundation),this.onIceCandidate.execute(r),r}async addIceCandidate(r,e){let t=nE.fromJSON(e);if(!t)return;let s;typeof t.sdpMid=="number"&&(s=this.getTransportByMid(t.sdpMid)),!s&&typeof t.sdpMLineIndex=="number"&&(s=this.getTransportByMLineIndex(r,t.sdpMLineIndex)),s||(s=this.iceTransports[0]),s?await s.addRemoteCandidate(t):cp("iceTransport not found for candidate",t)}getTransportByMid(r){let e,t=this.transceiverManager.getTransceivers().find(s=>s.mid===r);return t?e=t.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===r&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(r,e){let t=r.media[e];return t?this.getTransportByMid(t.rtp.muxId):void 0}restartIce(){for(let r of this.iceTransports)r.restart()}setLocalRole({type:r,role:e}){for(let t of this.dtlsTransports){let s=t.iceTransport;r==="offer"?s.connection.iceControlling=!0:s.connection.iceControlling=!1,s.connection.remoteIsLite&&(s.connection.iceControlling=!0),r==="answer"&&e&&(t.role=e)}}updateIceGatheringState(){let r=this.iceTransports;function e(...s){return r.filter(n=>s.includes(n.gatheringState)).length===r.length}let t;r.length&&e("complete")?t="complete":!r.length||e("new","complete")?t="new":r.map(s=>s.gatheringState).includes("gathering")?t="gathering":t="new",this.iceGatheringState!==t&&(this.iceGatheringState=t,this.iceGatheringStateChange.execute(t))}updateIceConnectionState(){let r=this.iceTransports,e;function t(...n){return r.filter(i=>n.includes(i.state)).length===r.length}function s(...n){return r.some(i=>n.includes(i.state))}this.connectionState==="closed"?e="closed":s("failed")?e="failed":s("disconnected")?e="disconnected":t("new","closed")?e="new":s("new","checking")?e="checking":t("completed","closed")?e="completed":t("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(cp("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(r){let e=this.iceTransports.find(t=>t.state==="connected"||t.state==="completed");r&&e?cp("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(t=>t.gather())).catch(t=>{cp("gatherCandidates failed",t)})}setConnectionState(r){cp("connectionStateChange",r),this.connectionState=r,this.connectionStateChange.execute(r)}async getStats(){let r=[];for(let e of this.dtlsTransports){let t=await e.getStats();t&&r.push(...t)}return r}async ensureCerts(){this.certificate||(this.certificate=await $_.SetupCertificate());for(let r of this.dtlsTransports)r.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(r=>r.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},X$=[Ck.SRTP_AEAD_AES_128_GCM,Ck.SRTP_AES128_CM_HMAC_SHA1_80],Sn=ut("werift:packages/webrtc/src/peerConnection.ts"),Y$=class extends H2{cname=(0,N7.randomUUID)().toString();config=L7();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new P7;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Ie;iceConnectionStateChange=new Ie;signalingStateChange=new Ie;connectionStateChange=new Ie;onDataChannel=new Ie;onRemoteTransceiverAdded=new Ie;onTransceiverAdded=new Ie;onIceCandidate=new Ie;onNegotiationneeded=new Ie;onTrack=new Ie;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(r={}){super(),this.setConfiguration(r),this.sdpManager=new O7({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new D7(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:t,transceiver:s})=>{let n={track:e,streams:[t],transceiver:s,receiver:s.receiver};this.onTrack.execute(e),this.emit("track",n),this.ontrack&&this.ontrack(n)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new W$,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let t={channel:e};this.ondatachannel?.(t),this.emit("datachannel",t)}),this.secureManager=new G$({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let t=e?e.toJSON():void 0;this.onIceCandidate.execute(t),this.onicecandidate?.({candidate:t}),this.emit("icecandidate",{candidate:t})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(r){if($B(this.config,r),this.config.icePortRange){let[e,t]=this.config.icePortRange;if(e===t)throw new Error("should not be same value");if(e>=t)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,t]of xk([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(t.payloadType==null)switch(t.payloadType=96+e,t.name.toLowerCase()){case"rtx":t.parameters=`apt=${t.payloadType-1}`;break;case"red":if(t.contentType==="audio"){let s=t.payloadType+1;t.parameters=`${s}/${s}`,t.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,t)=>{e.id=1+t})}getConfiguration(){return this.config}async createOffer({iceRestart:r}={}){(r||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let t of this.transceiverManager.getTransceivers())t.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(t),t.headerExtensions.length===0&&(t.headerExtensions=this.config.headerExtensions[t.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let r=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return r.setDtlsTransport(e),r}createDataChannel(r,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let t=this.sctpManager.createDataChannel(r,e);if(!t.sctp.dtlsTransport){let s=this.findOrCreateTransport();t.sctp.setDtlsTransport(s)}return t}removeTrack(r){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(r),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let r=this.dtlsTransports.find(n=>n.state!=="closed"),e=r?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&r)return r;let t=this.secureManager.createTransport();t.onRtp.subscribe(n=>{this.router.routeRtp(n)}),t.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});let s=t.iceTransport;return s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),s.onIceCandidate.subscribe(n=>{if(!this.localDescription){Sn("localDescription not found when ice candidate was gathered");return}if(!n){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport),this.onIceCandidate.execute(void 0),this.onicecandidate&&this.onicecandidate({candidate:void 0}),this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){Sn("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:n,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(i=>i?.dtlsTransport?.iceTransport.id===s.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===s.id?this.sctpTransport:void 0})}),t}async setLocalDescription(r){r=r??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let t=this.sdpManager.parseSdp({sdp:r.sdp,isLocal:!0,signalingState:this.signalingState,type:r.type});t.type==="offer"?this.setSignalingState("have-local-offer"):t.type==="answer"&&this.setSignalingState("stable");for(let[n,i]of xk(t.media)){let o=i.rtp.muxId;if(this.sdpManager.registerMid(o),["audio","video"].includes(i.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(n);a&&(a.mid=o)}i.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=o)}let s=t.media.find(n=>n.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:t.type,role:s}),["answer","pranswer"].includes(t.type))for(let n of this.transceiverManager.getTransceivers()){let i=eE(n.direction,n.offerDirection);n.setCurrentDirection(i)}return this.sdpManager.setLocal(t,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(n=>{Sn("gatherCandidates failed",n)}),t.type==="answer"&&this.connect().catch(n=>{Sn("connect failed",n),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(t,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),t}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(r){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,r)}async connect(){Sn("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:t}=e;if(t.state==="connected")return;let s=()=>e.state==="connected";s()||(this.secureManager.setConnectionState("connecting"),await t.start().catch(n=>{throw Sn("iceTransport.start failed",n),n}),!s()&&(await e.start().catch(n=>{throw Sn("dtlsTransport.start failed",n),n}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(r){r instanceof Cp&&(r=r.toSdp());let e=this.sdpManager.setRemoteDescription(r,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let t,s=(o,a)=>o.kind===a.kind&&[void 0,a.rtp.muxId].includes(o.mid),n=e.media.map((o,a)=>{let c;if(["audio","video"].includes(o.kind)){let u=this.transceiverManager.getTransceivers().find(f=>s(f,o));if(!u)u=this.addTransceiver(o.kind,{direction:"recvonly"}),u.mid=o.rtp.muxId,this.onRemoteTransceiverAdded.execute(u);else if(u.direction==="inactive"&&u.stopping){u.stopped=!0,r.type==="answer"&&u.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(t?u.setDtlsTransport(t):t=u.dtlsTransport),c=u.dtlsTransport,this.transceiverManager.setRemoteRTP(u,o,e.type,a)}else if(o.kind==="application"){let u=this.sctpTransport;u||(u=this.createSctpTransport(),u.mid=o.rtp.muxId),this.sdpManager.remoteIsBundled&&(t?u.setDtlsTransport(t):t=u.dtlsTransport),c=u.dtlsTransport,this.sctpManager.setRemoteSCTP(o,a)}else throw new Error("invalid media kind");let d=c.iceTransport;if(o.iceParams){let u=!!this.sdpManager.inactiveRemoteMedia;d.setRemoteParams(o.iceParams,u),o.iceParams?.iceLite&&(d.connection.iceControlling=!0)}return o.dtlsParams&&c.setRemoteParams(o.dtlsParams),o.iceCandidates.forEach(d.addRemoteCandidate),o.iceCandidatesComplete&&d.addRemoteCandidate(void 0),e.type==="answer"&&o.dtlsParams?.role&&(c.role=o.dtlsParams.role==="client"?"server":"client"),d});n=n.filter(o=>!!o);let i=this.transceiverManager.getTransceivers().filter(o=>e.media.find(a=>s(o,a))==null);if(r.type==="answer")for(let o of i)o.stop(),o.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(Sn("caller start connect"),this.connect().catch(o=>{Sn("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(r,e={}){let t=this.findOrCreateTransport(),s=this.transceiverManager.addTransceiver(r,t,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),s}addTrack(r,e){if(this.isClosed)throw new Error("is closed");let t=this.transceiverManager.addTrack(r,e);if(!t.dtlsTransport){let s=this.findOrCreateTransport();t.setDtlsTransport(s)}return this.needNegotiation(),t.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(r){Sn("signalingStateChange",r),this.signalingState=r,this.signalingStateChange.execute(r),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let r=Ea();return{type:"peer-connection",id:qt("peer-connection"),timestamp:r,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(r){let e=[];e.push(this.createPeerConnectionStats());let t=await this.transceiverManager.getStats(r);e.push(...t);let s=await this.secureManager.getStats();if(e.push(...s),this.sctpTransport){let n=await this.sctpManager.getStats();n&&e.push(...n)}return new LB(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),Sn("peerConnection closed"))}},f2=(r,e)=>r.find(t=>t.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;J$=L7(),Q$=ut("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),D7=class{constructor(r,e,t){this.cname=r,this.config=e,this.router=t}transceivers=[];onTransceiverAdded=new Ie;onRemoteTransceiverAdded=new Ie;onTrack=new Ie;onNegotiationNeeded=new Ie;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(r=>r.sender)}getReceivers(){return this.getTransceivers().map(r=>r.receiver)}getTransceiverByMLineIndex(r){return this.transceivers.find(e=>e.mLineIndex===r)}pushTransceiver(r){this.transceivers.push(r)}replaceTransceiver(r,e){this.transceivers[e]=r}addTransceiver(r,e,t={}){let s=typeof r=="string"?r:r.kind,n=t.direction||"sendrecv",i=new B7(r),o=new uE(this.config,s,i.ssrc),a=new DB(s,e,o,i,n);a.options=t,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(u=>u.currentDirection==="inactive"&&!u.usedForSender),d=this.transceivers.find(u=>u.currentDirection==="inactive"&&!u.usedForSender);return c>-1&&d?(this.replaceTransceiver(a,c),a.mLineIndex=d.mLineIndex,a.mid=d.mid,d.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(r,e){if(this.getSenders().find(n=>n.track?.uuid===r.uuid))throw new Error("Track already added");let t=this.transceivers.find(n=>n.sender.track==null&&n.kind===r.kind&&jy.includes(n.direction)===!0);if(t)return t.sender.registerTrack(r),t;let s=this.transceivers.find(n=>n.sender.track==null&&n.kind===r.kind&&jy.includes(n.direction)===!1&&!n.usedForSender);if(s){switch(s.sender.registerTrack(r),s.direction){case"recvonly":s.setDirection("sendrecv");break;case"inactive":s.setDirection("sendonly");break}return s}else return this.addTransceiver(r,void 0,{direction:"sendrecv"})}removeTrack(r){if(!this.getSenders().find(({ssrc:t})=>r.ssrc===t))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:t}})=>r.ssrc===t);if(!e)throw new Error("No matching transceiver found");if(r.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(r){let e=this.config.codecs[r.kind].filter(t=>{switch(t.direction){case"recvonly":return!!s$.includes(r.direction);case"sendonly":return!!jy.includes(r.direction);case"sendrecv":return!![Y2,X2,G2].includes(r.direction);case"all":return!0;default:return!1}});r.codecs=e}getLocalRtpParams(r){if(r.mid==null)throw new Error("mid not assigned");return{codecs:r.codecs,muxId:r.mid,headerExtensions:r.headerExtensions,rtcp:{cname:this.cname,ssrc:r.sender.ssrc,mux:!0}}}getRemoteRtpParams(r,e){return{muxId:r.rtp.muxId,rtcp:r.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((s,n)=>{if(n.name.toLowerCase()==="rtx"){let i=Vp(n.parameters??""),o=s[i.apt];return o&&r.ssrc.length===2&&(o.rtx=new CB({ssrc:r.ssrc[1].ssrc})),s}return s[n.payloadType]=new TB({ssrc:r.ssrc[0]?.ssrc,payloadType:n.payloadType}),s},{}))}}setRemoteRTP(r,e,t,s){if(r.mid||(r.mid=e.rtp.muxId),r.mLineIndex=s,r.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],d=f2(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let f=Vp(d.parameters??"").apt,h=e.rtp.codecs.find(y=>y.payloadType===f);return h?!!f2(c,h):!1}return!0}),Q$("negotiated codecs",r.codecs),r.codecs.length===0)throw new Error("negotiate codecs failed.");r.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let n=e.direction??"inactive",i=HB(n);["answer","pranswer"].includes(t)?r.setCurrentDirection(i):r.offerDirection=i;let o=this.getLocalRtpParams(r);if(r.sender.prepareSend(o),["recvonly","sendrecv"].includes(r.direction)){let a=this.getRemoteRtpParams(e,r);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(r,c,a);r.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(r,a)}if(["sendonly","sendrecv"].includes(n)){if(e.msid){let[a,c]=e.msid.split(" ");r.receiver.remoteStreamId=a,r.receiver.remoteTrackId=c}this.onTrack.execute({track:r.receiver.track,transceiver:r,stream:new UB({id:r.receiver.remoteStreamId,tracks:[r.receiver.track]})})}e.ssrc[0]?.ssrc&&r.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(r){let e=[];for(let t of this.transceivers){let s=!r||t.sender.track===r||t.receiver.track===r;if(t.sender){let n=await t.sender.getStats();if(n)for(let i of n)i.type==="outbound-rtp"||i.type==="media-source"?s&&e.push(i):e.push(i)}if(t.receiver){let n=await t.receiver.getStats();if(n)for(let i of n)i.type==="inbound-rtp"||i.type==="remote-outbound-rtp"?s&&e.push(i):e.push(i)}if(s){let n=t.getCodecStats();n&&e.push(...n)}}return e}close(){for(let r of this.transceivers)r.receiver.stop(),r.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},Z$=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],eV=["closed","failed","disconnected","new","connecting","connected"]});var XV={};Tf(XV,{App:()=>iN,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>vE,RequestAbortError:()=>yo,RequestCancelledError:()=>yf,RequestDocSyncError:()=>mf,RequestError:()=>In,RequestTimeoutError:()=>pf,Session:()=>xf,StreamDirectionConflict:()=>gf,createStore:()=>cN,videoStream:()=>dN});module.exports=Bx(XV);var hd=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let s;try{s=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!s.channel)return;let n=this._handlers.get(s.channel);if(n)for(let i of n)i(s)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let s=this._handlers.get(e);return s||(s=new Set,this._handlers.set(e,s)),s.add(t),()=>{s.delete(t),s.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let s=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(s);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(s),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},pd=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[s,n]of this._handlers)for(let i of n)this._targetUnsubscribes.push(e.on(s,i));let t=this._pendingSends;this._pendingSends=[];for(let s of t)e.emit(s.channel,s.data)}rewriteSessionChannels(e,t){if(e===t)return;let s=`session:${e}:`,n=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(s)?n+o.slice(s.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(s)?n+o.channel.slice(s.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let s=this._handlers.get(e);s||(s=new Set,this._handlers.set(e,s)),s.add(t);let n=this._target?.on(e,t);return n&&this._targetUnsubscribes.push(n),()=>{s?.delete(t),s?.size===0&&this._handlers.delete(e),n?.(),n&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==n))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var G7=Ge(lb());var Ob=Ge(c6(),1);function Ex(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function H7(){return Ex()?"Chrome111":void 0}var tV=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],_x=null;function F7(){return Ex()?_x||(_x=rV(),_x):Promise.resolve()}async function rV(){let r=globalThis;if(typeof r.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;r.WebSocket=t}catch(e){j7("WebSocket",e)}if(typeof r.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(U7(),M7));sV(r,e)}catch(e){j7("werift",e)}}function sV(r,e){let{RTCPeerConnection:t,useH264:s,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:u}=e,f=()=>({video:[s(),n()],audio:[i()]}),h=()=>({video:[o(),a(),c(),d(),u()],audio:[o(),c(),d()]});class y extends t{constructor(S){super({...S,codecs:S?.codecs??f(),headerExtensions:S?.headerExtensions??h()})}}r.RTCPeerConnection=y;for(let v of tV)e[v]!=null&&typeof r[v]>"u"&&(r[v]=e[v])}function j7(r,e){let t=e instanceof Error?e.message:String(e);console.warn(`[urun-sh/core] Node WebRTC support: optional dependency "${r}" unavailable (${t}). Realtime media will not work in this Node process; install "${r}" to enable it. Doc/KV transport over WebSocket is unaffected.`)}var q7="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function nV(r){let e=globalThis.crypto,t=new Uint8Array(r);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let s=0;s<r;s++)t[s]=Math.floor(Math.random()*256);return t}function Cx(r=16){let e=nV(r),t="";for(let s=0;s<r;s++)t+=q7[e[s]%q7.length];return t}var z7=[1e3,2e3,4e3,8e3,3e4],$7=5,iV=15e3,oV=2e3,aV=6e3,cV=2,dV=750,uV=3,V7=[1e3,2e3,4e3],fV=15e3,fE="control",X7=0,Y7=1,lE=64;function lV(r,e){if(r===fE){let n=new Uint8Array(1+e.length);return n[0]=X7,n.set(e,1),n}let t=new TextEncoder().encode(r);if(t.length<1||t.length>lE)throw new Error(`[urun] doc key length out of range (1..${lE}): ${t.length}`);let s=new Uint8Array(3+t.length+e.length);return s[0]=Y7,s[1]=t.length>>>8&255,s[2]=t.length&255,s.set(t,3),s.set(e,3+t.length),s}function hV(r){if(r.length===0)return{docKey:fE,payload:r.slice()};let e=r[0];if(e===X7)return{docKey:fE,payload:r.slice(1)};if(e===Y7){if(r.length<3)return null;let t=r[1]<<8|r[2];if(t<1||t>lE||r.length<3+t)return null;let s=new TextDecoder().decode(r.subarray(3,3+t)),n=r.slice(3+t);return{docKey:s,payload:n}}return null}var pV={queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",allocated:"connecting",connecting:"connecting",live:"live",running:"live",failed:"error",rejected:"error",expired:"error",cancelled:"ended",canceled:"ended",closed:"ended"},mV=8e3,K7=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],lf=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Ob.default;_ws=null;_device=null;_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvTransportMsg=null;_lastConsumeMsg=null;_recvConnectWatchdog=null;_recvTcpFailoverDone=!1;_phase={name:"idle"};_requestId;_liveReached=!1;_mediaMonitorTimer=null;_lastInboundTotal=0;_mediaEverFlowed=!1;_lastInboundAdvanceAt=0;_mediaDeathHandled=!1;_currentEpoch=0;_consumerId=null;_pendingStreamSubscribes=new Set;get consumerId(){return this._consumerId===null&&(this._consumerId=gV()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws?.readyState===WebSocket.OPEN}getTrackByName(e){let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let s of this._tracks.values())if(s.kind===e&&s.readyState!=="ended")return s;return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen)throw new Error("TransportSession: cannot change connection while connected");this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,s=xV(t);s!==void 0&&this.setIncarnation(s)}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,s=this._state==="connected";this._currentEpoch=e,t&&s&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended")return!1;let s=e.status_epoch??e.statusEpoch,n=typeof s=="number"?s:Number(s);return Number.isFinite(n)?n<this._currentEpoch:!1}async connect(e){this._lastStartOptions=e,this._intentionalDisconnect=!1;let t=++this._generation;this._state!=="reconnecting"&&this._state!=="renegotiating"&&this._setState("connecting");let s=null,n=()=>t!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let c of this._connectUrls()){i();try{return await this._connectOnce(c,t,e),!0}catch(d){s=d instanceof Error?d:new Error(String(d)),this._cleanupSocket()}}return!1},a=this._resolveConnection?cV:1;for(let c=0;c<a;c++)if(c>0&&(await W7(dV),i()),await o())return;if(this._resolveConnection)for(let c=0;c<uV;c++){this._setState("reconnecting"),await W7(V7[Math.min(c,V7.length-1)]),i();try{let d=await this._resolveConnection();i(),this.setAuth({jwt:d.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:d.url,sessionId:d.sessionId,iceServers:d.iceServers??this._options.iceServers})}catch(d){if(n())throw new Error("TransportSession: connect cancelled");s=d instanceof Error?d:new Error(String(d));continue}if(await o())return}throw this._setState("failed"),s??new Error("TransportSession: connect failed")}disconnect(){if(this._generation+=1,this._intentionalDisconnect=!0,this._stopMediaMonitor(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){this._clearRecvWatchdog();try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._ws){let e=this._ws;this._ws=null;try{e.close(1e3,"intentional disconnect")}catch{}}this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("ended"),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendDocSync(e,t){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(lV(e,t))}onDocSync(e,t){let s=(n,i)=>{n===e&&t(i)};return this.on("docSync",s)}onDocSyncReady(e){return this.on("docSyncReady",e)}_emitDocSyncFrame(e){let t=hV(e);if(!t){console.warn("[urun] doc-sync: unknown/malformed typed-v1 frame; dropped");return}this._emitter.emit("docSync",t.docKey,t.payload)}async addTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._audioProducer=await this._sendTransport.produce({track:e,codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}})}removeTrack(){this._audioProducer&&(this._send({type:"stopAudio"}),this._audioProducer.close(),this._audioProducer=null)}async addVideoTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._videoProducer=await this._sendTransport.produce({track:e})}stopVideo(){this._videoProducer&&(this._send({type:"stopVideo"}),this._videoProducer.close(),this._videoProducer=null)}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}subscribeStream(e){this._pendingStreamSubscribes.add(e),this._sendStreamSubscribe(e)}unsubscribeStream(e){this._pendingStreamSubscribes.delete(e),this._send({t:"stream.unsubscribe",name:e,consumerId:this.consumerId})}_sendStreamSubscribe(e){this._send({t:"stream.subscribe",name:e,consumerId:this.consumerId})}_flushStreamSubscribes(){for(let e of this._pendingStreamSubscribes)this._sendStreamSubscribe(e)}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break}}_onStatus(e){let t=e.request_id??e.requestId;if(t&&(this._requestId=t),this._liveReached)return;let s=typeof e.status=="string"?e.status:void 0,n=(s&&pV[s])??"provisioning",i=e.queue_position??e.queuePosition,o=e.queue_depth??e.queueDepth,a=typeof i=="number"&&typeof o=="number";if(n==="error"){this._setPhase("error",{error:{reason:s??"admission failed",code:s}});return}if(n==="ended"){this._setPhase("ended");return}if(n==="queued"){this._setPhase("queued",a?{queue:{position:i,depth:o}}:void 0);return}if(n==="connecting"){this._setPhase("connecting");return}this._setPhase("provisioning")}async _onRouterCapabilities(e){Ex()&&await F7();let t=H7(),s=new G7.Device(t?{handlerName:t}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&(this._recvTransportMsg=e,this._recvTcpFailoverDone=!1,this._buildRecvTransport(e,!1))}_buildRecvTransport(e,t){if(!this._device)return;let s=e.iceCandidates,n=t?s.filter(a=>a.protocol==="tcp"):s,i=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:n,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??K7}),o=this._generation;i.on("connect",({dtlsParameters:a},c,d)=>{try{this._send({type:"connectTransport",transportId:i.id,dtlsParameters:a}),c()}catch(u){d(u)}}),i.on("connectionstatechange",a=>{if(o===this._generation){if(a==="connected"){this._clearRecvWatchdog();return}if(!(this._intentionalDisconnect&&a==="closed")&&(a==="failed"||a==="disconnected")){if(!t&&!this._recvTcpFailoverDone){this._failoverRecvToTcp(`state:${a}`);return}a==="failed"&&this._emitError(new Error(`media transport ${a}`),a)}}}),this._recvTransport=i,this._clearRecvWatchdog(),t||(this._recvConnectWatchdog=setTimeout(()=>{o===this._generation&&this._recvTransport?.connectionState!=="connected"&&this._failoverRecvToTcp("timeout")},mV))}_clearRecvWatchdog(){this._recvConnectWatchdog&&(clearTimeout(this._recvConnectWatchdog),this._recvConnectWatchdog=null)}_failoverRecvToTcp(e){if(this._recvTcpFailoverDone||this._intentionalDisconnect)return;let t=this._recvTransportMsg;if(!this._device||!t)return;if(!t.iceCandidates.some(n=>n.protocol==="tcp")){this._emitter.emit("error",new Error(`media transport failed (${e}); no TCP candidate`));return}if(this._recvTcpFailoverDone=!0,this._clearRecvWatchdog(),this._recvTransport)try{this._recvTransport.close()}catch{}this._buildRecvTransport(t,!0),this._lastConsumeMsg&&this._onConsume(this._lastConsumeMsg)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??K7}),s=this._generation;t.on("connect",({dtlsParameters:n},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:n}),i()}catch(a){o(a)}}),t.on("produce",({kind:n,rtpParameters:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=setTimeout(()=>{let d=this._pendingProduce;!d||d.timeoutId!==c||(this._pendingProduce=null,d.reject(new Error("Produce timed out")))},15e3);this._pendingProduce={timeoutId:c,resolve:d=>{o({id:d})},reject:a};try{this._send({type:"produce",kind:n,rtpParameters:i})}catch(d){this._pendingProduce?.timeoutId===c&&(this._pendingProduce=null,clearTimeout(c)),a(d)}}),t.on("connectionstatechange",n=>{s===this._generation&&(this._intentionalDisconnect&&n==="closed"||(n==="failed"||n==="closed")&&this._emitError(new Error(`media send transport ${n}`),n))}),this._sendTransport=t,this._emitter.emit("audioTransportReady")}async _onConsume(e){if(!this._recvTransport)return;this._lastConsumeMsg=e;let t=this._generation,s=await this._recvTransport.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track);let n=e.streamName??e.label;n&&this._tracksByName.set(n,s.track),this._liveReached||this._setPhase("live"),this._emitter.emit("track",s.track),s.track.addEventListener("ended",()=>{t!==this._generation||this._intentionalDisconnect||this._renegotiate()},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaMonitor()}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?oV:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?aV:e}_startMediaMonitor(){let e=this._mediaPollMs();if(e<=0||this._mediaMonitorTimer)return;this._lastInboundTotal=0,this._mediaEverFlowed=!1,this._lastInboundAdvanceAt=Date.now(),this._mediaDeathHandled=!1;let t=this._generation;this._mediaMonitorTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._sampleMediaLiveness(t)},e)}_stopMediaMonitor(){this._mediaMonitorTimer&&(clearInterval(this._mediaMonitorTimer),this._mediaMonitorTimer=null)}async _sampleMediaLiveness(e){if(this._consumers.size===0)return;let t=0;for(let n of this._consumers.values())t+=await yV(n);if(e!==this._generation||this._intentionalDisconnect)return;let s=Date.now();if(t>this._lastInboundTotal){this._lastInboundTotal=t,this._lastInboundAdvanceAt=s,t>0&&(this._mediaEverFlowed=!0);return}this._mediaEverFlowed&&(this._mediaDeathHandled||s-this._lastInboundAdvanceAt>=this._mediaStallTimeoutMs()&&(this._mediaDeathHandled=!0,this._renegotiate()))}_renegotiate(){this._intentionalDisconnect||this._reconnectTimer||(this._stopMediaMonitor(),this._setState("renegotiating"),this._attemptReconnect())}_attemptReconnect(e){if(this._intentionalDisconnect||this._reconnectTimer)return;if(this._reconnectAttempts>=$7){this._setState("failed"),this._emitError(new Error(`Failed after ${$7} attempts`));return}let t=z7[Math.min(this._reconnectAttempts,z7.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._cleanupMedia();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},t)}_connectUrls(){let e=[],t=s=>{if(!s)return;let n=/\/ws\/rtc\/[^/?#]+/.test(s),i=this._sessionId&&!n?`${s}${s.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:s;e.includes(i)||e.push(i)};t(this._options.url);for(let s of this._options.fallbackUrls??[])t(s);return e}_connectOnce(e,t,s){return new Promise((n,i)=>{let o=!1,a=!1,c=null,d=new WebSocket(e);d.binaryType="arraybuffer",this._ws=d;let u=f=>{a||this._ws!==d||t!==this._generation||(a=!0,c&&clearTimeout(c),i(f))};c=setTimeout(()=>{try{d.close()}catch{}u(new Error("TransportSession: connect timed out"))},iV),d.onopen=()=>{a||t!==this._generation||(o=!0,c&&clearTimeout(c),this._multiplexer=new hd(d),d.send(JSON.stringify(this._startMessage(s))),this._emitter.emit("docSyncReady"),this._flushStreamSubscribes(),this._scheduleReconnectBudgetReset(),this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,n())},d.onerror=()=>{o||u(new Error("WebSocket connection error"))},d.onclose=()=>{if(!(this._ws!==d||t!==this._generation)){if(this._clearReconnectBudgetReset(),!o){u(new Error("WebSocket closed before connecting"));return}c&&clearTimeout(c),this._setState("disconnected"),this._intentionalDisconnect||(this._emitter.emit("disconnected"),this._attemptReconnect(s))}},d.onmessage=f=>{if(!(this._ws!==d||t!==this._generation)){if(typeof f.data=="string")try{this._handleMessage(JSON.parse(f.data))}catch(h){this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))}else if(f.data instanceof ArrayBuffer)this._emitDocSyncFrame(new Uint8Array(f.data));else if(ArrayBuffer.isView(f.data)){let h=f.data;this._emitDocSyncFrame(new Uint8Array(h.buffer,h.byteOffset,h.byteLength))}}}})}_startMessage(e){let t={type:"start",docFraming:"typed-v1",video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null;try{e.close()}catch{}}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},fV))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupMedia(){this._stopMediaMonitor();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._clearRecvWatchdog(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(JSON.stringify(e))}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_setPhase(e,t){e==="live"&&(this._liveReached=!0);let s={name:e};t?.queue&&(s.queue=t.queue),this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),t?.error&&(s.error=t.error),this._phase=s,this._emitter.emit("phase",s)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t}}),this._emitter.emit("error",e)}};function W7(r){return new Promise(e=>setTimeout(e,r))}function gV(){return Cx()}async function yV(r){if(typeof r.getStats!="function")return 0;let e;try{e=await r.getStats()}catch{return 0}let t=0,s=n=>{if(!n||typeof n!="object")return;let i=n;if(i.type==="inbound-rtp"){let o=typeof i.bytesReceived=="number"?i.bytesReceived:0,a=typeof i.packetsReceived=="number"?i.packetsReceived:0;t+=o+a}};if(e instanceof Map)for(let n of e.values())s(n);else if(Array.isArray(e))for(let n of e)s(n);else e&&typeof e.forEach=="function"&&e.forEach(s);return t}function xV(r){if(!r||typeof r!="object")return;let e=r.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var bV="session-api.prod.cloud.urun.sh",vV=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Tx(r){return r.trim().replace(/\/+$/,"")}function J7(r,e){let t=[],s=n=>{if(!n)return;let i=Tx(n);i&&!t.includes(i)&&t.push(i)};s(r);for(let n of e??[])s(n);for(let n of RV(r))s(n);return t}var wV=120,SV=1e3,_V=3;function EV(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return Tx(`${e.origin}${t}`)}catch{return null}}async function Q7(r){let e=J7(r.baseUrl,r.fallbackUrls),t=null,s=e.length>1;for(let n of e)try{return await CV(n,r,{pollAttempts:wV,retryAfterLimitMs:s?SV:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof cd)throw t}throw t??new Error("[urun] session allocation failed")}async function CV(r,e,t){let s,n,i,o=r,a=0,c=new Set;for(let d=0;d<t.pollAttempts;d++){n=i??await pE(e),i=void 0;let u=s?await fetch(`${o}/api/session-requests/${encodeURIComponent(s)}`,{headers:hE(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...hE(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(TV(e))});if(!s&&(u.status===307||u.status===308)){let v=EV(u.headers.get("location"));if(v&&v!==o&&a<_V){a+=1,o=v;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let f=await eN(u);if(u.ok&&(f.status==="allocated"||!f.status&&!!f.session_id)&&!!f.session_id){let v=f.session_id;if(!f.ws_url)throw new cd(`[urun] gateway allocated session ${v} without ws_url`);if(!tN(f.ws_url))throw new cd(`[urun] gateway allocated session ${v} with non-absolute ws_url`);return{baseUrl:o,sessionId:v,wsUrl:f.ws_url,response:f}}if(u.status===202||f.status==="pending"||f.status==="queued"||f.queued){if(s=f.request_id||s,!s)throw new Error("[urun] gateway queued session without request_id");await IV(AV(u,f,t.retryAfterLimitMs));continue}if((u.status===401||u.status===403)&&e.getAccessToken){let v=n??"";c.add(v);let S=await pE(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!c.has(S)){i=S,s=void 0;continue}}let y=f.error_message||f.error_code||`HTTP ${u.status}`;throw new Error(`[urun] session allocation failed at ${o}: ${y}`)}throw new Error(`[urun] timed out waiting for session allocation at ${o}`)}function hE(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function pE(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function TV(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function Z7(r){let e=J7(r.baseUrl,r.fallbackUrls),t=null;for(let s of e)try{let n={baseUrl:s,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},i=await pE(n),o=await fetch(`${Tx(s)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:hE(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await eN(o);if(!a.ws_url||!tN(a.ws_url))throw new cd(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:Tx(s),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(n){if(t=n instanceof Error?n:new Error(String(n)),t instanceof cd)throw t}throw t??new Error("[urun] viewer-connect failed")}async function eN(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function AV(r,e,t){let s=Number(r.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??s),i=t??1e4;return Number.isFinite(n)&&n>0?Math.min(n*1e3,i):1e3}function IV(r){return new Promise(e=>setTimeout(e,r))}var cd=class extends Error{};function tN(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function RV(r){try{return new URL(r).hostname!==bV?[]:vV}catch{return[]}}var hf=Ge(require("yjs")),rN=Symbol("urun:doc:remote"),kV=Symbol("urun:doc:local");function dd(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ax="$bytes";function PV(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function BV(r){if(!dd(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===Ax&&typeof r[Ax]=="string"}function NV(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function OV(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function LV(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}function mE(r){if(PV(r))return{[Ax]:OV(NV(r))};if(Array.isArray(r))return r.map(mE);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=mE(s);return e}return r}function s0(r){if(BV(r))return LV(r[Ax]);if(Array.isArray(r))return r.map(s0);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=s0(s);return e}return r}function gE(r,e){let t={...r};for(let s of Object.keys(e)){let n=e[s],i=t[s];dd(n)&&dd(i)?t[s]=gE(i,n):t[s]=n}return t}var nN=Symbol("urun:doc:path-absent");function DV(r,e){let t=e.split("."),s=r;for(let n of t){if(s===null||typeof s!="object"||!(n in s))return nN;s=s[n]}return s}function sN(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}var Ix=class{_doc=new hf.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==rN&&this._transport?.sendDocSync(this._key,e)};constructor(e,t,s){this._key=e,this._sessionId=t,this._transport=s??null,this._synced=this._transport===null,this._root.observeDeep(this._observer),this._doc.on("update",this._updateHandler),this._transport&&(this._transportUnsubs.push(this._transport.onDocSync(this._key,n=>this.applyRemote(n)),this._transport.onDocSyncReady(()=>this.sendHello())),this._transport.isOpen&&this.sendHello())}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){if(e=mE(e),!this._synced){this._pendingPatches.push(sN(e)),this.notify();return}this.applyPatch(e)}get(e,t){let s=this.snapshot();if(!e)return s0(s);let n=DV(s,e);return n===nN?t:s0(n)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new yE(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._doc.off("update",this._updateHandler);for(let e of this._transportUnsubs)e();this._transportUnsubs=[],this._transport=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,hf.encodeStateAsUpdate(this._doc))}applyRemote(e){if(hf.applyUpdate(this._doc,e,rN),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let n of t)this.applyPatch(n);let s=[...this._syncWaiters];this._syncWaiters.clear();for(let n of s)n()}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[s,n]of Object.entries(e)){let i=t[s],o=dd(n)&&dd(i)?gE(i,n):sN(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(s,o)}},kV)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=gE(e,t);return e}notify(){let e=s0(this.snapshot());for(let t of this._listeners)t(e)}},yE=class{constructor(e){this._ytext=e;this._observer=t=>{for(let s of t.delta)if(typeof s.insert=="string"&&s.insert.length>0){let n=s.insert;for(let i of this._delta)i(n)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var In=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},pf=class extends In{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},mf=class extends In{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},gf=class extends Error{stream;owner;attempted;constructor(e,t,s){super(`[urun] stream "${e}" is already produced by the ${t}; this (${s}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=s,Object.setPrototypeOf(this,new.target.prototype)}},yo=class extends In{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},yf=class extends In{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var MV=new Set,UV="rpc",jV="llm",vE=3e4,HV="llm-resp";function FV(r){return`${HV}:${r}`}function xE(){return Cx()}function qV(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:s}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function zV(r,e,t,s,n,i,o,a,c){let d=[],u=null,f=!1,h=null,y=!1,v,S,C=new Promise((ne,T)=>{v=ne,S=T});C.catch(()=>{});let O=i(),K=null,z=null,Q=null,oe=null,te=!0,Ee=()=>{Q&&(clearTimeout(Q),Q=null),oe&&(oe(),oe=null)},ge=()=>{te=!1,Ee(),K?.(),K=null,z?.(),z=null,o?.removeEventListener("abort",$),O.dispose(),y&&r.set({requests:{[e]:null}})},Y=()=>{if(u){if(d.length>0){let ne=u;u=null,ne.resolve({value:d.shift(),done:!1})}else if(h!==null){let ne=u;u=null,ne.reject(h)}else if(f){let ne=u;u=null,ne.resolve({value:void 0,done:!0})}}},Ze=ne=>{f||(d.push(ne),Y())},vt=ne=>{f||(h=ne,f=!0,S(ne),ge(),Y())},Fe=ne=>{f||(f=!0,v(ne),ge(),Y())},$=()=>vt(new yo(e)),V=ne=>{if(!(f||!ne||typeof ne!="object"))switch(ne.t){case"delta":typeof ne.delta=="string"&&Ze(ne.delta);break;case"response":Fe(ne.body);break;case"error":{let{message:T,code:R}=qV(ne.body);vt(new In(T,{requestId:e,code:ne.code??R}));break}}},H=()=>{let ne=O.messages()[Symbol.asyncIterator]();K=()=>{ne.return?.(void 0)};let T=()=>{te&&ne.next().then(R=>{if(te){if(R.done){f||Fe(void 0);return}V(R.value),T()}},R=>{te&&vt(R)})};T()},me=()=>{if(!y){if(y=!0,o){if(o.aborted){vt(new yo(e));return}o.addEventListener("abort",$,{once:!0})}z=a?.(ne=>vt(ne))??null,H(),r.set({requests:{[e]:{payload:t,consumer_id:s,stream:n}}}),c&&c>0&&!r.synced&&(Q=setTimeout(()=>{Q=null,!f&&!r.synced&&vt(new mf(c,e))},c),oe=r.onSynced(()=>Ee()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(me(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(h!==null){let ne=h;return h=null,Promise.reject(ne)}return f?Promise.resolve({value:void 0,done:!0}):new Promise((ne,T)=>{u={resolve:ne,reject:T}})},return(){return f||(f=!0,v(void 0),ge()),Promise.resolve({value:void 0,done:!0})},throw(ne){return f||(f=!0,S(ne),ge()),Promise.reject(ne)}}}},body:C,start:me}}function $V(r,e){return[`streams/${r}/${e}`,`streams/${r}/*`]}function VV(r,e){return`streams/${r}/${e??"*"}`}function KV(r,e){let s=r.get("streams")?.[e];if(s&&typeof s=="object"){let{producer:n,epoch:i}=s;if(n==="runtime"||n==="browser")return{producer:n,epoch:typeof i=="number"?i:0}}return null}var bE=class{constructor(e,t,s,n){this._name=e;this._transport=t;this._laneDoc=s;this._controlDoc=n;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_laneDoc;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],s=null,n=!1,i={push(a){if(!n)if(s){let c=s;s=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,s){let a=s;s=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{n=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{s=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){if(!(this._subscribed||this._disposed)&&(this._subscribed=!0,this._transport.subscribeStream(this._name),!!this._laneDoc))for(let e of $V(this._name,this._transport.consumerId)){let t=this._laneDoc(e);this._laneSeen.set(e,0);let s=n=>this._drainLane(e,n);s(t.get()),this._laneUnsubs.push(t.on("change",s))}}_drainLane(e,t){let s=t.messages;if(!Array.isArray(s))return;let n=this._laneSeen.get(e)??0;for(;n<s.length;n++){let i=s[n];this._replay.push(i);for(let o of this._messageConsumers)o.push(i)}this._laneSeen.set(e,n)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}_claimBrowserProducer(){if(!this._controlDoc)return;let e=this._controlDoc(),t=KV(e,this._name);if(t&&t.producer==="runtime")throw new gf(this._name,"runtime","browser");if(t&&t.producer==="browser")return;let s=(typeof t?.epoch=="number"?t.epoch:0)+1;e.set({streams:{[this._name]:{producer:"browser",epoch:s}}})}async attach(e){this._claimBrowserProducer(),await this._transport.addTrack(e)}async attachVideo(e){this._claimBrowserProducer(),await this._transport.addVideoTrack(e)}async emit(e,t={}){if(this._claimBrowserProducer(),!this._laneDoc)throw new Error("[urun] stream.emit requires the session doc transport (no laneDoc wired)");let s=VV(this._name,t.to),n=this._laneDoc(s),i=n.get("messages"),o=Array.isArray(i)?[...i]:[];o.push(e),n.set({messages:o})}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}on(e,t){let s=this._handlers.get(e);return s||(s=new Set,this._handlers.set(e,s)),s.add(t),()=>{s?.delete(t),s?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name);for(let e of this._laneUnsubs)e();this._laneUnsubs=[];for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let s of t)s(e)}},xf=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_activeRequests=new Set;constructor(e,t,s){this._sessionId=e,this._multiplexer=t,this._transport=s,this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let s=await Z7({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new pd,o=new lf({url:s.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new r(e,i,o);return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let s of this._docs.values())s.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new bE(e,this._transport,s=>this.doc(s),()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Ix(e,this._sessionId,MV.has(e)?null:this._transport),this._docs.set(e,t)),t}sendImage(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let s=this.doc(UV),n=xE();return new Promise((i,o)=>{let a=!1,c=null,d=null,u=null,f=()=>{d&&(clearTimeout(d),d=null),c&&(c(),c=null),u&&(this._activeRequests.delete(u),u=null),t.signal?.removeEventListener("abort",y),s.set({requests:{[n]:null}})},h=S=>{a||(a=!0,f(),S())},y=()=>h(()=>o(new yo(n)));if(t.signal){if(t.signal.aborted){a=!0,o(new yo(n));return}t.signal.addEventListener("abort",y,{once:!0})}let v=S=>{let O=S.responses?.[n];if(O==null)return;let K=O;if(K.error!==void 0&&K.error!==null){let z=typeof K.error=="string"?K.error:JSON.stringify(K.error);h(()=>o(new In(z,{requestId:n,code:K.code})))}else h(()=>i(K.result))};c=s.on("change",v),u=S=>h(()=>o(S)),this._activeRequests.add(u),typeof t.timeout=="number"&&t.timeout>=0&&(d=setTimeout(()=>h(()=>o(new pf(t.timeout,n))),t.timeout)),s.set({requests:{[n]:{payload:e}}}),v(s.get())})}_consumeResponse(e,t,s,n,i){let o=this.doc(jV);return zV(o,e,t,this._transport.consumerId,s,()=>this.stream(FV(e)),n,a=>(this._activeRequests.add(a),()=>this._activeRequests.delete(a)),i??vE)}requestStream(e,t={}){let s=xE();return this._consumeResponse(s,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let s=xE(),n=this._consumeResponse(s,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new yf)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var WV=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function iN(r,e){return new Proxy({},{get(t,s){if(!(WV.has(s)||typeof s!="string"))return n=>{let i=n??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new pd,d=new lf({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),u=new xf(a,c,d),f=async h=>{let y=await Q7({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:h}),v=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return u.setSessionId(y.sessionId),{url:y.wsUrl,sessionId:y.sessionId,jwt:v,iceServers:y.response.ice_servers}};return d.setConnectionResolver(()=>f(o())),d.on("connected",()=>{d.multiplexer&&c.setTarget(d.multiplexer)}),(async()=>{let h=await f(a);d.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),await d.connect({app:r,functionName:s,args:i})})().catch(h=>{console.error(`[urun] Failed to connect session for ${s}:`,h)}),u}}})}var oN=3e4,aN="stream:",wE=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",s=>{let n;try{n=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let i=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(i.timer),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let s=`${aN}${e}`;return this._multiplexer.on(s,n=>{t(n)})}emit(e,t){let s=`${aN}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(s,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((s,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),n(new Error(`RPC request "${e}" timed out after ${oN}ms`)))},oN);this._pendingRpc.set(i,{resolve:s,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function cN(r){let s=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,n=new WebSocket(s);(r.jwt||r.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new hd(n);return new wE(n,i)}var GV='video/mp4; codecs="avc1.42E01E"';function dN(r,e){let t=e?.codec??GV,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(t)}catch(C){throw C instanceof DOMException&&C.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):C}let y=r.getReader();function v(){return h.updating?new Promise(C=>{h.addEventListener("updateend",()=>C(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:C,value:O}=await y.read();if(C){await v(),n.readyState==="open"&&n.endOfStream();return}await v();try{h.appendBuffer(O)}catch(K){if(K instanceof DOMException&&K.name==="QuotaExceededError"){let z=h.buffered;if(z.length>0){let Q=z.start(z.length-1);h.remove(0,Q),await v(),h.appendBuffer(O)}else throw K}else throw K}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}S()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),d=c.getTracks(),u=0,f=d.length;if(f===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of d)h.addEventListener("ended",()=>{u++,u>=f&&URL.revokeObjectURL(i)});return c}0&&(module.exports={App,DEFAULT_DOC_SYNC_TIMEOUT_MS,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,Session,StreamDirectionConflict,createStore,videoStream});
7
+ `}});var ve=C(le=>{"use strict";var De=Bn(),Ja=Wn(),Xa=Zt();le.grammar=Xa;le.write=Ja;le.parse=De.parse;le.parseParams=De.parseParams;le.parseFmtpConfig=De.parseFmtpConfig;le.parsePayloads=De.parsePayloads;le.parseRemoteCandidates=De.parseRemoteCandidates;le.parseImageAttributes=De.parseImageAttributes;le.parseSimulcastStreamList=De.parseSimulcastStreamList});var Ie=C(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.parse=ec;var Za=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function ec(s){let e=Za.exec(s??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var Kn=C(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.OfferMediaSection=Ce.AnswerMediaSection=Ce.MediaSection=void 0;var tc=ve(),Hn=ke(),yt=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let n of t){let i={foundation:n.foundation,component:1,ip:n.address??n.ip,port:n.port,priority:n.priority,transport:n.protocol,type:n.type};n.tcpType&&(i.tcptype=n.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};Ce.MediaSection=yt;var ts=class extends yt{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let p of c.codecs){let l={payload:p.payloadType,codec:Gn(p),rate:p.clockRate};p.channels>1&&(l.encoding=p.channels),this._mediaObject.rtp.push(l);let u=Hn.clone(p.parameters)??{},m=Hn.clone(p.rtcpFeedback)??[];if(d){let{opusStereo:h,opusFec:g,opusDtx:_,opusMaxPlaybackRate:y,opusMaxAverageBitrate:x,opusPtime:P,opusNack:k,videoGoogleStartBitrate:I,videoGoogleMaxBitrate:he,videoGoogleMinBitrate:ae}=d,Y=a.codecs.find(fe=>fe.payloadType===p.payloadType);switch(p.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{h!==void 0&&(Y.parameters["sprop-stereo"]=h?1:0,u.stereo=h?1:0),g!==void 0&&(Y.parameters.useinbandfec=g?1:0,u.useinbandfec=g?1:0),_!==void 0&&(Y.parameters.usedtx=_?1:0,u.usedtx=_?1:0),y!==void 0&&(u.maxplaybackrate=y),x!==void 0&&(u.maxaveragebitrate=x),P!==void 0&&(Y.parameters.ptime=P,u.ptime=P),k||(Y.rtcpFeedback=Y.rtcpFeedback.filter(fe=>fe.type!=="nack"||fe.parameter),m=m.filter(fe=>fe.type!=="nack"||fe.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{I!==void 0&&(u["x-google-start-bitrate"]=I),he!==void 0&&(u["x-google-max-bitrate"]=he),ae!==void 0&&(u["x-google-min-bitrate"]=ae);break}}}let f={payload:p.payloadType,config:""};for(let h of Object.keys(u))f.config&&(f.config+=";"),f.config+=`${h}=${u[h]}`;f.config&&this._mediaObject.fmtp.push(f);for(let h of m)this._mediaObject.rtcpFb.push({payload:p.payloadType,type:h.type,subtype:h.parameter})}this._mediaObject.payloads=c.codecs.map(p=>p.payloadType).join(" "),this._mediaObject.ext=[];for(let p of c.headerExtensions)(o.ext??[]).some(u=>u.uri===p.uri)&&this._mediaObject.ext.push({uri:p.uri,value:p.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let p of o.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let p of o.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let r=this._mediaObject.simulcast.list1,n=tc.parseSimulcastStreamList(r);for(let i of n)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=n.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};Ce.AnswerMediaSection=ts;var rs=class extends yt{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:p}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},n?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:d,appdata:p}];for(let f of c.codecs){let h={payload:f.payloadType,codec:Gn(f),rate:f.clockRate};f.channels>1&&(h.encoding=f.channels),this._mediaObject.rtp.push(h);let g={payload:f.payloadType,config:""};for(let _ of Object.keys(f.parameters??{}))g.config&&(g.config+=";"),g.config+=`${_}=${f.parameters[_]}`;g.config&&this._mediaObject.fmtp.push(g);for(let _ of f.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:f.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(f=>f.payloadType).join(" "),this._mediaObject.ext=[];for(let f of c.headerExtensions)this._mediaObject.ext.push({uri:f.uri,value:f.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let l=c.encodings[0],u=l.ssrc,m=l.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],u&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:u,attribute:"cname",value:c.rtcp.cname}),m&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:m,attribute:"cname",value:c.rtcp.cname}),u&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${m}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};Ce.OfferMediaSection=rs;function Gn(s){let t=new RegExp("^(audio|video)/(.+)","i").exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var rt=C(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.RemoteSdp=void 0;var rc=ve(),sc=z(),er=Kn(),nc=ns(),ic=["av1","h264"],tr=new sc.Logger("RemoteSdp"),ss=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${nc.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[o-1].algorithm,hash:r.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){tr.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){tr.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){tr.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}){let o=new er.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),a=o.getObject();a.rtp.find(d=>ic.includes(d.codec.toLowerCase()))||(a.ext=a.ext?.filter(d=>d.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();let o=new er.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(tr.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){let t=new er.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new er.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,rc.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let r=this._midToIndex.get(t);if(r===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{let r=this._midToIndex.get(e.mid);if(r===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[r]=e,this._sdpObject.media[r]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};rr.RemoteSdp=ss});var st=C(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extractRtpCapabilities=oc;Le.extractDtlsParameters=ac;Le.getCname=cc;Le.applyCodecParameters=dc;Le.addHeaderExtension=pc;var Qn=ve();function oc({sdpObject:s}){let e=new Map,t=new Map;for(let n of s.media){let i=n.type;switch(i){case"audio":case"video":break;default:continue}for(let o of n.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of n.fmtp??[]){let a=Qn.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of n.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of n.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function ac({sdpObject:s}){let e=s.setup,t=s.fingerprint;if(!e||!t){let i=(s.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let r;switch(e){case"active":{r="client";break}case"passive":{r="server";break}case"actpass":{r="auto";break}}return{role:r,fingerprints:[{algorithm:t.type,value:t.hash}]}}function cc({offerMediaObject:s}){let e=(s.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function dc({offerRtpParameters:s,answerMediaObject:e}){for(let t of s.codecs){let r=t.mimeType.toLowerCase();if(r!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=Qn.parseParams(i.config);if(r==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function pc({offerMediaObject:s,headerExtensionUri:e,headerExtensionId:t}){s.ext||(s.ext=[]),s.ext.push({uri:e,value:t})}});var nt=C(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.getRtpEncodings=lc;sr.addLegacySimulcast=uc;function lc({offerMediaObject:s,codecs:e}){let t=new Set;for(let i of s.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let r=new Map;for(let i of s.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),r.set(a,c))}for(let i of t)r.set(i,void 0);let n=[];for(let[i,o]of r){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),n.push(a)}return n}function uc({offerMediaObject:s,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(s.ssrcs??[]).find(l=>l.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[r,n]=t.value.split(" "),i=Number(t.id),o;(s.ssrcGroups??[]).some(l=>{if(l.semantics!=="FID")return!1;let u=l.ssrcs.split(/\s+/);return Number(u[0])===i?(o=Number(u[1]),!0):!1});let a=(s.ssrcs??[]).find(l=>l.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,d=[],p=[];for(let l=0;l<e;++l)d.push(i+l),o&&p.push(o+l);s.ssrcGroups=[],s.ssrcs=[],s.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(let l of d)s.ssrcs.push({id:l,attribute:"cname",value:c}),s.ssrcs.push({id:l,attribute:"msid",value:`${r} ${n}`});for(let l=0;l<p.length;++l){let u=d[l],m=p[l];s.ssrcs.push({id:m,attribute:"cname",value:c}),s.ssrcs.push({id:m,attribute:"msid",value:`${r} ${n}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${m}`})}}});var it=C(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.addNackSupportForOpus=hc;bt.addHeaderExtensionSupport=fc;bt.getMsidStreamIdAndTrackId=mc;function hc(s){for(let e of s.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function fc(s,e){let t,r=s.headerExtensions?.find(i=>i.uri===e.uri);if(r){if(r.kind===e.kind)return;t=r.preferredId}if(s.headerExtensions||(s.headerExtensions=[]),t===void 0){t=1;let i=new Set(s.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let n={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};s.headerExtensions.push(n)}function mc(s){if(!s||typeof s!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=s.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var Zn=C(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.Chrome111=void 0;var ue=ve(),gc=G(),_c=z(),St=ce(),vc=X(),wc=Ie(),yc=rt(),Rt=st(),Yn=nt(),is=it(),T=new _c.Logger("Chrome111"),Jn="Chrome111",Xn={OS:65535,MIS:65535},os=class s extends gc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Jn,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{T.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=ue.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(T.debug("getNativeSctpCapabilities()"),{numStreams:Xn})}}static getLocalRtpCapabilities(e,t=[]){let r=Rt.extractRtpCapabilities({sdpObject:e});St.validateAndNormalizeRtpCapabilities(r),is.addNackSupportForOpus(r);for(let n of t)is.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),T.debug("constructor()"),this._direction=e,this._remoteSdp=new yc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(T.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Jn}close(){if(T.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),T.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),T.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});T.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),T.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let P=1;for(let k of r){let I=k.scalabilityMode?(0,wc.parse)(k.scalabilityMode).temporalLayers:3;I>P&&(P=I)}r.forEach((k,I)=>{k.rid=`r${I}`,k.scalabilityMode=`L1T${P}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(d.sender);let p=await this._pc.createOffer(),l=ue.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=St.getSendingRtpParameters(e.kind,f);h.codecs=St.reduceCodecs(h.codecs,o);let g=St.getSendingRemoteRtpParameters(e.kind,f);if(g.codecs=St.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),i?.absCaptureTime){let P=l.media[c.idx];Rt.addHeaderExtension({offerMediaObject:P,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:ue.write(l)}}T.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let _=d.mid;h.mid=_,l=ue.parse(this._pc.localDescription.sdp);let y=l.media[c.idx];if(h.rtcp.cname=Rt.getCname({offerMediaObject:y}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=Yn.getRtpEncodings({offerMediaObject:y,codecs:h.codecs});else if(r.length===1){let P=Yn.getRtpEncodings({offerMediaObject:y,codecs:h.codecs});Object.assign(P[0],r[0]),h.encodings=P}else h.encodings=r;this._remoteSdp.send({offerMediaObject:y,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let x={type:"answer",sdp:this._remoteSdp.getSdp()};return T.debug("send() | calling pc.setRemoteDescription() [answer:%o]",x),await this._pc.setRemoteDescription(x),this._mapMidTransceiver.set(_,d),{localId:_,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),T.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();T.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),T.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();T.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),T.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();T.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?T.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):T.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),T.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();T.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),T.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();T.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};T.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Xn.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ue.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),T.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;T.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:m}=is.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=ue.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);Rt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:ue.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),T.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){T.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){T.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){T.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};T.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),m=ue.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:ue.write(m)},T.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ue.parse(this._pc.localDescription.sdp));let r=Rt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new vc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};nr.Chrome111=os});var ri=C(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.Chrome74=void 0;var Z=ve(),bc=z(),Sc=G(),Ct=ce(),Rc=X(),Cc=Ie(),Tc=rt(),Tt=st(),as=nt(),cs=it(),S=new bc.Logger("Chrome74"),ei="Chrome74",ti={OS:1024,MIS:1024},ds=class s extends Sc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ei,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{S.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Z.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(S.debug("getNativeSctpCapabilities()"),{numStreams:ti})}}static getLocalRtpCapabilities(e,t=[]){let r=Tt.extractRtpCapabilities({sdpObject:e});Ct.validateAndNormalizeRtpCapabilities(r),cs.addNackSupportForOpus(r);for(let n of t)cs.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),S.debug("constructor()"),this._direction=e,this._remoteSdp=new Tc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(S.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return ei}close(){if(S.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),S.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),S.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});S.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),S.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((k,I)=>{k.rid=`r${I}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r}),d=await this._pc.createOffer(),p=Z.parse(d.sdp);p.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let u=s.getLocalRtpCapabilities(p,l),m=this._getSendExtendedRtpCapabilities(u),f=Ct.getSendingRtpParameters(e.kind,m);f.codecs=Ct.reduceCodecs(f.codecs,o);let h=Ct.getSendingRemoteRtpParameters(e.kind,m);h.codecs=Ct.reduceCodecs(h.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:p});let g=!1,_=(0,Cc.parse)((r??[{}])[0].scalabilityMode),y;r?.length===1&&_.spatialLayers>1&&f.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(S.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,p=Z.parse(d.sdp),y=p.media[a.idx],as.addLegacySimulcast({offerMediaObject:y,numStreams:_.spatialLayers}),d={type:"offer",sdp:Z.write(p)}),S.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),i?.absCaptureTime&&(y=p.media[a.idx],Tt.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:h.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Z.write(p)}),await this._pc.setLocalDescription(d);let x=c.mid;if(f.mid=x,p=Z.parse(this._pc.localDescription.sdp),y=p.media[a.idx],f.rtcp.cname=Tt.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,!r)f.encodings=as.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});else if(r.length===1){let k=as.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(k[0],r[0]),g&&(k=[k[0]]),f.encodings=k}else f.encodings=r;if(f.encodings.length>1&&(f.codecs[0].mimeType.toLowerCase()==="video/vp8"||f.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let k of f.encodings)k.scalabilityMode?k.scalabilityMode=`L1T${_.temporalLayers}`:k.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:h,codecOptions:n});let P={type:"answer",sdp:this._remoteSdp.getSdp()};return S.debug("send() | calling pc.setRemoteDescription() [answer:%o]",P),await this._pc.setRemoteDescription(P),this._mapMidTransceiver.set(x,c),{localId:x,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),S.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();S.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),S.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();S.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),S.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();S.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?S.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):S.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),S.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();S.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),S.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();S.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};S.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ti.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Z.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),S.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;S.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:m}=cs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer(),o=Z.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);Tt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:Z.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),S.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){S.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){S.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){S.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};S.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),m=Z.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:Z.write(m)},S.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Z.parse(this._pc.localDescription.sdp));let r=Tt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Rc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};ir.Chrome74=ds});var ai=C(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.Firefox120=void 0;var we=ve(),Ec=G(),kc=z(),si=X(),Et=ce(),xc=Ie(),Pc=rt(),or=st(),ni=nt(),Dc=it(),E=new kc.Logger("Firefox120"),ii="Firefox120",oi={OS:16,MIS:2048},ps=class s extends Ec.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ii,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{E.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),r=document.createElement("canvas");r.getContext("2d");let i=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{r.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=we.parse(o.sdp);return s.getLocalRtpCapabilities(a)}catch(o){try{r.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(E.debug("getNativeSctpCapabilities()"),{numStreams:oi})}}static getLocalRtpCapabilities(e){let t=or.extractRtpCapabilities({sdpObject:e});return Et.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),E.debug("constructor()"),this._direction=e,this._remoteSdp=new Pc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(E.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return ii}close(){if(E.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new si.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),E.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});E.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),E.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((y,x)=>{y.rid=`r${x}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(a.sender);let c=await this._pc.createOffer(),d=we.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=s.getLocalRtpCapabilities(d),l=this._getSendExtendedRtpCapabilities(p),u=Et.getSendingRtpParameters(e.kind,l);u.codecs=Et.reduceCodecs(u.codecs,i);let m=Et.getSendingRemoteRtpParameters(e.kind,l);m.codecs=Et.reduceCodecs(m.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let f=(0,xc.parse)((r??[{}])[0].scalabilityMode);E.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let h=a.mid;u.mid=h,d=we.parse(this._pc.localDescription.sdp);let g=d.media[d.media.length-1];if(u.rtcp.cname=or.getCname({offerMediaObject:g}),u.msid=`${t??this._sendStream.id} ${e.id}`,!r)u.encodings=ni.getRtpEncodings({offerMediaObject:g,codecs:u.codecs});else if(r.length===1){let y=ni.getRtpEncodings({offerMediaObject:g,codecs:u.codecs});Object.assign(y[0],r[0]),u.encodings=y}else u.encodings=r;if(u.encodings.length>1&&(u.codecs[0].mimeType.toLowerCase()==="video/vp8"||u.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let y of u.encodings)y.scalabilityMode?y.scalabilityMode=`L1T${f.temporalLayers}`:y.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,offerRtpParameters:u,answerRtpParameters:m,codecOptions:n});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return E.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:u,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),E.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let r=await this._pc.createOffer();E.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();E.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();E.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?E.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):E.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();E.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();E.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};E.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%oi.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=we.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),E.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;E.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:m}=Dc.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=we.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);or.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l}),i={type:"answer",sdp:we.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),E.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(!p)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){E.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){E.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){E.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};E.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),m=we.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:m}),u={type:"answer",sdp:we.write(m)},E.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=we.parse(this._pc.localDescription.sdp));let r=or.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new si.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};ar.Firefox120=ps});var li=C(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.Safari12=void 0;var ee=ve(),Ic=G(),Lc=z(),kt=ce(),Mc=X(),Oc=Ie(),Ac=rt(),xt=st(),ci=nt(),ls=it(),R=new Lc.Logger("Safari12"),di="Safari12",pi={OS:65535,MIS:65535},us=class s extends Ic.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:di,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{R.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=ee.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(R.debug("getNativeSctpCapabilities()"),{numStreams:pi})}}static getLocalRtpCapabilities(e,t=[]){let r=xt.extractRtpCapabilities({sdpObject:e});kt.validateAndNormalizeRtpCapabilities(r),ls.addNackSupportForOpus(r);for(let n of t)ls.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),R.debug("constructor()"),this._direction=e,this._remoteSdp=new Ac.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",p=>{this.emit("@icecandidateerror",p)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(R.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return di}close(){if(R.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),R.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),R.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});R.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),R.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(d.sender);let p=await this._pc.createOffer(),l=ee.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=kt.getSendingRtpParameters(e.kind,f);h.codecs=kt.reduceCodecs(h.codecs,o);let g=kt.getSendingRemoteRtpParameters(e.kind,f);g.codecs=kt.reduceCodecs(g.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let y=(0,Oc.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(R.debug("send() | enabling legacy simulcast"),l=ee.parse(p.sdp),_=l.media[c.idx],ci.addLegacySimulcast({offerMediaObject:_,numStreams:r.length}),p={type:"offer",sdp:ee.write(l)}),i?.absCaptureTime&&(_=l.media[c.idx],xt.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:ee.write(l)}),R.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let x=d.mid;if(h.mid=x,l=ee.parse(this._pc.localDescription.sdp),_=l.media[c.idx],h.rtcp.cname=xt.getCname({offerMediaObject:_}),h.msid=`${t??this._sendStream.id} ${e.id}`,h.encodings=ci.getRtpEncodings({offerMediaObject:_,codecs:h.codecs}),r)for(let k=0;k<h.encodings.length;++k)r[k]&&Object.assign(h.encodings[k],r[k]);if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let k of h.encodings)k.scalabilityMode?k.scalabilityMode=`L1T${y.temporalLayers}`:k.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let P={type:"answer",sdp:this._remoteSdp.getSdp()};return R.debug("send() | calling pc.setRemoteDescription() [answer:%o]",P),await this._pc.setRemoteDescription(P),this._mapMidTransceiver.set(x,d),{localId:x,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;R.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();R.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),R.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();R.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),R.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();R.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?R.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):R.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),R.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();R.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),R.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();R.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};R.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%pi.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ee.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),R.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;R.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:m}=ls.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=ee.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);xt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:ee.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),R.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(!p)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){R.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){R.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){R.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};R.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),m=ee.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:ee.write(m)},R.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ee.parse(this._pc.localDescription.sdp));let r=xt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Mc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};cr.Safari12=us});var fi=C(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.ReactNative106=void 0;var te=ve(),Nc=G(),jc=z(),Pt=ce(),Fc=X(),qc=Ie(),$c=rt(),Dt=st(),hs=nt(),fs=it(),b=new jc.Logger("ReactNative106"),ui="ReactNative106",hi={OS:65535,MIS:65535},ms=class s extends Nc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ui,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{b.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=te.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(b.debug("getNativeSctpCapabilities()"),{numStreams:hi})}}static getLocalRtpCapabilities(e,t=[]){let r=Dt.extractRtpCapabilities({sdpObject:e});Pt.validateAndNormalizeRtpCapabilities(r),fs.addNackSupportForOpus(r);for(let n of t)fs.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),b.debug("constructor()"),this._direction=e,this._remoteSdp=new $c.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(b.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return ui}close(){if(b.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),b.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),b.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});b.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),b.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((I,he)=>{I.rid=`r${he}`});let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(d.sender);let p=await this._pc.createOffer(),l=te.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=Pt.getSendingRtpParameters(e.kind,f);h.codecs=Pt.reduceCodecs(h.codecs,o);let g=Pt.getSendingRemoteRtpParameters(e.kind,f);g.codecs=Pt.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let _=!1,y=(0,qc.parse)((r??[{}])[0].scalabilityMode),x;r?.length===1&&y.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(b.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,l=te.parse(p.sdp),x=l.media[c.idx],hs.addLegacySimulcast({offerMediaObject:x,numStreams:y.spatialLayers}),p={type:"offer",sdp:te.write(l)}),i?.absCaptureTime&&(x=l.media[c.idx],Dt.addHeaderExtension({offerMediaObject:x,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(I=>I.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:te.write(l)}),b.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let P=d.mid??void 0;if(P||b.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),h.mid=P,l=te.parse(this._pc.localDescription.sdp),x=l.media[c.idx],h.rtcp.cname=Dt.getCname({offerMediaObject:x}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=hs.getRtpEncodings({offerMediaObject:x,codecs:h.codecs});else if(r.length===1){let I=hs.getRtpEncodings({offerMediaObject:x,codecs:h.codecs});Object.assign(I[0],r[0]),_&&(I=[I[0]]),h.encodings=I}else h.encodings=r;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let I of h.encodings)I.scalabilityMode?I.scalabilityMode=`L1T${y.temporalLayers}`:I.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:x,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let k={type:"answer",sdp:this._remoteSdp.getSdp()};return b.debug("send() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),P||(P=d.mid,h.mid=P),this._mapMidTransceiver.set(P,d),{localId:P,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;b.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();b.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),b.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();b.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),b.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();b.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?b.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):b.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),b.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();b.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),b.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();b.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};b.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%hi.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=te.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),b.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;b.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:m}=fs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=te.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);Dt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:te.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),b.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){b.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){b.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){b.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};b.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),m=te.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:te.write(m)},b.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=te.parse(this._pc.localDescription.sdp));let r=Dt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Fc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};dr.ReactNative106=ms});var vi=C(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.Device=void 0;ot.detectDevice=mi;ot.detectDeviceAsync=gi;var Uc=z(),zc=G(),Te=X(),pr=ke(),K=ce(),Bc=Fn(),Vc=Zn(),Wc=ri(),Hc=ai(),Gc=li(),Kc=fi(),w=new Uc.Logger("Device");function mi(s,e){return w.debug("detectDevice()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),_i(s,e)}async function gi(s,e){return w.debug("detectDeviceAsync()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),_i(s,e)}var gs=class s{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new zc.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(w.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await gi(),!e))throw new Te.UnsupportedError("device not supported");return new s({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(w.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)w.debug("constructor() | handler given: %s",e);else if(e=mi(),e)w.debug("constructor() | detected handler: %s",e);else throw new Te.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Vc.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=Wc.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=Hc.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=Gc.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Kc.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new Te.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new Te.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Te.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(w.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Te.InvalidStateError("already loaded");let r=pr.clone(e);K.validateAndNormalizeRtpCapabilities(r);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=pr.clone(await n({direction:"recvonly"}));w.debug("load() | got native receiving RTP capabilities:%o",o),K.validateAndNormalizeRtpCapabilities(o);let a=pr.clone(await n({direction:"sendonly"}));w.debug("load() | got native sending RTP capabilities:%o",a),K.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=p=>pr.clone(K.getExtendedRtpCapabilities(p,r,t));let c=K.getExtendedRtpCapabilities(o,r,!1);this._recvRtpCapabilities=K.getRecvRtpCapabilities(c),w.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),K.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let d=K.getExtendedRtpCapabilities(a,r,t);this._sendRtpCapabilities=K.getSendRtpCapabilities(d),w.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),K.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=K.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=K.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),K.validateSctpCapabilities(this._sctpCapabilities),w.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),w.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new Te.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return w.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return w.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof r!="object")throw new TypeError("missing iceParameters");if(Array.isArray(n)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(p&&typeof p!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new Te.InvalidStateError("not loaded");let l=new Bc.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}};ot.Device=gs;function _i(s,e){w.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',s,e);let t=Qc(s,e);if(t){if(t>=111)return w.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return w.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";w.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let r=Yc(s);if(r){if(r>=120)return w.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";w.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let n=Jc(s);if(n){if(n>=605)return w.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";w.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Xc(s);if(i){if(i>=605)return w.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";w.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(It()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return w.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";w.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}w.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',s,e)}function Qc(s,e){if(w.debug("getChromiumMajorVersion()"),lr(s,e)){w.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(It()){w.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let n=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(n){let i=Number(n.version);return w.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=s?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return w.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${r}`),r}w.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function Yc(s){if(w.debug("getFirefoxMajorVersion()"),lr(s)){w.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(It()){w.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=s?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return w.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}w.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function Jc(s){if(w.debug("getMacOSWebKitMajorVersion()"),lr(s)){w.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(It()){w.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(s&&/\bSafari\b/i.test(s)&&!/\bChrome\b/i.test(s)&&!/\bChromium\b/i.test(s)&&!/\bFirefox\b/i.test(s))){w.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=s.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return w.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${r}`),r}w.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Xc(s){if(w.debug("getIOSWebKitMajorVersion()"),!lr(s)){w.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(It()){w.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=s?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return w.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}w.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function lr(s,e){return w.debug("isIOS()"),e?.platform==="iOS"?(w.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(w.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):s&&/iPad|iPhone|iPod/.test(s)?(w.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(w.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(w.debug("isIOS() | this is not iOS => false"),!1)}function It(){return w.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(w.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(w.debug("isReactNative() | this is not React-Native => false"),!1)}});var yi=C(wi=>{"use strict";var Me=256,hr=[],ur;for(;Me--;)hr[Me]=(Me+256).toString(16).substring(1);function Zc(){var s=0,e,t="";if(!ur||Me+16>256){for(ur=Array(s=256);s--;)ur[s]=256*Math.random()|0;s=Me=0}for(;s<16;s++)e=ur[Me+s],s==6?t+=hr[e&15|64]:s==8?t+=hr[e&63|128]:t+=hr[e],s&1&&s>1&&s<11&&(t+="-");return Me++,t}wi.v4=Zc});var bi=C(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.FakeEventTarget=void 0;var _s=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};fr.FakeEventTarget=_s});var Si=C(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.FakeEvent=void 0;var vs=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};mr.FakeEvent=vs});var Ri=C(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.clone=ed;function ed(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}});var Ti=C(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.FakeMediaStreamTrack=void 0;var Ci=yi(),td=bi(),at=Si(),gr=Ri(),ys=class s extends td.FakeEventTarget{#m;#l;#u;#e;#r;#t;#s;#h;#n;#f;#i;#o=null;#a=null;#c=null;#d=null;#p=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:o,readyState:a,capabilities:c,constraints:d,settings:p,data:l}){super(),this.#m=t??(0,Ci.v4)(),this.#l=e,this.#u=r??"",this.#s=n??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#n=d??{},this.#f=p??{},this.#i=l??{}}get id(){return this.#m}get kind(){return this.#l}get label(){return this.#u}get contentHint(){return this.#s}set contentHint(e){this.#s=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new at.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#p}set onstopped(e){this.#p&&this.removeEventListener("stopped",this.#p),this.#p=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new at.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new s({id:e??(0,Ci.v4)(),kind:this.#l,label:this.#u,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,gr.clone)(this.#h),constraints:(0,gr.clone)(this.#n),settings:(0,gr.clone)(this.#f),data:t??(0,gr.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#n}async applyConstraints(e={}){return this.#n=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new at.FakeEvent("stopped")),this.dispatchEvent(new at.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new at.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new at.FakeEvent("unmute")))}};_r.FakeMediaStreamTrack=ys});var Ei=C(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.FakeEventTarget=void 0;var bs=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};vr.FakeEventTarget=bs});var Pi=C(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.FakeHandler=void 0;var rd=Ti(),sd=G(),nd=z(),ct=ke(),Ss=ce(),xi=X(),id=Ei(),$=new nd.Logger("FakeHandler"),ki="FakeHandler",Rs=class s extends sd.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${ct.generateRandomNumber()}`;_defaultSendStreamId=`${ct.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:ki,factory:t=>new s(t,e),getNativeRtpCapabilities:async({direction:t})=>($.debug("getNativeRtpCapabilities() [direction:%o]",t),s.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>($.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Ss.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),$.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return ki}close(){$.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),$.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),$.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),$.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=s.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Ss.getSendingRtpParameters(e.kind,a);c.codecs=Ss.reduceCodecs(c.codecs,i);let d=c.codecs.some(l=>/.+\/rtx$/i.test(l.mimeType));c.mid=`mid-${ct.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(let l of r)l.ssrc=ct.generateRandomNumber(),d&&(l.rtx={ssrc:ct.generateRandomNumber()});c.encodings=r,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let p=this._nextLocalId++;return this._tracks.set(p,e),{localId:String(p),rtpParameters:c}}async stopSending(e){if($.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?$.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):$.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),$.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),$.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),$.debug("sendDataChannel()");let t=new wr({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),r={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:r}}async receive(e){this.assertNotClosed();let t=[];for(let r of e){let{trackId:n,kind:i}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),$.debug("receive() [trackId:%s, kind:%s]",n,i);let o=this._nextLocalId++,a=new rd.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)$.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),$.debug("receiveDataChannel()"),{dataChannel:new wr({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let r=ct.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((n,i)=>this.emit("@connect",{dtlsParameters:r},n,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new xi.InvalidStateError("method called in a closed handler")}};yr.FakeHandler=Rs;var wr=class extends id.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:n=null,label:i="",protocol:o=""}){super(),$.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new xi.InvalidStateError("not open")}}});var Di=C(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.generateRouterRtpCapabilities=od;ie.generateNativeRtpCapabilities=ad;ie.generateNativeSctpCapabilities=cd;ie.generateLocalDtlsParameters=dd;ie.generateTransportRemoteParameters=pd;ie.generateProducerRemoteParameters=ld;ie.generateConsumerRemoteParameters=ud;ie.generateDataProducerRemoteParameters=hd;ie.generateDataConsumerRemoteParameters=fd;var V=ke();function Q(){return String(V.generateRandomNumber())}function od(){return V.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function ad(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function cd(){return V.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function dd(){return V.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function pd(){return{id:Q(),iceParameters:V.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:V.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:V.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:V.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function ld(){return V.deepFreeze({id:Q()})}function ud({id:s,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:s??Q(),producerId:Q(),kind:"audio",rtpParameters:V.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:s??Q(),producerId:Q(),kind:"audio",rtpParameters:V.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:s??Q(),producerId:Q(),kind:"video",rtpParameters:V.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:s??Q(),producerId:Q(),kind:"video",rtpParameters:V.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function hd(){return V.deepFreeze({id:Q()})}function fd({id:s}={}){return{id:s??Q(),dataProducerId:Q(),sctpStreamParameters:V.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var ns=C(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.debug=A.testFakeParameters=A.FakeHandler=A.enhancedEvents=A.ortc=A.parseScalabilityMode=A.detectDeviceAsync=A.detectDevice=A.Device=A.version=A.types=void 0;var md=gt();A.debug=md.default;A.types=en();A.version="3.20.0";var Cs=vi();Object.defineProperty(A,"Device",{enumerable:!0,get:function(){return Cs.Device}});Object.defineProperty(A,"detectDevice",{enumerable:!0,get:function(){return Cs.detectDevice}});Object.defineProperty(A,"detectDeviceAsync",{enumerable:!0,get:function(){return Cs.detectDeviceAsync}});var gd=Ie();Object.defineProperty(A,"parseScalabilityMode",{enumerable:!0,get:function(){return gd.parse}});A.ortc=ce();A.enhancedEvents=G();var _d=Pi();Object.defineProperty(A,"FakeHandler",{enumerable:!0,get:function(){return _d.FakeHandler}});A.testFakeParameters=Di()});var Li=C((pl,Ts)=>{"use strict";var vd=Object.prototype.hasOwnProperty,W="~";function Lt(){}Object.create&&(Lt.prototype=Object.create(null),new Lt().__proto__||(W=!1));function wd(s,e,t){this.fn=s,this.context=e,this.once=t||!1}function Ii(s,e,t,r,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new wd(t,r||s,n),o=W?W+e:e;return s._events[o]?s._events[o].fn?s._events[o]=[s._events[o],i]:s._events[o].push(i):(s._events[o]=i,s._eventsCount++),s}function br(s,e){--s._eventsCount===0?s._events=new Lt:delete s._events[e]}function U(){this._events=new Lt,this._eventsCount=0}U.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)vd.call(t,r)&&e.push(W?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};U.prototype.listeners=function(e){var t=W?W+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,i=r.length,o=new Array(i);n<i;n++)o[n]=r[n].fn;return o};U.prototype.listenerCount=function(e){var t=W?W+e:e,r=this._events[t];return r?r.fn?1:r.length:0};U.prototype.emit=function(e,t,r,n,i,o){var a=W?W+e:e;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,p,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,n),!0;case 5:return c.fn.call(c.context,t,r,n,i),!0;case 6:return c.fn.call(c.context,t,r,n,i,o),!0}for(l=1,p=new Array(d-1);l<d;l++)p[l-1]=arguments[l];c.fn.apply(c.context,p)}else{var u=c.length,m;for(l=0;l<u;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,r);break;case 4:c[l].fn.call(c[l].context,t,r,n);break;default:if(!p)for(m=1,p=new Array(d-1);m<d;m++)p[m-1]=arguments[m];c[l].fn.apply(c[l].context,p)}}return!0};U.prototype.on=function(e,t,r){return Ii(this,e,t,r,!1)};U.prototype.once=function(e,t,r){return Ii(this,e,t,r,!0)};U.prototype.removeListener=function(e,t,r,n){var i=W?W+e:e;if(!this._events[i])return this;if(!t)return br(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!r||o.context===r)&&br(this,i);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==t||n&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:br(this,i)}return this};U.prototype.removeAllListeners=function(e){var t;return e?(t=W?W+e:e,this._events[t]&&br(this,t)):(this._events=new Lt,this._eventsCount=0),this};U.prototype.off=U.prototype.removeListener;U.prototype.addListener=U.prototype.on;U.prefixed=W;U.EventEmitter=U;typeof Ts<"u"&&(Ts.exports=U)});var fp={};Us(fp,{App:()=>Zi,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>Ns,RequestAbortError:()=>ye,RequestCancelledError:()=>ft,RequestDocSyncError:()=>ut,RequestError:()=>oe,RequestTimeoutError:()=>lt,Session:()=>mt,StreamDirectionConflict:()=>ht,createStore:()=>ro,videoStream:()=>so});module.exports=Bs(fp);var Fe=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let n=this._handlers.get(r.channel);if(n)for(let i of n)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r.delete(t),r.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},qe=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,n]of this._handlers)for(let i of n)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,n=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?n+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?n+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let n=this._target?.on(e,t);return n&&this._targetUnsubscribes.push(n),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),n?.(),n&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==n))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var zi=Se(ns());var Es=Se(Li(),1);function Rr(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Oi(){return Rr()?"Chrome111":void 0}var yd=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],Sr=null;function Ai(){return Rr()?Sr||(Sr=bd(),Sr):Promise.resolve()}async function bd(){let s=globalThis;if(typeof s.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;s.WebSocket=t}catch(e){Mi("WebSocket",e)}if(typeof s.RTCPeerConnection>"u")try{let e=await import("werift");Sd(s,e)}catch(e){Mi("werift",e)}}function Sd(s,e){let{RTCPeerConnection:t,useH264:r,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:p}=e,l=()=>({video:[r(),n()],audio:[i()]}),u=()=>({video:[o(),a(),c(),d(),p()],audio:[o(),c(),d()]});class m extends t{constructor(h){super({...h,codecs:h?.codecs??l(),headerExtensions:h?.headerExtensions??u()})}}s.RTCPeerConnection=m;for(let f of yd)e[f]!=null&&typeof s[f]>"u"&&(s[f]=e[f])}function Mi(s,e){let t=e instanceof Error?e.message:String(e);console.warn(`[urun-sh/core] Node WebRTC support: optional dependency "${s}" unavailable (${t}). Realtime media will not work in this Node process; install "${s}" to enable it. Doc/KV transport over WebSocket is unaffected.`)}var Ni="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Rd(s){let e=globalThis.crypto,t=new Uint8Array(s);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let r=0;r<s;r++)t[r]=Math.floor(Math.random()*256);return t}function Cr(s=16){let e=Rd(s),t="";for(let r=0;r<s;r++)t+=Ni[e[r]%Ni.length];return t}var ji=[1e3,2e3,4e3,8e3,3e4],Fi=5,Cd=15e3,Td=2e3,Ed=6e3,kd=2,xd=750,Pd=3,qi=[1e3,2e3,4e3],Dd=15e3,ks="control",Bi=0,Vi=1,xs=64;function Id(s,e){if(s===ks){let n=new Uint8Array(1+e.length);return n[0]=Bi,n.set(e,1),n}let t=new TextEncoder().encode(s);if(t.length<1||t.length>xs)throw new Error(`[urun] doc key length out of range (1..${xs}): ${t.length}`);let r=new Uint8Array(3+t.length+e.length);return r[0]=Vi,r[1]=t.length>>>8&255,r[2]=t.length&255,r.set(t,3),r.set(e,3+t.length),r}function Ld(s){if(s.length===0)return{docKey:ks,payload:s.slice()};let e=s[0];if(e===Bi)return{docKey:ks,payload:s.slice(1)};if(e===Vi){if(s.length<3)return null;let t=s[1]<<8|s[2];if(t<1||t>xs||s.length<3+t)return null;let r=new TextDecoder().decode(s.subarray(3,3+t)),n=s.slice(3+t);return{docKey:r,payload:n}}return null}var Md={queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",allocated:"connecting",connecting:"connecting",live:"live",running:"live",failed:"error",rejected:"error",expired:"error",cancelled:"ended",canceled:"ended",closed:"ended"},Od=8e3,$i=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],dt=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Es.default;_ws=null;_device=null;_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvTransportMsg=null;_lastConsumeMsg=null;_recvConnectWatchdog=null;_recvTcpFailoverDone=!1;_phase={name:"idle"};_requestId;_liveReached=!1;_mediaMonitorTimer=null;_lastInboundTotal=0;_mediaEverFlowed=!1;_lastInboundAdvanceAt=0;_mediaDeathHandled=!1;_currentEpoch=0;_consumerId=null;_pendingStreamSubscribes=new Set;get consumerId(){return this._consumerId===null&&(this._consumerId=Ad()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws?.readyState===WebSocket.OPEN}getTrackByName(e){let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let r of this._tracks.values())if(r.kind===e&&r.readyState!=="ended")return r;return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen)throw new Error("TransportSession: cannot change connection while connected");this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,r=jd(t);r!==void 0&&this.setIncarnation(r)}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=e,t&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended")return!1;let r=e.status_epoch??e.statusEpoch,n=typeof r=="number"?r:Number(r);return Number.isFinite(n)?n<this._currentEpoch:!1}async connect(e){this._lastStartOptions=e,this._intentionalDisconnect=!1;let t=++this._generation;this._state!=="reconnecting"&&this._state!=="renegotiating"&&this._setState("connecting");let r=null,n=()=>t!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let c of this._connectUrls()){i();try{return await this._connectOnce(c,t,e),!0}catch(d){r=d instanceof Error?d:new Error(String(d)),this._cleanupSocket()}}return!1},a=this._resolveConnection?kd:1;for(let c=0;c<a;c++)if(c>0&&(await Ui(xd),i()),await o())return;if(this._resolveConnection)for(let c=0;c<Pd;c++){this._setState("reconnecting"),await Ui(qi[Math.min(c,qi.length-1)]),i();try{let d=await this._resolveConnection();i(),this.setAuth({jwt:d.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:d.url,sessionId:d.sessionId,iceServers:d.iceServers??this._options.iceServers})}catch(d){if(n())throw new Error("TransportSession: connect cancelled");r=d instanceof Error?d:new Error(String(d));continue}if(await o())return}throw this._setState("failed"),r??new Error("TransportSession: connect failed")}disconnect(){if(this._generation+=1,this._intentionalDisconnect=!0,this._stopMediaMonitor(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){this._clearRecvWatchdog();try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._ws){let e=this._ws;this._ws=null;try{e.close(1e3,"intentional disconnect")}catch{}}this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("ended"),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendDocSync(e,t){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(Id(e,t))}onDocSync(e,t){let r=(n,i)=>{n===e&&t(i)};return this.on("docSync",r)}onDocSyncReady(e){return this.on("docSyncReady",e)}_emitDocSyncFrame(e){let t=Ld(e);if(!t){console.warn("[urun] doc-sync: unknown/malformed typed-v1 frame; dropped");return}this._emitter.emit("docSync",t.docKey,t.payload)}async addTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._audioProducer=await this._sendTransport.produce({track:e,codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}})}removeTrack(){this._audioProducer&&(this._send({type:"stopAudio"}),this._audioProducer.close(),this._audioProducer=null)}async addVideoTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._videoProducer=await this._sendTransport.produce({track:e})}stopVideo(){this._videoProducer&&(this._send({type:"stopVideo"}),this._videoProducer.close(),this._videoProducer=null)}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}subscribeStream(e){this._pendingStreamSubscribes.add(e),this._sendStreamSubscribe(e)}unsubscribeStream(e){this._pendingStreamSubscribes.delete(e),this._send({t:"stream.unsubscribe",name:e,consumerId:this.consumerId})}_sendStreamSubscribe(e){this._send({t:"stream.subscribe",name:e,consumerId:this.consumerId})}_flushStreamSubscribes(){for(let e of this._pendingStreamSubscribes)this._sendStreamSubscribe(e)}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break}}_onStatus(e){let t=e.request_id??e.requestId;if(t&&(this._requestId=t),this._liveReached)return;let r=typeof e.status=="string"?e.status:void 0,n=(r&&Md[r])??"provisioning",i=e.queue_position??e.queuePosition,o=e.queue_depth??e.queueDepth,a=typeof i=="number"&&typeof o=="number";if(n==="error"){this._setPhase("error",{error:{reason:r??"admission failed",code:r}});return}if(n==="ended"){this._setPhase("ended");return}if(n==="queued"){this._setPhase("queued",a?{queue:{position:i,depth:o}}:void 0);return}if(n==="connecting"){this._setPhase("connecting");return}this._setPhase("provisioning")}async _onRouterCapabilities(e){Rr()&&await Ai();let t=Oi(),r=new zi.Device(t?{handlerName:t}:void 0);await r.load({routerRtpCapabilities:e}),this._device=r,this._send({type:"rtpCapabilities",rtpCapabilities:r.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&(this._recvTransportMsg=e,this._recvTcpFailoverDone=!1,this._buildRecvTransport(e,!1))}_buildRecvTransport(e,t){if(!this._device)return;let r=e.iceCandidates,n=t?r.filter(a=>a.protocol==="tcp"):r,i=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:n,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??$i}),o=this._generation;i.on("connect",({dtlsParameters:a},c,d)=>{try{this._send({type:"connectTransport",transportId:i.id,dtlsParameters:a}),c()}catch(p){d(p)}}),i.on("connectionstatechange",a=>{if(o===this._generation){if(a==="connected"){this._clearRecvWatchdog();return}if(!(this._intentionalDisconnect&&a==="closed")&&(a==="failed"||a==="disconnected")){if(!t&&!this._recvTcpFailoverDone){this._failoverRecvToTcp(`state:${a}`);return}a==="failed"&&this._emitError(new Error(`media transport ${a}`),a)}}}),this._recvTransport=i,this._clearRecvWatchdog(),t||(this._recvConnectWatchdog=setTimeout(()=>{o===this._generation&&this._recvTransport?.connectionState!=="connected"&&this._failoverRecvToTcp("timeout")},Od))}_clearRecvWatchdog(){this._recvConnectWatchdog&&(clearTimeout(this._recvConnectWatchdog),this._recvConnectWatchdog=null)}_failoverRecvToTcp(e){if(this._recvTcpFailoverDone||this._intentionalDisconnect)return;let t=this._recvTransportMsg;if(!this._device||!t)return;if(!t.iceCandidates.some(n=>n.protocol==="tcp")){this._emitter.emit("error",new Error(`media transport failed (${e}); no TCP candidate`));return}if(this._recvTcpFailoverDone=!0,this._clearRecvWatchdog(),this._recvTransport)try{this._recvTransport.close()}catch{}this._buildRecvTransport(t,!0),this._lastConsumeMsg&&this._onConsume(this._lastConsumeMsg)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??$i}),r=this._generation;t.on("connect",({dtlsParameters:n},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:n}),i()}catch(a){o(a)}}),t.on("produce",({kind:n,rtpParameters:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=setTimeout(()=>{let d=this._pendingProduce;!d||d.timeoutId!==c||(this._pendingProduce=null,d.reject(new Error("Produce timed out")))},15e3);this._pendingProduce={timeoutId:c,resolve:d=>{o({id:d})},reject:a};try{this._send({type:"produce",kind:n,rtpParameters:i})}catch(d){this._pendingProduce?.timeoutId===c&&(this._pendingProduce=null,clearTimeout(c)),a(d)}}),t.on("connectionstatechange",n=>{r===this._generation&&(this._intentionalDisconnect&&n==="closed"||(n==="failed"||n==="closed")&&this._emitError(new Error(`media send transport ${n}`),n))}),this._sendTransport=t,this._emitter.emit("audioTransportReady")}async _onConsume(e){if(!this._recvTransport)return;this._lastConsumeMsg=e;let t=this._generation,r=await this._recvTransport.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});this._consumers.set(r.id,r),this._tracks.set(r.track.id,r.track);let n=e.streamName??e.label;n&&this._tracksByName.set(n,r.track),this._liveReached||this._setPhase("live"),this._emitter.emit("track",r.track),r.track.addEventListener("ended",()=>{t!==this._generation||this._intentionalDisconnect||this._renegotiate()},{once:!0}),this._send({type:"resumeConsumer",consumerId:r.id}),this._startMediaMonitor()}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?Td:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Ed:e}_startMediaMonitor(){let e=this._mediaPollMs();if(e<=0||this._mediaMonitorTimer)return;this._lastInboundTotal=0,this._mediaEverFlowed=!1,this._lastInboundAdvanceAt=Date.now(),this._mediaDeathHandled=!1;let t=this._generation;this._mediaMonitorTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._sampleMediaLiveness(t)},e)}_stopMediaMonitor(){this._mediaMonitorTimer&&(clearInterval(this._mediaMonitorTimer),this._mediaMonitorTimer=null)}async _sampleMediaLiveness(e){if(this._consumers.size===0)return;let t=0;for(let n of this._consumers.values())t+=await Nd(n);if(e!==this._generation||this._intentionalDisconnect)return;let r=Date.now();if(t>this._lastInboundTotal){this._lastInboundTotal=t,this._lastInboundAdvanceAt=r,t>0&&(this._mediaEverFlowed=!0);return}this._mediaEverFlowed&&(this._mediaDeathHandled||r-this._lastInboundAdvanceAt>=this._mediaStallTimeoutMs()&&(this._mediaDeathHandled=!0,this._renegotiate()))}_renegotiate(){this._intentionalDisconnect||this._reconnectTimer||(this._stopMediaMonitor(),this._setState("renegotiating"),this._attemptReconnect())}_attemptReconnect(e){if(this._intentionalDisconnect||this._reconnectTimer)return;if(this._reconnectAttempts>=Fi){this._setState("failed"),this._emitError(new Error(`Failed after ${Fi} attempts`));return}let t=ji[Math.min(this._reconnectAttempts,ji.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._cleanupMedia();try{await this.connect(e??this._lastStartOptions)}catch(r){if(r instanceof Error&&r.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},t)}_connectUrls(){let e=[],t=r=>{if(!r)return;let n=/\/ws\/rtc\/[^/?#]+/.test(r),i=this._sessionId&&!n?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r;e.includes(i)||e.push(i)};t(this._options.url);for(let r of this._options.fallbackUrls??[])t(r);return e}_connectOnce(e,t,r){return new Promise((n,i)=>{let o=!1,a=!1,c=null,d=new WebSocket(e);d.binaryType="arraybuffer",this._ws=d;let p=l=>{a||this._ws!==d||t!==this._generation||(a=!0,c&&clearTimeout(c),i(l))};c=setTimeout(()=>{try{d.close()}catch{}p(new Error("TransportSession: connect timed out"))},Cd),d.onopen=()=>{a||t!==this._generation||(o=!0,c&&clearTimeout(c),this._multiplexer=new Fe(d),d.send(JSON.stringify(this._startMessage(r))),this._emitter.emit("docSyncReady"),this._flushStreamSubscribes(),this._scheduleReconnectBudgetReset(),this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,n())},d.onerror=()=>{o||p(new Error("WebSocket connection error"))},d.onclose=()=>{if(!(this._ws!==d||t!==this._generation)){if(this._clearReconnectBudgetReset(),!o){p(new Error("WebSocket closed before connecting"));return}c&&clearTimeout(c),this._setState("disconnected"),this._intentionalDisconnect||(this._emitter.emit("disconnected"),this._attemptReconnect(r))}},d.onmessage=l=>{if(!(this._ws!==d||t!==this._generation)){if(typeof l.data=="string")try{this._handleMessage(JSON.parse(l.data))}catch(u){this._emitter.emit("error",u instanceof Error?u:new Error(String(u)))}else if(l.data instanceof ArrayBuffer)this._emitDocSyncFrame(new Uint8Array(l.data));else if(ArrayBuffer.isView(l.data)){let u=l.data;this._emitDocSyncFrame(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}}}})}_startMessage(e){let t={type:"start",docFraming:"typed-v1",video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null;try{e.close()}catch{}}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},Dd))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupMedia(){this._stopMediaMonitor();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._clearRecvWatchdog(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(JSON.stringify(e))}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_setPhase(e,t){e==="live"&&(this._liveReached=!0);let r={name:e};t?.queue&&(r.queue=t.queue),this._requestId&&(r.requestId=this._requestId),this._sessionId&&(r.sessionId=this._sessionId),t?.error&&(r.error=t.error),this._phase=r,this._emitter.emit("phase",r)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t}}),this._emitter.emit("error",e)}};function Ui(s){return new Promise(e=>setTimeout(e,s))}function Ad(){return Cr()}async function Nd(s){if(typeof s.getStats!="function")return 0;let e;try{e=await s.getStats()}catch{return 0}let t=0,r=n=>{if(!n||typeof n!="object")return;let i=n;if(i.type==="inbound-rtp"){let o=typeof i.bytesReceived=="number"?i.bytesReceived:0,a=typeof i.packetsReceived=="number"?i.packetsReceived:0;t+=o+a}};if(e instanceof Map)for(let n of e.values())r(n);else if(Array.isArray(e))for(let n of e)r(n);else e&&typeof e.forEach=="function"&&e.forEach(r);return t}function jd(s){if(!s||typeof s!="object")return;let e=s.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var Fd="session-api.prod.cloud.urun.sh",qd=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Tr(s){return s.trim().replace(/\/+$/,"")}function Wi(s,e){let t=[],r=n=>{if(!n)return;let i=Tr(n);i&&!t.includes(i)&&t.push(i)};r(s);for(let n of e??[])r(n);for(let n of Kd(s))r(n);return t}var $d=120,Ud=1e3,zd=3;function Bd(s){if(!s)return null;try{let e=new URL(s),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return Tr(`${e.origin}${t}`)}catch{return null}}async function Hi(s){let e=Wi(s.baseUrl,s.fallbackUrls),t=null,r=e.length>1;for(let n of e)try{return await Vd(n,s,{pollAttempts:$d,retryAfterLimitMs:r?Ud:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof Oe)throw t}throw t??new Error("[urun] session allocation failed")}async function Vd(s,e,t){let r,n,i,o=s,a=0,c=new Set;for(let d=0;d<t.pollAttempts;d++){n=i??await Ds(e),i=void 0;let p=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}`,{headers:Ps(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ps(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Wd(e))});if(!r&&(p.status===307||p.status===308)){let f=Bd(p.headers.get("location"));if(f&&f!==o&&a<zd){a+=1,o=f;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let l=await Ki(p);if(p.ok&&(l.status==="allocated"||!l.status&&!!l.session_id)&&!!l.session_id){let f=l.session_id;if(!l.ws_url)throw new Oe(`[urun] gateway allocated session ${f} without ws_url`);if(!Qi(l.ws_url))throw new Oe(`[urun] gateway allocated session ${f} with non-absolute ws_url`);return{baseUrl:o,sessionId:f,wsUrl:l.ws_url,response:l}}if(p.status===202||l.status==="pending"||l.status==="queued"||l.queued){if(r=l.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");await Gd(Hd(p,l,t.retryAfterLimitMs));continue}if((p.status===401||p.status===403)&&e.getAccessToken){let f=n??"";c.add(f);let h=await Ds(e,{forceRefresh:!0,reason:"unauthorized"});if(h&&!c.has(h)){i=h,r=void 0;continue}}let m=l.error_message||l.error_code||`HTTP ${p.status}`;throw new Error(`[urun] session allocation failed at ${o}: ${m}`)}throw new Error(`[urun] timed out waiting for session allocation at ${o}`)}function Ps(s,e){let t={"X-Tenant-Id":s.orgId,"X-Auth-Provider":s.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Ds(s,e){return s.getAccessToken?await s.getAccessToken(e)??void 0:s.jwt}function Wd(s){return{app:s.app,function:s.functionName,gpus:1,idempotency_key:s.idempotencyKey}}async function Gi(s){let e=Wi(s.baseUrl,s.fallbackUrls),t=null;for(let r of e)try{let n={baseUrl:r,app:"",functionName:"",orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider,idempotencyKey:""},i=await Ds(n),o=await fetch(`${Tr(r)}/api/sessions/${encodeURIComponent(s.sessionId)}/viewer-connect`,{headers:Ps(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${s.sessionId} failed: HTTP ${o.status}`);let a=await Ki(o);if(!a.ws_url||!Qi(a.ws_url))throw new Oe(`[urun] viewer-connect returned no usable ws_url for ${s.sessionId}`);return{baseUrl:Tr(r),sessionId:s.sessionId,wsUrl:a.ws_url,response:a}}catch(n){if(t=n instanceof Error?n:new Error(String(n)),t instanceof Oe)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Ki(s){try{let e=await s.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Hd(s,e,t){let r=Number(s.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??r),i=t??1e4;return Number.isFinite(n)&&n>0?Math.min(n*1e3,i):1e3}function Gd(s){return new Promise(e=>setTimeout(e,s))}var Oe=class extends Error{};function Qi(s){try{let e=new URL(s);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Kd(s){try{return new URL(s).hostname!==Fd?[]:qd}catch{return[]}}var pt=Se(require("yjs")),Yi=Symbol("urun:doc:remote"),Qd=Symbol("urun:doc:local");function Ae(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var Er="$bytes";function Yd(s){return s instanceof Uint8Array||s instanceof ArrayBuffer}function Jd(s){if(!Ae(s))return!1;let e=Object.keys(s);return e.length===1&&e[0]===Er&&typeof s[Er]=="string"}function Xd(s){return s instanceof ArrayBuffer?new Uint8Array(s):s}function Zd(s){if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return btoa(e)}function ep(s){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(s,"base64"));let e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Is(s){if(Yd(s))return{[Er]:Zd(Xd(s))};if(Array.isArray(s))return s.map(Is);if(Ae(s)){let e={};for(let[t,r]of Object.entries(s))e[t]=Is(r);return e}return s}function Mt(s){if(Jd(s))return ep(s[Er]);if(Array.isArray(s))return s.map(Mt);if(Ae(s)){let e={};for(let[t,r]of Object.entries(s))e[t]=Mt(r);return e}return s}function Ls(s,e){let t={...s};for(let r of Object.keys(e)){let n=e[r],i=t[r];Ae(n)&&Ae(i)?t[r]=Ls(i,n):t[r]=n}return t}var Xi=Symbol("urun:doc:path-absent");function tp(s,e){let t=e.split("."),r=s;for(let n of t){if(r===null||typeof r!="object"||!(n in r))return Xi;r=r[n]}return r}function Ji(s){return s===void 0?s:JSON.parse(JSON.stringify(s))}var kr=class{_doc=new pt.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==Yi&&this._transport?.sendDocSync(this._key,e)};constructor(e,t,r){this._key=e,this._sessionId=t,this._transport=r??null,this._synced=this._transport===null,this._root.observeDeep(this._observer),this._doc.on("update",this._updateHandler),this._transport&&(this._transportUnsubs.push(this._transport.onDocSync(this._key,n=>this.applyRemote(n)),this._transport.onDocSyncReady(()=>this.sendHello())),this._transport.isOpen&&this.sendHello())}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){if(e=Is(e),!this._synced){this._pendingPatches.push(Ji(e)),this.notify();return}this.applyPatch(e)}get(e,t){let r=this.snapshot();if(!e)return Mt(r);let n=tp(r,e);return n===Xi?t:Mt(n)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new Ms(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._doc.off("update",this._updateHandler);for(let e of this._transportUnsubs)e();this._transportUnsubs=[],this._transport=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,pt.encodeStateAsUpdate(this._doc))}applyRemote(e){if(pt.applyUpdate(this._doc,e,Yi),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let n of t)this.applyPatch(n);let r=[...this._syncWaiters];this._syncWaiters.clear();for(let n of r)n()}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[r,n]of Object.entries(e)){let i=t[r],o=Ae(n)&&Ae(i)?Ls(i,n):Ji(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(r,o)}},Qd)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=Ls(e,t);return e}notify(){let e=Mt(this.snapshot());for(let t of this._listeners)t(e)}},Ms=class{constructor(e){this._ytext=e;this._observer=t=>{for(let r of t.delta)if(typeof r.insert=="string"&&r.insert.length>0){let n=r.insert;for(let i of this._delta)i(n)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var oe=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},lt=class extends oe{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},ut=class extends oe{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},ht=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},ye=class extends oe{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},ft=class extends oe{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var rp=new Set,sp="rpc",np="llm",Ns=3e4,ip="llm-resp";function op(s){return`${ip}:${s}`}function Os(){return Cr()}function ap(s){if(s&&typeof s=="object"){let e=s.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof s=="string"?s:JSON.stringify(s)}}function cp(s,e,t,r,n,i,o,a,c){let d=[],p=null,l=!1,u=null,m=!1,f,h,g=new Promise((D,be)=>{f=D,h=be});g.catch(()=>{});let _=i(),y=null,x=null,P=null,k=null,I=!0,he=()=>{P&&(clearTimeout(P),P=null),k&&(k(),k=null)},ae=()=>{I=!1,he(),y?.(),y=null,x?.(),x=null,o?.removeEventListener("abort",qs),_.dispose(),m&&s.set({requests:{[e]:null}})},Y=()=>{if(p){if(d.length>0){let D=p;p=null,D.resolve({value:d.shift(),done:!1})}else if(u!==null){let D=p;p=null,D.reject(u)}else if(l){let D=p;p=null,D.resolve({value:void 0,done:!0})}}},fe=D=>{l||(d.push(D),Y())},Ne=D=>{l||(u=D,l=!0,h(D),ae(),Y())},Fs=D=>{l||(l=!0,f(D),ae(),Y())},qs=()=>Ne(new ye(e)),no=D=>{if(!(l||!D||typeof D!="object"))switch(D.t){case"delta":typeof D.delta=="string"&&fe(D.delta);break;case"response":Fs(D.body);break;case"error":{let{message:be,code:je}=ap(D.body);Ne(new oe(be,{requestId:e,code:D.code??je}));break}}},io=()=>{let D=_.messages()[Symbol.asyncIterator]();y=()=>{D.return?.(void 0)};let be=()=>{I&&D.next().then(je=>{if(I){if(je.done){l||Fs(void 0);return}no(je.value),be()}},je=>{I&&Ne(je)})};be()},$s=()=>{if(!m){if(m=!0,o){if(o.aborted){Ne(new ye(e));return}o.addEventListener("abort",qs,{once:!0})}x=a?.(D=>Ne(D))??null,io(),s.set({requests:{[e]:{payload:t,consumer_id:r,stream:n}}}),c&&c>0&&!s.synced&&(P=setTimeout(()=>{P=null,!l&&!s.synced&&Ne(new ut(c,e))},c),k=s.onSynced(()=>he()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if($s(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(u!==null){let D=u;return u=null,Promise.reject(D)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((D,be)=>{p={resolve:D,reject:be}})},return(){return l||(l=!0,f(void 0),ae()),Promise.resolve({value:void 0,done:!0})},throw(D){return l||(l=!0,h(D),ae()),Promise.reject(D)}}}},body:g,start:$s}}function dp(s,e){return[`streams/${s}/${e}`,`streams/${s}/*`]}function pp(s,e){return`streams/${s}/${e??"*"}`}function lp(s,e){let r=s.get("streams")?.[e];if(r&&typeof r=="object"){let{producer:n,epoch:i}=r;if(n==="runtime"||n==="browser")return{producer:n,epoch:typeof i=="number"?i:0}}return null}var As=class{constructor(e,t,r,n){this._name=e;this._transport=t;this._laneDoc=r;this._controlDoc=n;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_laneDoc;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,i={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{n=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){if(!(this._subscribed||this._disposed)&&(this._subscribed=!0,this._transport.subscribeStream(this._name),!!this._laneDoc))for(let e of dp(this._name,this._transport.consumerId)){let t=this._laneDoc(e);this._laneSeen.set(e,0);let r=n=>this._drainLane(e,n);r(t.get()),this._laneUnsubs.push(t.on("change",r))}}_drainLane(e,t){let r=t.messages;if(!Array.isArray(r))return;let n=this._laneSeen.get(e)??0;for(;n<r.length;n++){let i=r[n];this._replay.push(i);for(let o of this._messageConsumers)o.push(i)}this._laneSeen.set(e,n)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}_claimBrowserProducer(){if(!this._controlDoc)return;let e=this._controlDoc(),t=lp(e,this._name);if(t&&t.producer==="runtime")throw new ht(this._name,"runtime","browser");if(t&&t.producer==="browser")return;let r=(typeof t?.epoch=="number"?t.epoch:0)+1;e.set({streams:{[this._name]:{producer:"browser",epoch:r}}})}async attach(e){this._claimBrowserProducer(),await this._transport.addTrack(e)}async attachVideo(e){this._claimBrowserProducer(),await this._transport.addVideoTrack(e)}async emit(e,t={}){if(this._claimBrowserProducer(),!this._laneDoc)throw new Error("[urun] stream.emit requires the session doc transport (no laneDoc wired)");let r=pp(this._name,t.to),n=this._laneDoc(r),i=n.get("messages"),o=Array.isArray(i)?[...i]:[];o.push(e),n.set({messages:o})}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name);for(let e of this._laneUnsubs)e();this._laneUnsubs=[];for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},mt=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_activeRequests=new Set;constructor(e,t,r){this._sessionId=e,this._multiplexer=t,this._transport=r,this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Gi({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new qe,o=new dt({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,i,o);return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new As(e,this._transport,r=>this.doc(r),()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new kr(e,this._sessionId,rp.has(e)?null:this._transport),this._docs.set(e,t)),t}sendImage(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=this.doc(sp),n=Os();return new Promise((i,o)=>{let a=!1,c=null,d=null,p=null,l=()=>{d&&(clearTimeout(d),d=null),c&&(c(),c=null),p&&(this._activeRequests.delete(p),p=null),t.signal?.removeEventListener("abort",m),r.set({requests:{[n]:null}})},u=h=>{a||(a=!0,l(),h())},m=()=>u(()=>o(new ye(n)));if(t.signal){if(t.signal.aborted){a=!0,o(new ye(n));return}t.signal.addEventListener("abort",m,{once:!0})}let f=h=>{let _=h.responses?.[n];if(_==null)return;let y=_;if(y.error!==void 0&&y.error!==null){let x=typeof y.error=="string"?y.error:JSON.stringify(y.error);u(()=>o(new oe(x,{requestId:n,code:y.code})))}else u(()=>i(y.result))};c=r.on("change",f),p=h=>u(()=>o(h)),this._activeRequests.add(p),typeof t.timeout=="number"&&t.timeout>=0&&(d=setTimeout(()=>u(()=>o(new lt(t.timeout,n))),t.timeout)),r.set({requests:{[n]:{payload:e}}}),f(r.get())})}_consumeResponse(e,t,r,n,i){let o=this.doc(np);return cp(o,e,t,this._transport.consumerId,r,()=>this.stream(op(e)),n,a=>(this._activeRequests.add(a),()=>this._activeRequests.delete(a)),i??Ns)}requestStream(e,t={}){let r=Os();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Os(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ft)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var up=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Zi(s,e){return new Proxy({},{get(t,r){if(!(up.has(r)||typeof r!="string"))return n=>{let i=n??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new qe,d=new dt({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),p=new mt(a,c,d),l=async u=>{let m=await Hi({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:u}),f=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return p.setSessionId(m.sessionId),{url:m.wsUrl,sessionId:m.sessionId,jwt:f,iceServers:m.response.ice_servers}};return d.setConnectionResolver(()=>l(o())),d.on("connected",()=>{d.multiplexer&&c.setTarget(d.multiplexer)}),(async()=>{let u=await l(a);d.setAuth({jwt:u.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:u.url,sessionId:u.sessionId,iceServers:u.iceServers}),await d.connect({app:s,functionName:r,args:i})})().catch(u=>{console.error(`[urun] Failed to connect session for ${r}:`,u)}),p}}})}var eo=3e4,to="stream:",js=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let i=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(i.timer),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${to}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${to}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),n(new Error(`RPC request "${e}" timed out after ${eo}ms`)))},eo);this._pendingRpc.set(i,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function ro(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let i=new Fe(n);return new js(n,i)}var hp='video/mp4; codecs="avc1.42E01E"';function so(s,e){let t=e?.codec??hp,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);r.src=i,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):g}let m=s.getReader();function f(){return u.updating?new Promise(g=>{u.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function h(){try{for(;;){let{done:g,value:_}=await m.read();if(g){await f(),n.readyState==="open"&&n.endOfStream();return}await f();try{u.appendBuffer(_)}catch(y){if(y instanceof DOMException&&y.name==="QuotaExceededError"){let x=u.buffered;if(x.length>0){let P=x.start(x.length-1);u.remove(0,P),await f(),u.appendBuffer(_)}else throw y}else throw y}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}h()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),d=c.getTracks(),p=0,l=d.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let u of d)u.addEventListener("ended",()=>{p++,p>=l&&URL.revokeObjectURL(i)});return c}0&&(module.exports={App,DEFAULT_DOC_SYNC_TIMEOUT_MS,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,Session,StreamDirectionConflict,createStore,videoStream});