@tribe-nest/forge 3.41.1 → 3.42.1
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/package.json +2 -2
- package/src/_tests/publishedResolvability.spec.ts +81 -3
- package/src/data/queries/useAuthActions.ts +15 -2
- package/src/ui/styled/ForgotPasswordForm.tsx +12 -2
- package/src/ui/styled/_tests/broadcastStage.spec.ts +41 -0
- package/src/ui/styled/broadcast/BroadcastMoqStage.tsx +124 -0
- package/src/ui/styled/broadcast/BroadcastPlayer.tsx +239 -16
- package/src/ui/styled/broadcast/BroadcastRealtimeStage.tsx +6 -3
- package/src/ui/styled/broadcast/broadcastStage.spec.ts +32 -0
- package/src/ui/styled/broadcast/broadcastStage.ts +38 -2
- package/src/ui/styled/broadcast/relayReachable.spec.ts +42 -0
- package/src/ui/styled/broadcast/relayReachable.ts +47 -0
- package/src/ui/styled/broadcast/vendor/moq-watch.bundle.d.ts +12 -0
- package/src/ui/styled/broadcast/vendor/moq-watch.bundle.js +549 -0
- package/src/ui/styled/forge-utilities.css +7 -0
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
var Fm=Object.create;var No=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Cm=Object.getOwnPropertyNames;var Om=Object.getPrototypeOf,Vm=Object.prototype.hasOwnProperty;var Eu=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var ge=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Lm=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ke=(r,e)=>{for(var t in e)No(r,t,{get:e[t],enumerable:!0})},Um=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Cm(e))!Vm.call(r,i)&&i!==t&&No(r,i,{get:()=>e[i],enumerable:!(n=Dm(e,i))||n.enumerable});return r};var Bm=(r,e,t)=>(t=r!=null?Fm(Om(r)):{},Um(e||!r||!r.__esModule?No(t,"default",{value:r,enumerable:!0}):t,r));var sf=Lm((Ti,sc)=>{(function(r,e){typeof Ti=="object"&&typeof sc=="object"?sc.exports=e():typeof define=="function"&&define.amd?define([],e):typeof Ti=="object"?Ti.bowser=e():r.bowser=e()})(Ti,(function(){return(function(r){var e={};function t(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return r[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}return t.m=r,t.c=e,t.d=function(n,i,s){t.o(n,i)||Object.defineProperty(n,i,{enumerable:!0,get:s})},t.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,i){if(1&i&&(n=t(n)),8&i||4&i&&typeof n=="object"&&n&&n.__esModule)return n;var s=Object.create(null);if(t.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:n}),2&i&&typeof n!="string")for(var a in n)t.d(s,a,function(o){return n[o]}.bind(null,a));return s},t.n=function(n){var i=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(i,"a",i),i},t.o=function(n,i){return Object.prototype.hasOwnProperty.call(n,i)},t.p="",t(t.s=90)})({17:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n=t(18),i=(function(){function s(){}return s.getFirstMatch=function(a,o){var c=o.match(a);return c&&c.length>0&&c[1]||""},s.getSecondMatch=function(a,o){var c=o.match(a);return c&&c.length>1&&c[2]||""},s.matchAndReturnConst=function(a,o,c){if(a.test(o))return c},s.getWindowsVersionName=function(a){switch(a){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},s.getMacOSVersionName=function(a){var o=a.split(".").splice(0,2).map((function(d){return parseInt(d,10)||0}));o.push(0);var c=o[0],u=o[1];if(c===10)switch(u){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},s.getAndroidVersionName=function(a){var o=a.split(".").splice(0,2).map((function(c){return parseInt(c,10)||0}));if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},s.getVersionPrecision=function(a){return a.split(".").length},s.compareVersions=function(a,o,c){c===void 0&&(c=!1);var u=s.getVersionPrecision(a),d=s.getVersionPrecision(o),f=Math.max(u,d),l=0,h=s.map([a,o],(function(p){var _=f-s.getVersionPrecision(p),w=p+new Array(_+1).join(".0");return s.map(w.split("."),(function(y){return new Array(20-y.length).join("0")+y})).reverse()}));for(c&&(l=f-Math.min(u,d)),f-=1;f>=l;){if(h[0][f]>h[1][f])return 1;if(h[0][f]===h[1][f]){if(f===l)return 0;f-=1}else if(h[0][f]<h[1][f])return-1}},s.map=function(a,o){var c,u=[];if(Array.prototype.map)return Array.prototype.map.call(a,o);for(c=0;c<a.length;c+=1)u.push(o(a[c]));return u},s.find=function(a,o){var c,u;if(Array.prototype.find)return Array.prototype.find.call(a,o);for(c=0,u=a.length;c<u;c+=1){var d=a[c];if(o(d,c))return d}},s.assign=function(a){for(var o,c,u=a,d=arguments.length,f=new Array(d>1?d-1:0),l=1;l<d;l++)f[l-1]=arguments[l];if(Object.assign)return Object.assign.apply(Object,[a].concat(f));var h=function(){var p=f[o];typeof p=="object"&&p!==null&&Object.keys(p).forEach((function(_){u[_]=p[_]}))};for(o=0,c=f.length;o<c;o+=1)h();return a},s.getBrowserAlias=function(a){return n.BROWSER_ALIASES_MAP[a]},s.getBrowserTypeByAlias=function(a){return n.BROWSER_MAP[a]||""},s})();e.default=i,r.exports=e.default},18:function(r,e,t){"use strict";e.__esModule=!0,e.ENGINE_MAP=e.OS_MAP=e.PLATFORMS_MAP=e.BROWSER_MAP=e.BROWSER_ALIASES_MAP=void 0,e.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},e.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},e.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},e.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},e.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n,i=(n=t(91))&&n.__esModule?n:{default:n},s=t(18);function a(c,u){for(var d=0;d<u.length;d++){var f=u[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,f.key,f)}}var o=(function(){function c(){}var u,d,f;return c.getParser=function(l,h,p){if(h===void 0&&(h=!1),p===void 0&&(p=null),typeof l!="string")throw new Error("UserAgent should be a string");return new i.default(l,h,p)},c.parse=function(l,h){return h===void 0&&(h=null),new i.default(l,h).getResult()},u=c,f=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(d=null)&&a(u.prototype,d),f&&a(u,f),c})();e.default=o,r.exports=e.default},91:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n=c(t(92)),i=c(t(93)),s=c(t(94)),a=c(t(95)),o=c(t(17));function c(d){return d&&d.__esModule?d:{default:d}}var u=(function(){function d(l,h,p){if(h===void 0&&(h=!1),p===void 0&&(p=null),l==null||l==="")throw new Error("UserAgent parameter can't be empty");this._ua=l;var _=!1;typeof h=="boolean"?(_=h,this._hints=p):this._hints=h!=null&&typeof h=="object"?h:null,this.parsedResult={},_!==!0&&this.parse()}var f=d.prototype;return f.getHints=function(){return this._hints},f.hasBrand=function(l){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var h=l.toLowerCase();return this._hints.brands.some((function(p){return p.brand&&p.brand.toLowerCase()===h}))},f.getBrandVersion=function(l){if(this._hints&&Array.isArray(this._hints.brands)){var h=l.toLowerCase(),p=this._hints.brands.find((function(_){return _.brand&&_.brand.toLowerCase()===h}));return p?p.version:void 0}},f.getUA=function(){return this._ua},f.test=function(l){return l.test(this._ua)},f.parseBrowser=function(){var l=this;this.parsedResult.browser={};var h=o.default.find(n.default,(function(p){if(typeof p.test=="function")return p.test(l);if(Array.isArray(p.test))return p.test.some((function(_){return l.test(_)}));throw new Error("Browser's test function is not valid")}));return h&&(this.parsedResult.browser=h.describe(this.getUA(),this)),this.parsedResult.browser},f.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},f.getBrowserName=function(l){return l?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},f.getBrowserVersion=function(){return this.getBrowser().version},f.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},f.parseOS=function(){var l=this;this.parsedResult.os={};var h=o.default.find(i.default,(function(p){if(typeof p.test=="function")return p.test(l);if(Array.isArray(p.test))return p.test.some((function(_){return l.test(_)}));throw new Error("Browser's test function is not valid")}));return h&&(this.parsedResult.os=h.describe(this.getUA())),this.parsedResult.os},f.getOSName=function(l){var h=this.getOS().name;return l?String(h).toLowerCase()||"":h||""},f.getOSVersion=function(){return this.getOS().version},f.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},f.getPlatformType=function(l){l===void 0&&(l=!1);var h=this.getPlatform().type;return l?String(h).toLowerCase()||"":h||""},f.parsePlatform=function(){var l=this;this.parsedResult.platform={};var h=o.default.find(s.default,(function(p){if(typeof p.test=="function")return p.test(l);if(Array.isArray(p.test))return p.test.some((function(_){return l.test(_)}));throw new Error("Browser's test function is not valid")}));return h&&(this.parsedResult.platform=h.describe(this.getUA())),this.parsedResult.platform},f.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},f.getEngineName=function(l){return l?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},f.parseEngine=function(){var l=this;this.parsedResult.engine={};var h=o.default.find(a.default,(function(p){if(typeof p.test=="function")return p.test(l);if(Array.isArray(p.test))return p.test.some((function(_){return l.test(_)}));throw new Error("Browser's test function is not valid")}));return h&&(this.parsedResult.engine=h.describe(this.getUA())),this.parsedResult.engine},f.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},f.getResult=function(){return o.default.assign({},this.parsedResult)},f.satisfies=function(l){var h=this,p={},_=0,w={},y=0;if(Object.keys(l).forEach((function(T){var R=l[T];typeof R=="string"?(w[T]=R,y+=1):typeof R=="object"&&(p[T]=R,_+=1)})),_>0){var b=Object.keys(p),g=o.default.find(b,(function(T){return h.isOS(T)}));if(g){var x=this.satisfies(p[g]);if(x!==void 0)return x}var P=o.default.find(b,(function(T){return h.isPlatform(T)}));if(P){var I=this.satisfies(p[P]);if(I!==void 0)return I}}if(y>0){var M=Object.keys(w),k=o.default.find(M,(function(T){return h.isBrowser(T,!0)}));if(k!==void 0)return this.compareVersion(w[k])}},f.isBrowser=function(l,h){h===void 0&&(h=!1);var p=this.getBrowserName().toLowerCase(),_=l.toLowerCase(),w=o.default.getBrowserTypeByAlias(_);return h&&w&&(_=w.toLowerCase()),_===p},f.compareVersion=function(l){var h=[0],p=l,_=!1,w=this.getBrowserVersion();if(typeof w=="string")return l[0]===">"||l[0]==="<"?(p=l.substr(1),l[1]==="="?(_=!0,p=l.substr(2)):h=[],l[0]===">"?h.push(1):h.push(-1)):l[0]==="="?p=l.substr(1):l[0]==="~"&&(_=!0,p=l.substr(1)),h.indexOf(o.default.compareVersions(w,p,_))>-1},f.isOS=function(l){return this.getOSName(!0)===String(l).toLowerCase()},f.isPlatform=function(l){return this.getPlatformType(!0)===String(l).toLowerCase()},f.isEngine=function(l){return this.getEngineName(!0)===String(l).toLowerCase()},f.is=function(l,h){return h===void 0&&(h=!1),this.isBrowser(l,h)||this.isOS(l)||this.isPlatform(l)},f.some=function(l){var h=this;return l===void 0&&(l=[]),l.some((function(p){return h.is(p)}))},d})();e.default=u,r.exports=e.default},92:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n,i=(n=t(17))&&n.__esModule?n:{default:n},s=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},u=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},u=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},u=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},u=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},u=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},u=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},u=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},u=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},u=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},u=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},u=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},u=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},u=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},u=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},u=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},u=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},u=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},u=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},u=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},u=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},u=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var c={name:"Opera"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},u=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},u=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},u=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},u=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},u=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},u=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},u=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},u=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},u=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},u=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},u=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},u=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},u=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},u=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return u&&(c.version=u),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},u=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},u=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},u=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},u=i.default.getFirstMatch(s,o)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},u=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},u=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},u=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},u=i.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},u=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},u=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},u=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),d=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),f=i.default.getFirstMatch(/se ([\d.]+)x/i,o),l=u||d||f;return l&&(c.version=l),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},u=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var u={name:"DuckDuckGo"};if(c){var d=c.getBrandVersion("DuckDuckGo");if(d)return u.version=d,u}var f=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return f&&(u.version=f),u}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var u={name:"Brave"};if(c){var d=c.getBrandVersion("Brave");if(d)return u.version=d,u}return u}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},u=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},u=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},u=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:function(o){var c=!o.test(/like android/i),u=o.test(/android/i);return c&&u},describe:function(o){var c={name:"Android Browser"},u=i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},u=i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},u=i.default.getFirstMatch(s,o);return u&&(c.version=u),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(c,o),version:i.default.getSecondMatch(c,o)}}}];e.default=a,r.exports=e.default},93:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n,i=(n=t(17))&&n.__esModule?n:{default:n},s=t(18),a=[{test:[/Roku\/DVP/],describe:function(o){var c=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:s.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:s.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),u=i.default.getWindowsVersionName(c);return{name:s.OS_MAP.Windows,version:c,versionName:u}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:s.OS_MAP.iOS},u=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return u&&(c.version=u),c}},{test:[/macintosh/i],describe:function(o){var c=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),u=i.default.getMacOSVersionName(c),d={name:s.OS_MAP.MacOS,version:c};return u&&(d.versionName=u),d}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:s.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:s.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),u=o.test(/android/i);return c&&u},describe:function(o){var c=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),u=i.default.getAndroidVersionName(c),d={name:s.OS_MAP.Android,version:c};return u&&(d.versionName=u),d}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),u={name:s.OS_MAP.WebOS};return c&&c.length&&(u.version=c),u}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||i.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:s.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:s.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:s.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var c=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:s.OS_MAP.PlayStation4,version:c}}}];e.default=a,r.exports=e.default},94:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n,i=(n=t(17))&&n.__esModule?n:{default:n},s=t(18),a=[{test:[/googlebot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:s.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var c=i.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",u={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(u.model=c),u}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(o){var c=o.test(/ipod|iphone/i),u=o.test(/like (ipod|iphone)/i);return c&&!u},describe:function(o){var c=i.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var c=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),u={type:s.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(u.model=c),u}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];e.default=a,r.exports=e.default},95:function(r,e,t){"use strict";e.__esModule=!0,e.default=void 0;var n,i=(n=t(17))&&n.__esModule?n:{default:n},s=t(18),a=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:s.ENGINE_MAP.Blink};var c=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:s.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:s.ENGINE_MAP.Trident},u=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:s.ENGINE_MAP.Presto},u=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:function(o){var c=o.test(/gecko/i),u=o.test(/like gecko/i);return c&&!u},describe:function(o){var c={name:s.ENGINE_MAP.Gecko},u=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:s.ENGINE_MAP.WebKit},u=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return u&&(c.version=u),c}}];e.default=a,r.exports=e.default}})}))});var Op={};ke(Op,{AVDISCARD_ALL:()=>iv,AVDISCARD_BIDIR:()=>tv,AVDISCARD_DEFAULT:()=>Jb,AVDISCARD_NONE:()=>Qb,AVDISCARD_NONINTRA:()=>rv,AVDISCARD_NONKEY:()=>nv,AVDISCARD_NONREF:()=>ev,AVERROR_EOF:()=>uA,AVFMT_FLAG_FLUSH_PACKETS:()=>Wb,AVFMT_FLAG_NOBUFFER:()=>jb,AVIO_FLAG_DIRECT:()=>Gb,AVIO_FLAG_NONBLOCK:()=>Zb,AVIO_FLAG_READ:()=>$b,AVIO_FLAG_READ_WRITE:()=>qb,AVIO_FLAG_WRITE:()=>Nb,AVMEDIA_TYPE_ATTACHMENT:()=>Cy,AVMEDIA_TYPE_AUDIO:()=>Ry,AVMEDIA_TYPE_DATA:()=>Fy,AVMEDIA_TYPE_SUBTITLE:()=>Dy,AVMEDIA_TYPE_UNKNOWN:()=>Py,AVMEDIA_TYPE_VIDEO:()=>zy,AVSEEK_FLAG_ANY:()=>Yb,AVSEEK_FLAG_BACKWARD:()=>Hb,AVSEEK_FLAG_BYTE:()=>Xb,AVSEEK_FLAG_FRAME:()=>Kb,AV_LOG_DEBUG:()=>fv,AV_LOG_ERROR:()=>cv,AV_LOG_FATAL:()=>av,AV_LOG_INFO:()=>dv,AV_LOG_PANIC:()=>ov,AV_LOG_QUIET:()=>sv,AV_LOG_TRACE:()=>hv,AV_LOG_VERBOSE:()=>lv,AV_LOG_WARNING:()=>uv,AV_NOPTS_VALUE:()=>My,AV_NOPTS_VALUE_HI:()=>Ty,AV_NOPTS_VALUE_I64:()=>Ey,AV_NOPTS_VALUE_LO:()=>ky,AV_OPT_SEARCH_CHILDREN:()=>Iy,AV_PIX_FMT_ABGR:()=>Sb,AV_PIX_FMT_ARGB:()=>Ab,AV_PIX_FMT_BGR24:()=>eb,AV_PIX_FMT_BGR4:()=>mb,AV_PIX_FMT_BGR4_BYTE:()=>_b,AV_PIX_FMT_BGR555BE:()=>Ub,AV_PIX_FMT_BGR555LE:()=>Bb,AV_PIX_FMT_BGR565BE:()=>Vb,AV_PIX_FMT_BGR565LE:()=>Lb,AV_PIX_FMT_BGR8:()=>pb,AV_PIX_FMT_BGRA:()=>Eb,AV_PIX_FMT_GRAY16BE:()=>kb,AV_PIX_FMT_GRAY16LE:()=>Tb,AV_PIX_FMT_GRAY8:()=>sb,AV_PIX_FMT_MONOBLACK:()=>ab,AV_PIX_FMT_MONOWHITE:()=>ob,AV_PIX_FMT_NONE:()=>Yy,AV_PIX_FMT_NV12:()=>bb,AV_PIX_FMT_NV21:()=>vb,AV_PIX_FMT_PAL8:()=>cb,AV_PIX_FMT_RGB24:()=>Jy,AV_PIX_FMT_RGB4:()=>gb,AV_PIX_FMT_RGB48BE:()=>zb,AV_PIX_FMT_RGB48LE:()=>Rb,AV_PIX_FMT_RGB4_BYTE:()=>yb,AV_PIX_FMT_RGB555BE:()=>Cb,AV_PIX_FMT_RGB555LE:()=>Ob,AV_PIX_FMT_RGB565BE:()=>Fb,AV_PIX_FMT_RGB565LE:()=>Db,AV_PIX_FMT_RGB8:()=>wb,AV_PIX_FMT_RGBA:()=>xb,AV_PIX_FMT_UYVY422:()=>fb,AV_PIX_FMT_UYYVYY411:()=>hb,AV_PIX_FMT_YUV410P:()=>nb,AV_PIX_FMT_YUV411P:()=>ib,AV_PIX_FMT_YUV420P:()=>Ky,AV_PIX_FMT_YUV422P:()=>tb,AV_PIX_FMT_YUV440P:()=>Mb,AV_PIX_FMT_YUV444P:()=>rb,AV_PIX_FMT_YUVA420P:()=>Pb,AV_PIX_FMT_YUVJ420P:()=>ub,AV_PIX_FMT_YUVJ422P:()=>db,AV_PIX_FMT_YUVJ440P:()=>Ib,AV_PIX_FMT_YUVJ444P:()=>lb,AV_PIX_FMT_YUYV422:()=>Qy,AV_PKT_FLAG_CORRUPT:()=>mv,AV_PKT_FLAG_DISCARD:()=>_v,AV_PKT_FLAG_DISPOSABLE:()=>gv,AV_PKT_FLAG_KEY:()=>pv,AV_PKT_FLAG_TRUSTED:()=>wv,AV_SAMPLE_FMT_DBL:()=>$y,AV_SAMPLE_FMT_DBLP:()=>jy,AV_SAMPLE_FMT_FLT:()=>By,AV_SAMPLE_FMT_FLTP:()=>Gy,AV_SAMPLE_FMT_NB:()=>Xy,AV_SAMPLE_FMT_NONE:()=>Oy,AV_SAMPLE_FMT_S16:()=>Ly,AV_SAMPLE_FMT_S16P:()=>qy,AV_SAMPLE_FMT_S32:()=>Uy,AV_SAMPLE_FMT_S32P:()=>Zy,AV_SAMPLE_FMT_S64:()=>Wy,AV_SAMPLE_FMT_S64P:()=>Hy,AV_SAMPLE_FMT_U8:()=>Vy,AV_SAMPLE_FMT_U8P:()=>Ny,AV_TIME_BASE:()=>Sy,AV_VERSION_INT:()=>xy,CONFIG:()=>py,DBG:()=>my,E2BIG:()=>yv,EADDRINUSE:()=>vv,EADDRNOTAVAIL:()=>Av,EAFNOSUPPORT:()=>xv,EAGAIN:()=>Sv,EALREADY:()=>Ev,EBADF:()=>kv,EBADMSG:()=>Tv,EBUSY:()=>Mv,ECANCELED:()=>Iv,ECHILD:()=>Pv,ECONNABORTED:()=>zv,ECONNREFUSED:()=>Rv,ECONNRESET:()=>Fv,EDEADLOCK:()=>Dv,EDESTADDRREQ:()=>Cv,EDOM:()=>Ov,EDQUOT:()=>Vv,EEXIST:()=>Lv,EFAULT:()=>Uv,EFBIG:()=>Bv,EHOSTUNREACH:()=>$v,EIDRM:()=>Nv,EILSEQ:()=>qv,EINPROGRESS:()=>Zv,EINTR:()=>Gv,EINVAL:()=>jv,EIO:()=>Wv,EISCONN:()=>Hv,EISDIR:()=>Xv,ELOOP:()=>Yv,EMFILE:()=>Kv,EMLINK:()=>Qv,EMSGSIZE:()=>Jv,EMULTIHOP:()=>eA,ENAMETOOLONG:()=>tA,ENETDOWN:()=>rA,ENETRESET:()=>nA,ENETUNREACH:()=>iA,ENFILE:()=>sA,ENOBUFS:()=>oA,ENODEV:()=>aA,ENOENT:()=>cA,EPERM:()=>bv,LibAV:()=>dA,VER:()=>hy,base:()=>uy,bigIntToi64:()=>by,default:()=>lA,f64toi64:()=>gy,factories:()=>_y,ff_channel_layout:()=>vy,ff_channels:()=>Ay,i64ToBigInt:()=>yy,i64tof64:()=>wy,isThreadingSupported:()=>ly,isWebAssemblySupported:()=>dy,target:()=>fy});var U,uy,dy,ly,fy,hy,py,my,_y,wy,gy,yy,by,vy,Ay,xy,Sy,Ey,ky,Ty,My,Iy,Py,zy,Ry,Fy,Dy,Cy,Oy,Vy,Ly,Uy,By,$y,Ny,qy,Zy,Gy,jy,Wy,Hy,Xy,Yy,Ky,Qy,Jy,eb,tb,rb,nb,ib,sb,ob,ab,cb,ub,db,lb,fb,hb,pb,mb,_b,wb,gb,yb,bb,vb,Ab,xb,Sb,Eb,kb,Tb,Mb,Ib,Pb,zb,Rb,Fb,Db,Cb,Ob,Vb,Lb,Ub,Bb,$b,Nb,qb,Zb,Gb,jb,Wb,Hb,Xb,Yb,Kb,Qb,Jb,ev,tv,rv,nv,iv,sv,ov,av,cv,uv,dv,lv,fv,hv,pv,mv,_v,wv,gv,yv,bv,vv,Av,xv,Sv,Ev,kv,Tv,Mv,Iv,Pv,zv,Rv,Fv,Dv,Cv,Ov,Vv,Lv,Uv,Bv,$v,Nv,qv,Zv,Gv,jv,Wv,Hv,Xv,Yv,Kv,Qv,Jv,eA,tA,rA,nA,iA,sA,oA,aA,cA,uA,dA,lA,Vp=ge(()=>{U={};(function(){function r(a){if(a=a||[0,97,115,109,1,0,0,0],typeof WebAssembly!="object"||typeof WebAssembly.instantiate!="function")return!1;try{var a=new WebAssembly.Module(new Uint8Array(a));if(a instanceof WebAssembly.Module)return new WebAssembly.Instance(a)instanceof WebAssembly.Instance}catch{}return!1}function e(){try{var a=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});return a.buffer instanceof SharedArrayBuffer}catch{}return!1}var t=typeof process<"u";U.base||(U.base=import.meta.url,U.base=U.base.replace(/\/[^\/]*$/,"")),U.isWebAssemblySupported=r,U.isThreadingSupported=e;function n(a){a=a||{};var o=!a.nowasm&&r(),c=a.yesthreads&&o&&!a.nothreads&&e();return o?c?"thr":"wasm":"asm"}U.target=n,U.VER="6.10.9.0",U.CONFIG="opus-af",U.DBG="",U.factories={};var i={};i.i64tof64=function(a,o){return!o&&a>=0||o===-1&&a<0?a:o*4294967296+a+(a<0?4294967296:0)},i.f64toi64=function(a){return[~~a,Math.floor(a/4294967296)]},i.i64ToBigInt=function(a,o){var c=new DataView(new ArrayBuffer(8));return c.setInt32(0,a,!0),c.setInt32(4,o,!0),c.getBigInt64(0,!0)},i.bigIntToi64=function(a){var o=new DataView(new ArrayBuffer(8));return o.setBigInt64(0,a,!0),[o.getInt32(0,!0),o.getInt32(4,!0)]},i.ff_channel_layout=function(a){return a.channel_layout?a.channel_layout:a.channels&&a.channels!==1?(1<<a.channels)-1:4},i.ff_channels=function(a){if(a.channels)return a.channels;if(a.channel_layout){for(var o=0,c=a.channel_layout;c;)o+=c&1,c>>=1;return o}else return 1},i.AV_VERSION_INT=function(a,o,c){return a<<16|o<<8|c};function s(a,o){typeof o>"u"&&(o=0);var c=o;a.forEach((function(u){i[u]=c++}))}i.AV_TIME_BASE=1e6,i.AV_NOPTS_VALUE_I64=[0,-2147483648],i.AV_NOPTS_VALUE_LO=0,i.AV_NOPTS_VALUE_HI=-2147483648,i.AV_NOPTS_VALUE=i.i64tof64(0,-2147483648),i.AV_OPT_SEARCH_CHILDREN=1,s(["AVMEDIA_TYPE_UNKNOWN","AVMEDIA_TYPE_VIDEO","AVMEDIA_TYPE_AUDIO","AVMEDIA_TYPE_DATA","AVMEDIA_TYPE_SUBTITLE","AVMEDIA_TYPE_ATTACHMENT"],-1),s(["AV_SAMPLE_FMT_NONE","AV_SAMPLE_FMT_U8","AV_SAMPLE_FMT_S16","AV_SAMPLE_FMT_S32","AV_SAMPLE_FMT_FLT","AV_SAMPLE_FMT_DBL","AV_SAMPLE_FMT_U8P","AV_SAMPLE_FMT_S16P","AV_SAMPLE_FMT_S32P","AV_SAMPLE_FMT_FLTP","AV_SAMPLE_FMT_DBLP","AV_SAMPLE_FMT_S64","AV_SAMPLE_FMT_S64P","AV_SAMPLE_FMT_NB"],-1),s(["AV_PIX_FMT_NONE","AV_PIX_FMT_YUV420P","AV_PIX_FMT_YUYV422","AV_PIX_FMT_RGB24","AV_PIX_FMT_BGR24","AV_PIX_FMT_YUV422P","AV_PIX_FMT_YUV444P","AV_PIX_FMT_YUV410P","AV_PIX_FMT_YUV411P","AV_PIX_FMT_GRAY8","AV_PIX_FMT_MONOWHITE","AV_PIX_FMT_MONOBLACK","AV_PIX_FMT_PAL8","AV_PIX_FMT_YUVJ420P","AV_PIX_FMT_YUVJ422P","AV_PIX_FMT_YUVJ444P","AV_PIX_FMT_UYVY422","AV_PIX_FMT_UYYVYY411","AV_PIX_FMT_BGR8","AV_PIX_FMT_BGR4","AV_PIX_FMT_BGR4_BYTE","AV_PIX_FMT_RGB8","AV_PIX_FMT_RGB4","AV_PIX_FMT_RGB4_BYTE","AV_PIX_FMT_NV12","AV_PIX_FMT_NV21","AV_PIX_FMT_ARGB","AV_PIX_FMT_RGBA","AV_PIX_FMT_ABGR","AV_PIX_FMT_BGRA","AV_PIX_FMT_GRAY16BE","AV_PIX_FMT_GRAY16LE","AV_PIX_FMT_YUV440P","AV_PIX_FMT_YUVJ440P","AV_PIX_FMT_YUVA420P","AV_PIX_FMT_RGB48BE","AV_PIX_FMT_RGB48LE","AV_PIX_FMT_RGB565BE","AV_PIX_FMT_RGB565LE","AV_PIX_FMT_RGB555BE","AV_PIX_FMT_RGB555LE","AV_PIX_FMT_BGR565BE","AV_PIX_FMT_BGR565LE","AV_PIX_FMT_BGR555BE","AV_PIX_FMT_BGR555LE"],-1),i.AVIO_FLAG_READ=1,i.AVIO_FLAG_WRITE=2,i.AVIO_FLAG_READ_WRITE=3,i.AVIO_FLAG_NONBLOCK=8,i.AVIO_FLAG_DIRECT=32768,i.AVFMT_FLAG_NOBUFFER=64,i.AVFMT_FLAG_FLUSH_PACKETS=512,i.AVSEEK_FLAG_BACKWARD=1,i.AVSEEK_FLAG_BYTE=2,i.AVSEEK_FLAG_ANY=4,i.AVSEEK_FLAG_FRAME=8,i.AVDISCARD_NONE=-16,i.AVDISCARD_DEFAULT=0,i.AVDISCARD_NONREF=8,i.AVDISCARD_BIDIR=16,i.AVDISCARD_NONINTRA=24,i.AVDISCARD_NONKEY=32,i.AVDISCARD_ALL=48,i.AV_LOG_QUIET=-8,i.AV_LOG_PANIC=0,i.AV_LOG_FATAL=8,i.AV_LOG_ERROR=16,i.AV_LOG_WARNING=24,i.AV_LOG_INFO=32,i.AV_LOG_VERBOSE=40,i.AV_LOG_DEBUG=48,i.AV_LOG_TRACE=56,i.AV_PKT_FLAG_KEY=1,i.AV_PKT_FLAG_CORRUPT=2,i.AV_PKT_FLAG_DISCARD=4,i.AV_PKT_FLAG_TRUSTED=8,i.AV_PKT_FLAG_DISPOSABLE=16,s(["E2BIG","EPERM","EADDRINUSE","EADDRNOTAVAIL","EAFNOSUPPORT","EAGAIN","EALREADY","EBADF","EBADMSG","EBUSY","ECANCELED","ECHILD","ECONNABORTED","ECONNREFUSED","ECONNRESET","EDEADLOCK","EDESTADDRREQ","EDOM","EDQUOT","EEXIST","EFAULT","EFBIG","EHOSTUNREACH","EIDRM","EILSEQ","EINPROGRESS","EINTR","EINVAL","EIO","EISCONN","EISDIR","ELOOP","EMFILE","EMLINK","EMSGSIZE","EMULTIHOP","ENAMETOOLONG","ENETDOWN","ENETRESET","ENETUNREACH","ENFILE","ENOBUFS","ENODEV","ENOENT"],1),i.AVERROR_EOF=-541478725,Object.assign(U,i),U.LibAV=function(a){a=a||{};var o=a.base||U.base,c=n(a),u=a.variant||U.variant||"opus-af",d=!0;d&&(a.noes6||U.noes6)&&(d=!1);var f=a.toImport||U.toImport||o+"/libav-6.10.9.0-"+u+"."+c+"."+(d?"mjs":"js"),l,h="direct";return c==="thr"?h="threads":!t&&!a.noworker&&typeof Worker<"u"&&(h="worker"),Promise.all([]).then((function(){if(a.factory||U.factory)return a.factory||U.factory;if(U.factories[f])return U.factories[f];if(h!=="worker")return d?import(f).then((function(p){return U.factories[f]=p.default,p.default})):t?U.factories[f]=Eu(f):typeof importScripts<"u"?(importScripts(f),U.factories[f]=LibAVFactory):new Promise((function(p,_){var w=document.createElement("script");w.src=f,w.addEventListener("load",p),w.addEventListener("error",_),w.async=!0,document.body.appendChild(w)})).then((function(){return U.factories[f]=LibAVFactory}))})).then((function(p){return h==="worker"?(l={},l.worker=new Worker(f,{type:d?"module":"classic"}),new Promise((function(_,w){l.worker.onerror=b=>{console.error(b),w(b.error||new Error(b.message))},l.worker.postMessage({config:{variant:a.variant||U.variant,wasmurl:a.wasmurl||U.wasmurl}}),l.on=1,l.handlers={error:[function(b){w(b)},null],onready:[function(){_()},null],onwrite:[function(b){l.onwrite&&l.onwrite.apply(l,b)},null],onread:[function(b){try{var g=null;l.onread&&(g=l.onread.apply(l,b)),g&&g.then&&g.catch&&g.catch((function(x){l.ff_reader_dev_send(b[0],null,{error:x})}))}catch(x){l.ff_reader_dev_send(b[0],null,{error:x})}},null],onblockread:[function(b){try{var g=null;l.onblockread&&(g=l.onblockread.apply(l,b)),g&&g.then&&g.catch&&g.catch((function(x){l.ff_block_reader_dev_send(b[0],b[1],null,{error:x})}))}catch(x){l.ff_block_reader_dev_send(b[0],b[1],null,{error:x})}},null]},l.c=function(){for(var b=Array.prototype.slice.call(arguments),g=[],x=0;x<b.length;x++)b[x]&&b[x].libavjsTransfer&&g.push.apply(g,b[x].libavjsTransfer);return new Promise((function(P,I){var M=l.on++;b=[M].concat(b),l.handlers[M]=[P,I],l.worker.postMessage(b,g)}))};function y(b){var g=b.data[0],x=l.handlers[g];x&&(b.data[2]?x[0](b.data[3]):x[1](b.data[3]),typeof g=="number"&&delete l.handlers[g])}l.worker.onmessage=y,l.terminate=function(){l.worker.terminate()}}))):h==="threads"?Promise.all([]).then((function(){return p({wasmurl:a.wasmurl||U.wasmurl,variant:a.variant||U.variant})})).then((function(_){l=_;var w=l.libavjs_create_main_thread(),y=l.PThread.pthreads[w],b=0,g=1,x={},P=null,I=new Promise((function(k){P=k}));l.c=function(){var k=Array.prototype.slice.call(arguments);return new Promise((function(T,R){var Y=g++;k=[Y].concat(k),x[Y]=[T,R],y.postMessage({c:"libavjs_run",a:k})}))};var M=y.onmessage;return y.onmessage=function(k){if(k.data&&k.data.c==="libavjs_ret"){var T=k.data.a,R=x[T[0]];R&&(T[2]?R[0](T[3]):R[1](T[3]),delete x[T[0]])}else if(k.data&&k.data.c==="libavjs_wait_reader")if(l.readerDevReady(k.data.fd))y.postMessage({c:"libavjs_wait_reader",fd:k.data.fd});else{var Y=l.fdName(k.data.fd),Ae=l.ff_reader_dev_waiters[Y];Ae||(Ae=l.ff_reader_dev_waiters[Y]=[]),Ae.push((function(){y.postMessage({c:"libavjs_wait_reader",fd:k.data.fd})}))}else if(k.data&&k.data.c==="libavjs_ready")P();else return M.apply(this,arguments)},l.terminate=function(){l.PThread.unusedWorkers.concat(l.PThread.runningWorkers).forEach((function(k){k.terminate()}))},I})):Promise.all([]).then((function(){return p({wasmurl:a.wasmurl||U.wasmurl,variant:a.variant||U.variant})})).then((function(_){l=_,l.worker=!1,l.c=function(w){var y=Array.prototype.slice.call(arguments,1);return new Promise((function(b,g){try{b(l[w].apply(l,y))}catch(x){g(x)}}))},l.terminate=function(){}}))})).then((function(){function p(b){b.forEach((function(g){l[g]=function(){return l.c.apply(l,[g].concat(Array.prototype.slice.call(arguments)))}}))}function _(b){b.forEach((function(g){var x=l[g+"_sync"]=l[g];l[g]=function(){var P=arguments;return new Promise((function(I,M){try{var k=x.apply(l,P);typeof k=="object"&&k!==null&&k.then?k.then(I).catch(M):I(k)}catch(T){M(T)}}))}}))}var w=["calloc","close","dup2","free","malloc","mallinfo_uordblks","open","strerror","libavjs_create_main_thread","libavjs_with_swscale","ff_malloc_int32_list","ff_malloc_int64_list","av_compare_ts_js","av_dict_copy_js","av_dict_free","av_dict_iterate","av_dict_set_js","av_log_get_level","av_log_set_level","av_opt_set","av_opt_set_int_list_js","av_strdup","ff_error","ff_nothing","LIBAVUTIL_VERSION_INT","AVDictionaryEntry_key","AVDictionaryEntry_value","av_dict_free_js","av_find_best_stream","av_find_input_format","avformat_alloc_context","avformat_alloc_output_context2_js","avformat_close_input","avformat_find_stream_info","avformat_flush","avformat_free_context","avformat_new_stream","avformat_open_input","avformat_open_input_js","avformat_seek_file","avformat_seek_file_min","avformat_seek_file_max","avformat_seek_file_approx","avformat_write_header","av_interleaved_write_frame","avio_open2_js","avio_close","avio_flush","av_read_frame","av_seek_frame","av_write_frame","av_write_trailer","LIBAVFORMAT_VERSION_INT","ff_init_muxer","ff_free_muxer","ff_get_demuxer_chapters","ff_init_demuxer_file","ff_write_multi","ff_read_frame_multi","ff_read_multi","AVFormatContext_chapters_a","AVFormatContext_chapters_a_s","AVFormatContext_duration","AVFormatContext_duration_s","AVFormatContext_durationhi","AVFormatContext_durationhi_s","AVFormatContext_flags","AVFormatContext_flags_s","AVFormatContext_metadata","AVFormatContext_metadata_s","AVFormatContext_nb_chapters","AVFormatContext_nb_chapters_s","AVFormatContext_nb_streams","AVFormatContext_nb_streams_s","AVFormatContext_oformat","AVFormatContext_oformat_s","AVFormatContext_pb","AVFormatContext_pb_s","AVFormatContext_start_time","AVFormatContext_start_time_s","AVFormatContext_start_timehi","AVFormatContext_start_timehi_s","AVFormatContext_streams_a","AVFormatContext_streams_a_s","AVStream_codecpar","AVStream_codecpar_s","AVStream_discard","AVStream_discard_s","AVStream_duration","AVStream_duration_s","AVStream_durationhi","AVStream_durationhi_s","AVStream_metadata","AVStream_metadata_s","AVStream_time_base_num","AVStream_time_base_den","AVStream_time_base_num_s","AVStream_time_base_den_s","AVStream_time_base_s","AVChapter_end","AVChapter_end_s","AVChapter_endhi","AVChapter_endhi_s","AVChapter_id","AVChapter_id_s","AVChapter_metadata","AVChapter_metadata_s","AVChapter_start","AVChapter_start_s","AVChapter_starthi","AVChapter_starthi_s","AVChapter_time_base_num","AVChapter_time_base_den","AVChapter_time_base_num_s","AVChapter_time_base_den_s","AVChapter_time_base_s","avformat_close_input_js","avcodec_descriptor_get","avcodec_descriptor_get_by_name","avcodec_descriptor_next","av_grow_packet","av_packet_alloc","av_packet_clone","av_packet_free","av_packet_make_writable","av_packet_new_side_data","av_packet_ref","av_packet_rescale_ts_js","AVPacketSideData_data","AVPacketSideData_size","AVPacketSideData_type","av_packet_unref","av_shrink_packet","ff_codecpar_new_side_data","LIBAVCODEC_VERSION_INT","ff_set_packet","ff_copyout_packet","ff_copyout_packet_ptr","ff_copyin_packet","ff_copyout_dict","AVCodecDescriptor_id","AVCodecDescriptor_id_s","AVCodecDescriptor_long_name","AVCodecDescriptor_mime_types_a","AVCodecDescriptor_mime_types_a_s","AVCodecDescriptor_name","AVCodecDescriptor_props","AVCodecDescriptor_props_s","AVCodecDescriptor_type","AVCodecDescriptor_type_s","AVCodecParameters_bit_rate","AVCodecParameters_bit_rate_s","AVCodecParameters_channel_layoutmask","AVCodecParameters_channel_layoutmask_s","AVCodecParameters_channels","AVCodecParameters_channels_s","AVCodecParameters_ch_layout_nb_channels","AVCodecParameters_ch_layout_nb_channels_s","AVCodecParameters_chroma_location","AVCodecParameters_chroma_location_s","AVCodecParameters_codec_id","AVCodecParameters_codec_id_s","AVCodecParameters_codec_tag","AVCodecParameters_codec_tag_s","AVCodecParameters_codec_type","AVCodecParameters_codec_type_s","AVCodecParameters_coded_side_data","AVCodecParameters_coded_side_data_s","AVCodecParameters_color_primaries","AVCodecParameters_color_primaries_s","AVCodecParameters_color_range","AVCodecParameters_color_range_s","AVCodecParameters_color_space","AVCodecParameters_color_space_s","AVCodecParameters_color_trc","AVCodecParameters_color_trc_s","AVCodecParameters_extradata","AVCodecParameters_extradata_s","AVCodecParameters_extradata_size","AVCodecParameters_extradata_size_s","AVCodecParameters_format","AVCodecParameters_format_s","AVCodecParameters_framerate_num","AVCodecParameters_framerate_den","AVCodecParameters_framerate_num_s","AVCodecParameters_framerate_den_s","AVCodecParameters_framerate_s","AVCodecParameters_height","AVCodecParameters_height_s","AVCodecParameters_level","AVCodecParameters_level_s","AVCodecParameters_nb_coded_side_data","AVCodecParameters_nb_coded_side_data_s","AVCodecParameters_profile","AVCodecParameters_profile_s","AVCodecParameters_sample_rate","AVCodecParameters_sample_rate_s","AVCodecParameters_width","AVCodecParameters_width_s","AVPacket_data","AVPacket_data_s","AVPacket_dts","AVPacket_dts_s","AVPacket_dtshi","AVPacket_dtshi_s","AVPacket_duration","AVPacket_duration_s","AVPacket_durationhi","AVPacket_durationhi_s","AVPacket_flags","AVPacket_flags_s","AVPacket_pos","AVPacket_pos_s","AVPacket_poshi","AVPacket_poshi_s","AVPacket_pts","AVPacket_pts_s","AVPacket_ptshi","AVPacket_ptshi_s","AVPacket_side_data","AVPacket_side_data_s","AVPacket_side_data_elems","AVPacket_side_data_elems_s","AVPacket_size","AVPacket_size_s","AVPacket_stream_index","AVPacket_stream_index_s","AVPacket_time_base_num","AVPacket_time_base_den","AVPacket_time_base_num_s","AVPacket_time_base_den_s","AVPacket_time_base_s","av_packet_free_js","avcodec_parameters_free_js","avcodec_alloc_context3","avcodec_find_decoder","avcodec_find_decoder_by_name","avcodec_find_encoder","avcodec_find_encoder_by_name","avcodec_flush_buffers","avcodec_free_context","avcodec_get_name","avcodec_open2","avcodec_open2_js","avcodec_parameters_alloc","avcodec_parameters_copy","avcodec_parameters_free","avcodec_parameters_from_context","avcodec_parameters_to_context","avcodec_receive_frame","avcodec_receive_packet","avcodec_send_frame","avcodec_send_packet","ff_init_encoder","ff_init_decoder","ff_free_encoder","ff_free_decoder","ff_encode_multi","ff_decode_multi","ff_copyout_codecpar","ff_copyin_codecpar","AVCodec_name","AVCodec_sample_fmts","AVCodec_sample_fmts_s","AVCodec_sample_fmts_a","AVCodec_sample_fmts_a_s","AVCodec_supported_samplerates","AVCodec_supported_samplerates_s","AVCodec_supported_samplerates_a","AVCodec_supported_samplerates_a_s","AVCodec_type","AVCodec_type_s","AVCodecContext_codec_id","AVCodecContext_codec_id_s","AVCodecContext_codec_type","AVCodecContext_codec_type_s","AVCodecContext_bit_rate","AVCodecContext_bit_rate_s","AVCodecContext_bit_ratehi","AVCodecContext_bit_ratehi_s","AVCodecContext_channel_layout","AVCodecContext_channel_layout_s","AVCodecContext_channel_layouthi","AVCodecContext_channel_layouthi_s","AVCodecContext_channels","AVCodecContext_channels_s","AVCodecContext_channel_layoutmask","AVCodecContext_channel_layoutmask_s","AVCodecContext_ch_layout_nb_channels","AVCodecContext_ch_layout_nb_channels_s","AVCodecContext_coded_side_data","AVCodecContext_coded_side_data_s","AVCodecContext_compression_level","AVCodecContext_compression_level_s","AVCodecContext_extradata","AVCodecContext_extradata_s","AVCodecContext_extradata_size","AVCodecContext_extradata_size_s","AVCodecContext_frame_size","AVCodecContext_frame_size_s","AVCodecContext_framerate_num","AVCodecContext_framerate_den","AVCodecContext_framerate_num_s","AVCodecContext_framerate_den_s","AVCodecContext_framerate_s","AVCodecContext_gop_size","AVCodecContext_gop_size_s","AVCodecContext_height","AVCodecContext_height_s","AVCodecContext_keyint_min","AVCodecContext_keyint_min_s","AVCodecContext_level","AVCodecContext_level_s","AVCodecContext_max_b_frames","AVCodecContext_max_b_frames_s","AVCodecContext_nb_coded_side_data","AVCodecContext_nb_coded_side_data_s","AVCodecContext_pix_fmt","AVCodecContext_pix_fmt_s","AVCodecContext_profile","AVCodecContext_profile_s","AVCodecContext_rc_max_rate","AVCodecContext_rc_max_rate_s","AVCodecContext_rc_max_ratehi","AVCodecContext_rc_max_ratehi_s","AVCodecContext_rc_min_rate","AVCodecContext_rc_min_rate_s","AVCodecContext_rc_min_ratehi","AVCodecContext_rc_min_ratehi_s","AVCodecContext_sample_aspect_ratio_num","AVCodecContext_sample_aspect_ratio_den","AVCodecContext_sample_aspect_ratio_num_s","AVCodecContext_sample_aspect_ratio_den_s","AVCodecContext_sample_aspect_ratio_s","AVCodecContext_sample_fmt","AVCodecContext_sample_fmt_s","AVCodecContext_sample_rate","AVCodecContext_sample_rate_s","AVCodecContext_strict_std_compliance","AVCodecContext_strict_std_compliance_s","AVCodecContext_time_base_num","AVCodecContext_time_base_den","AVCodecContext_time_base_num_s","AVCodecContext_time_base_den_s","AVCodecContext_time_base_s","AVCodecContext_pkt_timebase_num","AVCodecContext_pkt_timebase_den","AVCodecContext_pkt_timebase_num_s","AVCodecContext_pkt_timebase_den_s","AVCodecContext_pkt_timebase_s","AVCodecContext_qmax","AVCodecContext_qmax_s","AVCodecContext_qmin","AVCodecContext_qmin_s","AVCodecContext_width","AVCodecContext_width_s","avcodec_free_context_js","av_frame_alloc","av_frame_clone","av_frame_free","av_frame_get_buffer","av_frame_make_writable","av_frame_ref","av_frame_unref","av_get_bytes_per_sample","av_get_sample_fmt_name","av_pix_fmt_desc_get","AVPixFmtDescriptor_comp_depth","ff_frame_rescale_ts_js","ff_copyout_frame","ff_copyout_frame_video","ff_frame_video_packed_size","ff_copyout_frame_video_packed","ff_copyout_frame_video_imagedata","ff_copyout_frame_ptr","ff_copyin_frame","AVFrame_channel_layout","AVFrame_channel_layout_s","AVFrame_channel_layouthi","AVFrame_channel_layouthi_s","AVFrame_channels","AVFrame_channels_s","AVFrame_channel_layoutmask","AVFrame_channel_layoutmask_s","AVFrame_ch_layout_nb_channels","AVFrame_ch_layout_nb_channels_s","AVFrame_crop_bottom","AVFrame_crop_bottom_s","AVFrame_crop_left","AVFrame_crop_left_s","AVFrame_crop_right","AVFrame_crop_right_s","AVFrame_crop_top","AVFrame_crop_top_s","AVFrame_data_a","AVFrame_data_a_s","AVFrame_duration","AVFrame_duration_s","AVFrame_flags","AVFrame_flags_s","AVFrame_format","AVFrame_format_s","AVFrame_height","AVFrame_height_s","AVFrame_key_frame","AVFrame_key_frame_s","AVFrame_linesize_a","AVFrame_linesize_a_s","AVFrame_nb_samples","AVFrame_nb_samples_s","AVFrame_pict_type","AVFrame_pict_type_s","AVFrame_pts","AVFrame_pts_s","AVFrame_ptshi","AVFrame_ptshi_s","AVFrame_best_effort_timestamp","AVFrame_best_effort_timestamp_s","AVFrame_best_effort_timestamphi","AVFrame_best_effort_timestamphi_s","AVFrame_sample_aspect_ratio_num","AVFrame_sample_aspect_ratio_den","AVFrame_sample_aspect_ratio_num_s","AVFrame_sample_aspect_ratio_den_s","AVFrame_sample_aspect_ratio_s","AVFrame_sample_rate","AVFrame_sample_rate_s","AVFrame_time_base_num","AVFrame_time_base_den","AVFrame_time_base_num_s","AVFrame_time_base_den_s","AVFrame_time_base_s","AVFrame_width","AVFrame_width_s","AVPixFmtDescriptor_flags","AVPixFmtDescriptor_flags_s","AVPixFmtDescriptor_log2_chroma_h","AVPixFmtDescriptor_log2_chroma_h_s","AVPixFmtDescriptor_log2_chroma_w","AVPixFmtDescriptor_log2_chroma_w_s","AVPixFmtDescriptor_nb_components","AVPixFmtDescriptor_nb_components_s","av_frame_free_js","av_buffersink_get_frame","av_buffersink_get_time_base_num","av_buffersink_get_time_base_den","av_buffersink_set_frame_size","ff_buffersink_set_ch_layout","av_buffersrc_add_frame_flags","avfilter_free","avfilter_get_by_name","avfilter_graph_alloc","avfilter_graph_config","avfilter_graph_create_filter_js","avfilter_graph_free","avfilter_graph_parse","avfilter_inout_alloc","avfilter_inout_free","avfilter_link","LIBAVFILTER_VERSION_INT","ff_init_filter_graph","ff_filter_multi","ff_decode_filter_multi","AVFilterInOut_filter_ctx","AVFilterInOut_filter_ctx_s","AVFilterInOut_name","AVFilterInOut_name_s","AVFilterInOut_next","AVFilterInOut_next_s","AVFilterInOut_pad_idx","AVFilterInOut_pad_idx_s","avfilter_graph_free_js","avfilter_inout_free_js"],y=["copyin_u8","copyout_u8","copyin_s16","copyout_s16","copyin_s32","copyout_s32","copyin_f32","copyout_f32","createLazyFile","ff_block_reader_dev_send","ff_reader_dev_send","ff_reader_dev_waiting","mkblockreaderdev","mkdev","mkfsfhfile","mkreadaheadfile","mkreaderdev","mkstreamwriterdev","mkworkerfsfile","mkwriterdev","mountwriterfs","readFile","unlink","unlinkfsfhfile","unlinkreadaheadfile","unlinkworkerfsfile","unmount","writeFile"];return l.libavjsMode=h,h==="worker"?(p(w),p(y)):h==="threads"?(p(w),_(y)):(_(w),_(y)),Object.assign(l,i),l}))}})();({base:uy,isWebAssemblySupported:dy,isThreadingSupported:ly,target:fy,VER:hy,CONFIG:py,DBG:my,factories:_y,i64tof64:wy,f64toi64:gy,i64ToBigInt:yy,bigIntToi64:by,ff_channel_layout:vy,ff_channels:Ay,AV_VERSION_INT:xy,AV_TIME_BASE:Sy,AV_NOPTS_VALUE_I64:Ey,AV_NOPTS_VALUE_LO:ky,AV_NOPTS_VALUE_HI:Ty,AV_NOPTS_VALUE:My,AV_OPT_SEARCH_CHILDREN:Iy,AVMEDIA_TYPE_UNKNOWN:Py,AVMEDIA_TYPE_VIDEO:zy,AVMEDIA_TYPE_AUDIO:Ry,AVMEDIA_TYPE_DATA:Fy,AVMEDIA_TYPE_SUBTITLE:Dy,AVMEDIA_TYPE_ATTACHMENT:Cy,AV_SAMPLE_FMT_NONE:Oy,AV_SAMPLE_FMT_U8:Vy,AV_SAMPLE_FMT_S16:Ly,AV_SAMPLE_FMT_S32:Uy,AV_SAMPLE_FMT_FLT:By,AV_SAMPLE_FMT_DBL:$y,AV_SAMPLE_FMT_U8P:Ny,AV_SAMPLE_FMT_S16P:qy,AV_SAMPLE_FMT_S32P:Zy,AV_SAMPLE_FMT_FLTP:Gy,AV_SAMPLE_FMT_DBLP:jy,AV_SAMPLE_FMT_S64:Wy,AV_SAMPLE_FMT_S64P:Hy,AV_SAMPLE_FMT_NB:Xy,AV_PIX_FMT_NONE:Yy,AV_PIX_FMT_YUV420P:Ky,AV_PIX_FMT_YUYV422:Qy,AV_PIX_FMT_RGB24:Jy,AV_PIX_FMT_BGR24:eb,AV_PIX_FMT_YUV422P:tb,AV_PIX_FMT_YUV444P:rb,AV_PIX_FMT_YUV410P:nb,AV_PIX_FMT_YUV411P:ib,AV_PIX_FMT_GRAY8:sb,AV_PIX_FMT_MONOWHITE:ob,AV_PIX_FMT_MONOBLACK:ab,AV_PIX_FMT_PAL8:cb,AV_PIX_FMT_YUVJ420P:ub,AV_PIX_FMT_YUVJ422P:db,AV_PIX_FMT_YUVJ444P:lb,AV_PIX_FMT_UYVY422:fb,AV_PIX_FMT_UYYVYY411:hb,AV_PIX_FMT_BGR8:pb,AV_PIX_FMT_BGR4:mb,AV_PIX_FMT_BGR4_BYTE:_b,AV_PIX_FMT_RGB8:wb,AV_PIX_FMT_RGB4:gb,AV_PIX_FMT_RGB4_BYTE:yb,AV_PIX_FMT_NV12:bb,AV_PIX_FMT_NV21:vb,AV_PIX_FMT_ARGB:Ab,AV_PIX_FMT_RGBA:xb,AV_PIX_FMT_ABGR:Sb,AV_PIX_FMT_BGRA:Eb,AV_PIX_FMT_GRAY16BE:kb,AV_PIX_FMT_GRAY16LE:Tb,AV_PIX_FMT_YUV440P:Mb,AV_PIX_FMT_YUVJ440P:Ib,AV_PIX_FMT_YUVA420P:Pb,AV_PIX_FMT_RGB48BE:zb,AV_PIX_FMT_RGB48LE:Rb,AV_PIX_FMT_RGB565BE:Fb,AV_PIX_FMT_RGB565LE:Db,AV_PIX_FMT_RGB555BE:Cb,AV_PIX_FMT_RGB555LE:Ob,AV_PIX_FMT_BGR565BE:Vb,AV_PIX_FMT_BGR565LE:Lb,AV_PIX_FMT_BGR555BE:Ub,AV_PIX_FMT_BGR555LE:Bb,AVIO_FLAG_READ:$b,AVIO_FLAG_WRITE:Nb,AVIO_FLAG_READ_WRITE:qb,AVIO_FLAG_NONBLOCK:Zb,AVIO_FLAG_DIRECT:Gb,AVFMT_FLAG_NOBUFFER:jb,AVFMT_FLAG_FLUSH_PACKETS:Wb,AVSEEK_FLAG_BACKWARD:Hb,AVSEEK_FLAG_BYTE:Xb,AVSEEK_FLAG_ANY:Yb,AVSEEK_FLAG_FRAME:Kb,AVDISCARD_NONE:Qb,AVDISCARD_DEFAULT:Jb,AVDISCARD_NONREF:ev,AVDISCARD_BIDIR:tv,AVDISCARD_NONINTRA:rv,AVDISCARD_NONKEY:nv,AVDISCARD_ALL:iv,AV_LOG_QUIET:sv,AV_LOG_PANIC:ov,AV_LOG_FATAL:av,AV_LOG_ERROR:cv,AV_LOG_WARNING:uv,AV_LOG_INFO:dv,AV_LOG_VERBOSE:lv,AV_LOG_DEBUG:fv,AV_LOG_TRACE:hv,AV_PKT_FLAG_KEY:pv,AV_PKT_FLAG_CORRUPT:mv,AV_PKT_FLAG_DISCARD:_v,AV_PKT_FLAG_TRUSTED:wv,AV_PKT_FLAG_DISPOSABLE:gv,E2BIG:yv,EPERM:bv,EADDRINUSE:vv,EADDRNOTAVAIL:Av,EAFNOSUPPORT:xv,EAGAIN:Sv,EALREADY:Ev,EBADF:kv,EBADMSG:Tv,EBUSY:Mv,ECANCELED:Iv,ECHILD:Pv,ECONNABORTED:zv,ECONNREFUSED:Rv,ECONNRESET:Fv,EDEADLOCK:Dv,EDESTADDRREQ:Cv,EDOM:Ov,EDQUOT:Vv,EEXIST:Lv,EFAULT:Uv,EFBIG:Bv,EHOSTUNREACH:$v,EIDRM:Nv,EILSEQ:qv,EINPROGRESS:Zv,EINTR:Gv,EINVAL:jv,EIO:Wv,EISCONN:Hv,EISDIR:Xv,ELOOP:Yv,EMFILE:Kv,EMLINK:Qv,EMSGSIZE:Jv,EMULTIHOP:eA,ENAMETOOLONG:tA,ENETDOWN:rA,ENETRESET:nA,ENETUNREACH:iA,ENFILE:sA,ENOBUFS:oA,ENODEV:aA,ENOENT:cA,AVERROR_EOF:uA,LibAV:dA}=U),lA=U});var Ge,Zi=ge(()=>{Ge=class{constructor(e){{this.type=e.type,this.timestamp=e.timestamp,typeof e.duration=="number"?this.duration=e.duration:this.duration=null,this.byteLength=e.data.byteLength;let t=!1;if(e.transfer){let i;e.data.buffer?i=e.data.buffer:i=e.data;let s;e.transfer instanceof Array?s=e.transfer:s=Array.from(e.transfer);for(let a of s)if(a===i){t=!0;break}}let n=new Uint8Array(e.data.buffer||e.data,e.data.byteOffset||0,e.data.BYTES_PER_ELEMENT?e.data.BYTES_PER_ELEMENT*e.data.length:e.data.byteLength);t?this._data=n:this._data=n.slice(0)}}_libavGetData(){return this._data}copyTo(e){new Uint8Array(e.buffer||e,e.byteOffset||0).set(this._data)}}});var Rn=ge(()=>{(function(r){typeof globalThis!="object"&&(this?e():(r.defineProperty(r.prototype,"_T_",{configurable:!0,get:e}),_T_));function e(){var t=this||self;t.globalThis=t,delete r.prototype._T_}})(Object)});function su(r,e,t){switch(r){case"u8":case"u8-planar":return new Uint8Array(e,t);case"s16":case"s16-planar":return new Int16Array(e,t);case"s32":case"s32-planar":return new Int32Array(e,t);case"f32":case"f32-planar":return new Float32Array(e,t);default:throw new TypeError("Invalid AudioSampleFormat")}}function ou(r){switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new TypeError("Invalid AudioSampleFormat")}}function Fn(r){switch(r){case"u8":case"s16":case"s32":case"f32":return!0;case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!1;default:throw new TypeError("Invalid AudioSampleFormat")}}var ft,Gi=ge(()=>{Rn();ft=class r{constructor(e){r._checkValidAudioDataInit(e);{this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp;let t=!1;if(e.transfer){let a;e.data.buffer?a=e.data.buffer:a=e.data;let o;e.transfer instanceof Array?o=e.transfer:o=Array.from(e.transfer);for(let c of o)if(c===a){t=!0;break}}let n,i=0;t?(n=e.data,i=e.data.byteOffset||0):n=e.data.slice(0);let s=su(e.format,n.buffer||n,i);this._data=s}this.duration=e.numberOfFrames/e.sampleRate*1e6}toNative(e={}){let t=new globalThis.AudioData({data:this._data,format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,transfer:e.transfer?[this._data.buffer]:[]});return e.transfer&&this.close(),t}static fromNative(e){let t=e,i=Fn(t.format)?1:t.numberOfChannels,s=t.allocationSize({format:t.format,planeIndex:0}),a=new Uint8Array(s*i);for(let o=0;o<i;o++)t.copyTo(a.subarray(o*s),{format:t.format,planeIndex:o});return new r({data:a,format:t.format,sampleRate:t.sampleRate,numberOfFrames:t.numberOfFrames,numberOfChannels:t.numberOfChannels,timestamp:t.timestamp,transfer:[a.buffer]})}_libavGetData(){return this._data}static _checkValidAudioDataInit(e){if(e.sampleRate<=0)throw new TypeError(`Invalid sample rate ${e.sampleRate}`);if(e.numberOfFrames<=0)throw new TypeError(`Invalid number of frames ${e.numberOfFrames}`);if(e.numberOfChannels<=0)throw new TypeError(`Invalid number of channels ${e.numberOfChannels}`);{let t=e.numberOfFrames*e.numberOfChannels,i=ou(e.format)*t;if(e.data.byteLength<i)throw new TypeError(`This audio data must be at least ${i} bytes`)}}allocationSize(e){if(this._data===null)throw new DOMException("Detached","InvalidStateError");let t=this._computeCopyElementCount(e),n=this.format;return e.format&&(n=e.format),ou(n)*t}_computeCopyElementCount(e){let t=this.format;e.format&&(t=e.format);let n=Fn(t);if(n){if(e.planeIndex>0)throw new RangeError("Invalid plane")}else if(e.planeIndex>=this.numberOfChannels)throw new RangeError("Invalid plane");if(this.format!==t&&t!=="f32-planar")throw new DOMException("Only conversion to f32-planar is supported","NotSupportedError");let i=this.numberOfFrames,s=e.frameOffset||0;if(s>=i)throw new RangeError("Frame offset out of range");let a=i-s;if(typeof e.frameCount=="number"){if(e.frameCount>=a)throw new RangeError("Frame count out of range");a=e.frameCount}let o=a;return n&&(o*=this.numberOfChannels),o}copyTo(e,t){if(this._data===null)throw new DOMException("Detached","InvalidStateError");let n=this._computeCopyElementCount(t),i=this.format;if(t.format&&(i=t.format),ou(i)*n>e.byteLength)throw new RangeError("Buffer too small");let o=this._data.subarray(t.planeIndex*this.numberOfFrames),c=t.frameOffset||0,u=this.numberOfChannels;if(this.format===i){let d=su(i,e.buffer||e,e.byteOffset||0);Fn(i)?d.set(o.subarray(c*u,c*u+n)):d.set(o.subarray(c,c+n))}else{let d=su(i,e.buffer||e,e.byteOffset||0),f=0,l=1;switch(this.format){case"u8":case"u8-planar":f=128,l=128;break;case"s16":case"s16-planar":l=32768;break;case"s32":case"s32-planar":l=2147483648;break}if(Fn(this.format))for(let h=t.planeIndex+c*u,p=0;p<n;h+=u,p++)d[p]=(o[h]-f)/l;else for(let h=c,p=0;p<n;h++,p++)d[p]=(o[h]-f)/l}}clone(){if(this._data===null)throw new DOMException("Detached","InvalidStateError");return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._data=null}}});var au,ht,ji=ge(()=>{au=class{constructor(){let e=this._eventer=new EventTarget;this.addEventListener=e.addEventListener.bind(e),this.removeEventListener=e.removeEventListener.bind(e),this.dispatchEvent=e.dispatchEvent.bind(e)}},ht=class extends au{constructor(){super(),this.addEventListener("dequeue",e=>{this.ondequeue&&this.ondequeue(e)})}}});function Np(r){er=r}function qp(r){Up=r}function Le(){return uu(this,void 0,void 0,function*(){return cu.length?cu.shift():yield er.LibAV(Up)})}function Ue(r){cu.push(r)}function Lp(r){return uu(this,void 0,void 0,function*(){let e=yield Le(),t=[];for(let[n,i]of[["flac","flac"],["libopus","opus"],["libvorbis","vorbis"],["libaom-av1","av01"],["libvpx-vp9","vp09"],["libvpx","vp8"]])r?(yield e.avcodec_find_encoder_by_name(n))&&t.push(i):(yield e.avcodec_find_decoder_by_name(n))&&t.push(i);return Ue(e),t})}function Zp(){return uu(this,void 0,void 0,function*(){er=er||LibAV,Bp=yield Lp(!1),$p=yield Lp(!0)})}function Dn(r,e){if(typeof r=="string"){r=r.replace(/\..*/,"");let t=r;switch(r){case"flac":if(typeof e.description>"u")return null;break;case"opus":if(typeof e.description<"u")return null;t="libopus";break;case"vorbis":if(typeof e.description>"u")return null;t="libvorbis";break;case"av01":t="libaom-av1";break;case"vp09":t="libvpx-vp9";break;case"vp8":t="libvpx";break;case"mp3":case"mp4a":case"ulaw":case"alaw":case"avc1":case"avc3":case"hev1":case"hvc1":return null;default:throw new TypeError("Unrecognized codec")}return Bp.indexOf(r)>=0?{codec:t}:null}else return r.libavjs}function Cn(r,e){if(typeof r=="string"){let t=r.split(".");r=t[0];let n=r,i={},s={},a=!1;switch(r){case"flac":if(i.sample_fmt=2,i.bit_rate=0,typeof e.flac=="object"&&e.flac!==null){let o=e.flac;if(typeof o.blockSize=="number"&&(i.frame_size=o.blockSize),typeof o.compressLevel=="number")return null}break;case"opus":if(n="libopus",i.sample_fmt=3,i.sample_rate=48e3,typeof e.opus=="object"&&e.opus!==null){let o=e.opus;if(typeof o.frameDuration=="number"&&(s.frame_duration=""+o.frameDuration/1e3),typeof o.complexity<"u")return null;if(typeof o.packetlossperc=="number"){if(o.packetlossperc<0||o.packetlossperc>100)return null;s.packet_loss=""+o.packetlossperc}if(typeof o.useinbandfec=="boolean"&&(s.fec=o.useinbandfec?"1":"0"),typeof o.usedtx=="boolean"||typeof o.format=="string"&&o.format!=="opus")return null}break;case"vorbis":n="libvorbis",i.sample_fmt=8;break;case"av01":if(a=!0,n="libaom-av1",e.latencyMode==="realtime"&&(s.usage="realtime",s["cpu-used"]="8"),!fA(t,i))return null;break;case"vp09":if(a=!0,n="libvpx-vp9",e.latencyMode==="realtime"&&(s.quality="realtime",s["cpu-used"]="8"),!hA(t,i))return null;break;case"vp8":a=!0,n="libvpx",e.latencyMode==="realtime"&&(s.quality="realtime",s["cpu-used"]="8");break;case"mp3":case"mp4a":case"ulaw":case"alaw":case"avc1":return null;default:throw new TypeError("Unrecognized codec")}if(!($p.indexOf(r)>=0))return null;if(a){typeof i.pix_fmt!="number"&&(i.pix_fmt=0);let o=i.width=e.width,c=i.height=e.height;e.framerate&&(i.framerate_num=Math.round(e.framerate),i.framerate_den=1);let u=e.displayWidth||e.width,d=e.displayHeight||e.height;(u!==o||d!==c)&&(i.sample_aspect_ratio_num=u*c,i.sample_aspect_ratio_den=d*o)}else if(i.sample_rate||(i.sample_rate=e.sampleRate||48e3),e.numberOfChannels){let o=e.numberOfChannels;i.channel_layout=o===1?4:(1<<o)-1}return typeof i.bit_rate!="number"&&e.bitrate&&(i.bit_rate=e.bitrate),{codec:n,ctx:i,options:s}}else return r.libavjs}function fA(r,e){if(r[1]){let t=+r[1];if(t>=0&&t<=2)e.profile=t;else throw new TypeError("Invalid AV1 profile")}if(r[2]){let t=+r[2];if(t>=0&&t<=23)e.level=t;else throw new TypeError("Invalid AV1 level")}if(r[3])switch(r[3]){case"M":break;case"H":if(e.level&&e.level>=8)return!1;throw new TypeError("The AV1 high tier is only available for level 4.0 and up");default:throw new TypeError("Invalid AV1 tier")}if(r[4]){let t=+r[3];if(t===10||t===12)return!1;if(t!==8)throw new TypeError("Invalid AV1 bit depth")}if(r[5])switch(r[5]){case"0":break;case"1":return!1;default:throw new TypeError("Invalid AV1 monochrome flag")}if(r[6])switch(r[6]){case"000":e.pix_fmt=5;break;case"100":e.pix_fmt=4;break;case"110":e.pix_fmt=0;break;case"111":return!1;default:throw new TypeError("Invalid AV1 subsampling mode")}return!0}function hA(r,e){if(r[1]){let t=+r[1];if(t>=0&&t<=3)e.profile=t;else throw new TypeError("Invalid VP9 profile")}if(r[2]){let t=[+r[2][0],+r[2][1]];if(t[0]>=1&&t[0]<=4){if(!(t[1]>=0&&t[1]<=1))throw new TypeError("Invalid VP9 level")}else if(t[0]>=5&&t[0]<=6){if(!(t[1]>=0&&t[1]<=2))throw new TypeError("Invalid VP9 level")}else throw new TypeError("Invalid VP9 level");e.level=+r[2]}if(r[3]){let t=+r[3];if(t===10||t===12)return!1;if(t!==8)throw new TypeError("Invalid VP9 bit depth")}if(r[4])switch(+r[4]){case 0:case 1:e.pix_fmt=0;break;case 2:e.pix_fmt=4;break;case 3:e.pix_fmt=5;break;default:throw new TypeError("Invalid VP9 chroma subsampling format")}return!0}var uu,er,cu,Up,Bp,$p,Fr=ge(()=>{uu=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},er=null,cu=[],Up={},Bp=null,$p=null});function tr(r,e){let t={};for(let n of e)n in r&&(t[n]=r[n]);return t}var Wi=ge(()=>{});var Hi,rr,du=ge(()=>{Gi();ji();Fr();Wi();Hi=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},rr=class extends ht{constructor(e){super(),this._p=Promise.all([]),this._libav=null,this._codec=this._c=this._pkt=this._frame=0,this._output=e.output,this._error=e.error,this.state="unconfigured",this.decodeQueueSize=0}configure(e){if(this.state==="closed")throw new DOMException("Decoder is closed","InvalidStateError");this._libav&&(this._p=this._p.then(()=>this._free())),this.state="configured",this._p=this._p.then(()=>Hi(this,void 0,void 0,function*(){let t;if(e.description)if(ArrayBuffer.isView(e.description)){let u=e.description;t=new Uint8Array(u.buffer,u.byteOffset,u.byteLength)}else{let u=e.description;t=new Uint8Array(u)}let n=Dn(e.codec,e);if(!n){this._closeAudioDecoder(new DOMException("Unsupported codec","NotSupportedError"));return}let i=this._libav=yield Le(),s=yield i.avcodec_parameters_alloc(),a=[i.AVCodecParameters_channels_s(s,e.numberOfChannels),i.AVCodecParameters_sample_rate_s(s,e.sampleRate),i.AVCodecParameters_codec_type_s(s,1)],o=0;t?(a.push(i.AVCodecParameters_extradata_size_s(s,t.byteLength)),o=yield i.calloc(t.byteLength+64,1),a.push(i.copyin_u8(o,t)),a.push(i.AVCodecParameters_extradata_s(s,o))):(a.push(i.AVCodecParameters_extradata_s(s,0)),a.push(i.AVCodecParameters_extradata_size_s(s,0))),yield Promise.all(a),[this._codec,this._c,this._pkt,this._frame]=yield i.ff_init_decoder(n.codec,s);let c=[i.AVCodecContext_time_base_s(this._c,1,1e3),i.avcodec_parameters_free_js(s)];o&&c.push(i.free(o)),yield Promise.all(c)})).catch(this._error)}_free(){return Hi(this,void 0,void 0,function*(){this._c&&(yield this._libav.ff_free_decoder(this._c,this._pkt,this._frame),this._codec=this._c=this._pkt=this._frame=0),this._libav&&(Ue(this._libav),this._libav=null)})}_closeAudioDecoder(e){this._resetAudioDecoder(e),this.state="closed",this._p=this._p.then(()=>this._free()),e.name!=="AbortError"&&(this._p=this._p.then(()=>{this._error(e)}))}_resetAudioDecoder(e){if(this.state==="closed")throw new DOMException("Decoder closed","InvalidStateError");this.state="unconfigured",this._p=this._p.then(()=>this._free())}decode(e){if(this.state!=="configured")throw new DOMException("Unconfigured","InvalidStateError");this.decodeQueueSize++,this._p=this._p.then(()=>Hi(this,void 0,void 0,function*(){let t=this._libav,n=this._c,i=this._pkt,s=this._frame,a=null;this.decodeQueueSize--,this.dispatchEvent(new CustomEvent("dequeue"));try{let o=Math.floor(e.timestamp/1e3),[c,u]=t.f64toi64(o),d={data:e._libavGetData(),pts:c,ptshi:u,dts:c,dtshi:u};e.duration&&(d.duration=Math.floor(e.duration/1e3),d.durationhi=0),a=yield t.ff_decode_multi(n,i,s,[d])}catch(o){this._p=this._p.then(()=>{this._closeAudioDecoder(o)});return}a&&this._outputAudioData(a)})).catch(this._error)}_outputAudioData(e){let t=this._libav;for(let n of e){let i,s=!1;switch(n.format){case t.AV_SAMPLE_FMT_U8:i="u8";break;case t.AV_SAMPLE_FMT_S16:i="s16";break;case t.AV_SAMPLE_FMT_S32:i="s32";break;case t.AV_SAMPLE_FMT_FLT:i="f32";break;case t.AV_SAMPLE_FMT_U8P:i="u8",s=!0;break;case t.AV_SAMPLE_FMT_S16P:i="s16",s=!0;break;case t.AV_SAMPLE_FMT_S32P:i="s32",s=!0;break;case t.AV_SAMPLE_FMT_FLTP:i="f32",s=!0;break;default:throw new DOMException("Unsupported libav format!","EncodingError")}let a=n.sample_rate,o=n.nb_samples,c=n.channels,u=t.i64tof64(n.pts,n.ptshi)*1e3,d;if(s){let l=0;for(let h=0;h<n.data.length;h++)l+=n.data[h].length;d=new n.data[0].constructor(l),l=0;for(let h=0;h<n.data.length;h++){let p=n.data[h];d.set(p,l),l+=p.length}}else d=n.data;let f=new ft({format:i,sampleRate:a,numberOfFrames:o,numberOfChannels:c,timestamp:u,data:d});this._output(f)}}flush(){if(this.state!=="configured")throw new DOMException("Invalid state","InvalidStateError");let e=this._p.then(()=>Hi(this,void 0,void 0,function*(){if(!this._c)return;let t=this._libav,n=this._c,i=this._pkt,s=this._frame,a=null;try{a=yield t.ff_decode_multi(n,i,s,[],!0)}catch(o){this._p=this._p.then(()=>{this._closeAudioDecoder(o)})}a&&this._outputAudioData(a)}));return this._p=e,e}reset(){this._resetAudioDecoder(new DOMException("Reset","AbortError"))}close(){this._closeAudioDecoder(new DOMException("Close","AbortError"))}static isConfigSupported(e){return Hi(this,void 0,void 0,function*(){let t=Dn(e.codec,e),n=!1;if(t){let i=yield Le();try{let[,s,a,o]=yield i.ff_init_decoder(t.codec);yield i.ff_free_decoder(s,a,o),n=!0}catch{}yield Ue(i)}return{supported:n,config:tr(e,["codec","sampleRate","numberOfChannels"])}})}}});var Dr,nr,lu=ge(()=>{Gi();Zi();ji();Fr();Wi();Dr=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},nr=class extends ht{constructor(e){super(),this._outputMetadata=null,this._outputMetadataFilled=!1,this._pts=null,this._p=Promise.all([]),this._libav=null,this._codec=this._c=this._frame=this._pkt=0,this._filter_in_ctx=this._filter_out_ctx=null,this._filter_graph=this._buffersrc_ctx=this._buffersink_ctx=0,this._output=e.output,this._error=e.error,this.state="unconfigured",this.encodeQueueSize=0}configure(e){let t=this;if(this.state==="closed")throw new DOMException("Encoder is closed","InvalidStateError");this._libav&&(this._p=this._p.then(()=>this._free())),this.state="configured",this._p=this._p.then(function(){return Dr(this,void 0,void 0,function*(){let n=Cn(e.codec,e);if(t._outputMetadata={decoderConfig:{codec:e.codec,sampleRate:0,numberOfChannels:0}},t._outputMetadataFilled=!1,!n){t._closeAudioEncoder(new DOMException("Unsupported codec","NotSupportedError"));return}let i=t._libav=yield Le(),s;[t._codec,t._c,t._frame,t._pkt,s]=yield i.ff_init_encoder(n.codec,n),t._pts=null,yield i.AVCodecContext_time_base_s(t._c,1,n.ctx.sample_rate),t._filter_out_ctx={sample_rate:n.ctx.sample_rate,sample_fmt:n.ctx.sample_fmt,channel_layout:n.ctx.channel_layout,frame_size:s}})}).catch(this._error)}_free(){return Dr(this,void 0,void 0,function*(){this._filter_graph&&(yield this._libav.avfilter_graph_free_js(this._filter_graph),this._filter_in_ctx=this._filter_out_ctx=null,this._filter_graph=this._buffersrc_ctx=this._buffersink_ctx=0),this._c&&(yield this._libav.ff_free_encoder(this._c,this._frame,this._pkt),this._codec=this._c=this._frame=this._pkt=0),this._libav&&(Ue(this._libav),this._libav=null)})}_closeAudioEncoder(e){this._resetAudioEncoder(e),this.state="closed",this._p=this._p.then(()=>this._free()),e.name!=="AbortError"&&(this._p=this._p.then(()=>{this._error(e)}))}_resetAudioEncoder(e){if(this.state==="closed")throw new DOMException("Encoder closed","InvalidStateError");this.state="unconfigured",this._p=this._p.then(()=>this._free())}encode(e){if(e._libavGetData()===null)throw new TypeError("Detached");if(this.state!=="configured")throw new DOMException("Unconfigured","InvalidStateError");let t=e.clone();this.encodeQueueSize++,this._p=this._p.then(()=>Dr(this,void 0,void 0,function*(){let n=this._libav,i=this._c,s=this._pkt,a=this._frame,o=null;this.encodeQueueSize--,this.dispatchEvent(new CustomEvent("dequeue"));try{let c=t._libavGetData(),u=t.numberOfFrames;if(!Fn(t.format)){let x=[];for(let P=0;P<t.numberOfChannels;P++)x.push(c.subarray(P*u,(P+1)*u));c=x}let d;switch(t.format){case"u8":d=n.AV_SAMPLE_FMT_U8;break;case"s16":d=n.AV_SAMPLE_FMT_S16;break;case"s32":d=n.AV_SAMPLE_FMT_S32;break;case"f32":d=n.AV_SAMPLE_FMT_FLT;break;case"u8-planar":d=n.AV_SAMPLE_FMT_U8P;break;case"s16-planar":d=n.AV_SAMPLE_FMT_S16P;break;case"s32-planar":d=n.AV_SAMPLE_FMT_S32P;break;case"f32-planar":d=n.AV_SAMPLE_FMT_FLTP;break;default:throw new TypeError("Invalid AudioSampleFormat")}let f=Math.floor(t.timestamp/1e3),[l,h]=n.f64toi64(f),p=t.numberOfChannels,_=p===1?4:(1<<p)-1,w=t.sampleRate,y={data:c,format:d,pts:l,ptshi:h,channel_layout:_,sample_rate:w},b=null;if(this._filter_in_ctx){let x=this._filter_in_ctx;if(x.sample_fmt!==y.format||x.channel_layout!==y.channel_layout||x.sample_rate!==y.sample_rate){let P=yield this._filter([],!0);P=P.filter(I=>{let M;return I.data[0].length?M=I.data[0].length:M=I.data.length/I.channels,M===this._filter_out_ctx.frame_size}),P.length&&(b=yield n.ff_encode_multi(i,a,s,P)),yield n.avfilter_graph_free_js(this._filter_graph),this._filter_in_ctx=null,this._filter_graph=this._buffersrc_ctx=this._buffersink_ctx=0}}if(!this._filter_graph){let x=this._filter_in_ctx={sample_rate:y.sample_rate,sample_fmt:y.format,channel_layout:y.channel_layout};[this._filter_graph,this._buffersrc_ctx,this._buffersink_ctx]=yield n.ff_init_filter_graph("aresample",x,this._filter_out_ctx)}let g=yield this._filter([y]);o=yield n.ff_encode_multi(i,a,s,g),b&&(o=b.concat(o)),o.length&&!this._outputMetadataFilled&&g&&g.length&&(yield this._getOutputMetadata(g[0]))}catch(c){this._p=this._p.then(()=>{this._closeAudioEncoder(c)})}o&&this._outputEncodedAudioChunks(o)})).catch(this._error)}_filter(e,t=!1){return Dr(this,void 0,void 0,function*(){e.length&&this._pts===null&&(this._pts=e[0].pts||0);let n=yield this._libav.ff_filter_multi(this._buffersrc_ctx,this._buffersink_ctx,this._frame,e,t);for(let i of n)i.pts=this._pts,i.ptshi=0,this._pts+=i.nb_samples;return n})}_getOutputMetadata(e){return Dr(this,void 0,void 0,function*(){let t=this._libav,n=this._c,i=yield t.AVCodecContext_extradata(n),s=yield t.AVCodecContext_extradata_size(n),a=null;i&&s&&(a=yield t.copyout_u8(i,s)),this._outputMetadata.decoderConfig.sampleRate=e.sample_rate,this._outputMetadata.decoderConfig.numberOfChannels=e.channels,a&&(this._outputMetadata.decoderConfig.description=a),this._outputMetadataFilled=!0})}_outputEncodedAudioChunks(e){let t=this._libav,n=this._filter_out_ctx.sample_rate;for(let i of e){let s=i.data,a=i.flags&1?"key":"delta",o=t.i64tof64(i.pts,i.ptshi);o=Math.floor(o/n*1e6);let c;typeof i.duration<"u"&&(c=t.i64tof64(i.duration,i.durationhi||0),c=Math.floor(c/n*1e6));let u=new Ge({data:s,type:a,timestamp:o,duration:c});this._outputMetadataFilled?this._output(u,this._outputMetadata||void 0):this._output(u)}}flush(){if(this.state!=="configured")throw new DOMException("Invalid state","InvalidStateError");let e=this._p.then(()=>Dr(this,void 0,void 0,function*(){if(!this._c)return;let t=this._libav,n=this._c,i=this._frame,s=this._pkt,a=this._buffersrc_ctx,o=this._buffersink_ctx,c=null;try{let u=null;a&&(u=yield this._filter([],!0)),c=yield t.ff_encode_multi(n,i,s,u||[],!0),!this._outputMetadataFilled&&u&&u.length&&(yield this._getOutputMetadata(u[0]))}catch(u){this._p=this._p.then(()=>{this._closeAudioEncoder(u)})}c&&this._outputEncodedAudioChunks(c)}));return this._p=e,e}reset(){this._resetAudioEncoder(new DOMException("Reset","AbortError"))}close(){this._closeAudioEncoder(new DOMException("Close","AbortError"))}static isConfigSupported(e){return Dr(this,void 0,void 0,function*(){let t=Cn(e.codec,e),n=!1;if(t){let i=yield Le();try{let[,s,a,o]=yield i.ff_init_encoder(t.codec,t);yield i.ff_free_encoder(s,a,o),n=!0}catch{}yield Ue(i)}return{supported:n,config:tr(e,["codec","sampleRate","numberOfChannels","bitrate"])}})}}});var ir,Vo=ge(()=>{Zi();ir=Ge});function Yi(r,e){let t=r.AV_PIX_FMT_RGBA;switch(e){case"I420":t=r.AV_PIX_FMT_YUV420P;break;case"I420P10":t=62;break;case"I420P12":t=123;break;case"I420A":t=r.AV_PIX_FMT_YUVA420P;break;case"I420AP10":t=87;break;case"I420AP12":throw new TypeError("YUV420P12 is not supported by libav");case"I422":t=r.AV_PIX_FMT_YUV422P;break;case"I422P10":t=64;break;case"I422P12":t=127;break;case"I422A":t=78;break;case"I422AP10":t=89;break;case"I422AP10":t=186;break;case"I444":t=r.AV_PIX_FMT_YUV444P;break;case"I444P10":t=68;break;case"I444P12":t=131;break;case"I444A":t=79;break;case"I444AP10":t=91;break;case"I444AP12":t=188;break;case"NV12":t=r.AV_PIX_FMT_NV12;break;case"RGBA":t=r.AV_PIX_FMT_RGBA;break;case"RGBX":t=119;break;case"BGRA":t=r.AV_PIX_FMT_BGRA;break;case"BGRX":t=121;break;default:throw new TypeError("Invalid VideoPixelFormat")}return t}function Xi(r){switch(r){case"I420":case"I420P10":case"I420P12":case"I422":case"I422P10":case"I422P12":case"I444":case"I444P10":case"I444P12":return 3;case"I420A":case"I420AP10":case"I420AP12":case"I422A":case"I422AP10":case"I422AP12":case"I444A":case"I444AP10":case"I444AP12":return 4;case"NV12":return 2;case"RGBA":case"RGBX":case"BGRA":case"BGRX":return 1;default:throw new DOMException("Unsupported video pixel format","NotSupportedError")}}function mA(r,e){switch(r){case"I420":case"I420A":case"I422":case"I422A":case"I444":case"I444A":return 1;case"I420P10":case"I420AP10":case"I422P10":case"I422AP10":case"I444P10":case"I444AP10":case"I420P12":case"I420AP12":case"I422P12":case"I422AP12":case"I444P12":case"I444AP12":return 2;case"NV12":return e===1?2:1;case"RGBA":case"RGBX":case"BGRA":case"BGRX":return 4;default:throw new DOMException("Unsupported video pixel format","NotSupportedError")}}function hu(r,e){if(e===0||e===3)return 1;switch(r){case"I420":case"I420P10":case"I420P12":case"I420A":case"I420AP10":case"I420AP12":case"I422":case"I422P10":case"I422P12":case"I422A":case"I422AP10":case"I422AP12":return 2;case"I444":case"I444P10":case"I444P12":case"I444A":case"I444AP10":case"I444AP12":return 1;case"NV12":return 2;case"RGBA":case"RGBX":case"BGRA":case"BGRX":return 1;default:throw new DOMException("Unsupported video pixel format","NotSupportedError")}}function Lo(r,e){if(e===0||e===3)return 1;switch(r){case"I420":case"I420P10":case"I420P12":case"I420A":case"I420AP10":case"I420AP12":return 2;case"I422":case"I422P10":case"I422P12":case"I422A":case"I422AP10":case"I422AP12":case"I444":case"I444P10":case"I444P12":case"I444A":case"I444AP10":case"I444AP12":return 1;case"NV12":return 2;case"RGBA":case"RGBX":case"BGRA":case"BGRX":return 1;default:throw new DOMException("Unsupported video pixel format","NotSupportedError")}}var pA,sr,Be,Vn=ge(()=>{Rn();pA=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},sr=null,Be=class r{constructor(e,t){if(this.format="I420",this.codedWidth=0,this.codedHeight=0,this.codedRect=null,this.visibleRect=null,this.displayWidth=0,this.displayHeight=0,this.timestamp=0,this._layout=null,this._data=null,this._nonSquarePixels=!1,this._sar_num=1,this._sar_den=1,e instanceof ArrayBuffer||e.buffer instanceof ArrayBuffer)this._constructBuffer(e,t);else if(e instanceof r||globalThis.VideoFrame&&e instanceof globalThis.VideoFrame){let n=new Uint8Array(e.allocationSize());e.copyTo(n),this._constructBuffer(n,{transfer:[n.buffer],format:e.format,codedHeight:e.codedHeight,codedWidth:e.codedWidth,colorSpace:e.colorSpace,visibleRect:t?.visibleRect||e.visibleRect,displayHeight:t?.displayHeight||e.displayHeight,displayWidth:t?.displayWidth||e.displayWidth,duration:t?.duration||e.duration,timestamp:t?.timestamp||e.timestamp,metadata:JSON.parse(JSON.stringify(t?.metadata))})}else if(e instanceof HTMLVideoElement){if(e.readyState===HTMLVideoElement.prototype.HAVE_NOTHING||e.readyState===HTMLVideoElement.prototype.HAVE_METADATA)throw new DOMException("Video is not ready for reading frames","InvalidStateError");if(e.networkState===e.NETWORK_EMPTY)throw new DOMException("Video network state is empty","InvalidStateError");this._constructCanvas(e,Object.assign(Object.assign({},t),{timestamp:t?.timestamp||e.currentTime*1e6}))}else this._constructCanvas(e,t)}_constructCanvas(e,t){let n=0,i=0;if(e.naturalWidth?(n=e.naturalWidth,i=e.naturalHeight):e.videoWidth?(n=e.videoWidth,i=e.videoHeight):e.width&&(n=e.width,i=e.height),!n||!i)throw new DOMException("Could not determine dimensions","InvalidStateError");sr===null&&(typeof OffscreenCanvas<"u"?sr=new OffscreenCanvas(n,i):(sr=document.createElement("canvas"),sr.style.display="none",document.body.appendChild(sr))),sr.width=n,sr.height=i;let s={desynchronized:!0,willReadFrequently:!0},a=sr.getContext("2d",s);a.clearRect(0,0,n,i),a.drawImage(e,0,0),this._constructBuffer(a.getImageData(0,0,n,i).data,{format:"RGBA",codedWidth:n,codedHeight:i,timestamp:t?.timestamp||0,duration:t?.duration||0,layout:[{offset:0,stride:n*4}],displayWidth:t?.displayWidth||n,displayHeight:t?.displayHeight||i})}_constructBuffer(e,t){r._checkValidVideoFrameBufferInit(t);let n=new DOMRect(0,0,t.codedWidth,t.codedHeight),i;t.visibleRect&&(i=DOMRect.fromRect(t.visibleRect)),this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;let s=this._parseVisibleRect(n,i||null),a;t.layout&&(t.layout instanceof Array?a=t.layout:a=Array.from(t.layout)),this.format=t.format;let o=this._computeLayoutAndAllocationSize(s,a||null);if(e.byteLength<o.allocationSize)throw new TypeError("data is too small for layout");let c=!1;if(t.transfer){let p;e.buffer?p=e.buffer:p=e;let _;t.transfer instanceof Array?_=t.transfer:_=Array.from(t.transfer);for(let w of _)if(w===p){c=!0;break}}let u=t.format;if(t.layout)t.layout instanceof Array?this._layout=t.layout:this._layout=Array.from(t.layout);else{let p=Xi(u),_=[],w=0;for(let y=0;y<p;y++){let b=hu(u,y),g=Lo(u,y),x=~~(this.codedWidth/b);_.push({offset:w,stride:x}),w+=x*~~(this.codedHeight/g)}this._layout=_}if(this._data=new Uint8Array(e.buffer||e,e.byteOffset||0),!c){let p=Xi(u),_=this._layout,w=1/0,y=0;for(let b=0;b<p;b++){let g=_[b],x=g.offset;x<w&&(w=x);let P=Lo(u,b);x+=g.stride*~~(this.codedHeight/P),x>y&&(y=x)}w!==0&&(_=this._layout=_.map(b=>({offset:b.offset-w,stride:b.stride}))),this._data=this._data.slice(w,y)}let d=t.codedWidth,f=t.codedHeight,l=s.left,h=s.top;this.codedRect=new DOMRect(0,0,d,f),this.visibleRect=s,t.visibleRect?this.visibleRect=DOMRect.fromRect(t.visibleRect):this.visibleRect=new DOMRect(0,0,d,f),typeof t.displayWidth=="number"?this.displayWidth=t.displayWidth:this.displayWidth=this.visibleRect.width,typeof t.displayHeight=="number"?this.displayHeight=t.displayHeight:this.displayHeight=this.visibleRect.height,this.displayWidth!==this.visibleRect.width||this.displayHeight!==this.visibleRect.height?(this._nonSquarePixels=!0,this._sar_num=this.displayWidth*this.visibleRect.width,this._sar_den=this.displayHeight*this.visibleRect.height):(this._nonSquarePixels=!1,this._sar_num=this._sar_den=1),this.timestamp=t.timestamp,this.duration=t.duration}toNative(e={}){let t=new globalThis.VideoFrame(this._data,{layout:this._layout,format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,duration:this.duration,timestamp:this.timestamp,transfer:e.transfer?[this._data.buffer]:[]});return e.transfer&&this.close(),t}static fromNative(e){let t=e,n=new Uint8Array(t.allocationSize());return t.copyTo(n),new r(n,{format:t.format,codedWidth:t.codedWidth,codedHeight:t.codedHeight,visibleRect:t.visibleRect,displayWidth:t.displayWidth,displayHeight:t.displayHeight,duration:t.duration,timestamp:t.timestamp})}_libavGetData(){return this._data}_libavGetLayout(){return this._layout}static _checkValidVideoFrameBufferInit(e){if(!e.codedWidth||!e.codedHeight)throw new TypeError("Invalid coded dimensions");if(e.visibleRect){let t=DOMRect.fromRect(e.visibleRect);if(t.x<0||!Number.isFinite(t.x)||t.y<0||!Number.isFinite(t.y)||t.width<0||!Number.isFinite(t.width)||t.height<0||!Number.isFinite(t.height))throw new TypeError("Invalid visible rectangle");if(t.y+t.height>e.codedHeight)throw new TypeError("Visible rectangle outside of coded height");if(t.x+t.width>e.codedWidth)throw new TypeError("Visible rectangle outside of coded width");if(e.displayWidth&&!e.displayHeight||!e.displayWidth&&!e.displayHeight||e.displayWidth===0||e.displayHeight===0)throw new TypeError("Invalid display dimensions")}}metadata(){if(this._data===null)throw new DOMException("Detached","InvalidStateError");return null}allocationSize(e={}){if(this._data===null)throw new DOMException("Detached","InvalidStateError");if(this.format===null)throw new DOMException("Not supported","NotSupportedError");return this._parseVideoFrameCopyToOptions(e).allocationSize}_parseVideoFrameCopyToOptions(e){let t=this.visibleRect,n=e.rect?new DOMRect(e.rect.x,e.rect.y,e.rect.width,e.rect.height):null,i=this._parseVisibleRect(t,n),s=null;return e.layout&&(e.layout instanceof Array?s=e.layout:s=Array.from(e.layout)),this._computeLayoutAndAllocationSize(i,s)}_parseVisibleRect(e,t){let n=e;if(t){if(t.width===0||t.height===0)throw new TypeError("Invalid rectangle");if(t.x+t.width>this.codedWidth)throw new TypeError("Invalid rectangle");if(t.y+t.height>this.codedHeight)throw new TypeError("Invalid rectangle");n=t}if(!this._verifyRectOffsetAlignment(n))throw new TypeError("Invalid alignment");return n}_computeLayoutAndAllocationSize(e,t){let n=Xi(this.format);if(t&&t.length!==n)throw new TypeError("Invalid layout");let i=0,s=[],a=[],o=0;for(;o<n;){let u=mA(this.format,o),d=hu(this.format,o),f=Lo(this.format,o),l={destinationOffset:0,destinationStride:0,sourceTop:Math.ceil(~~e.y/f),sourceHeight:Math.ceil(~~e.height/f),sourceLeftBytes:~~(e.x/d*u),sourceWidthBytes:~~(e.width/d*u)};if(t){let w=t[o];if(w.stride<l.sourceWidthBytes)throw new TypeError("Invalid stride");l.destinationOffset=w.offset,l.destinationStride=w.stride}else l.destinationOffset=i,l.destinationStride=l.sourceWidthBytes;let h=l.destinationStride*l.sourceHeight,p=h+l.destinationOffset;if(h>=4294967296||p>=4294967296)throw new TypeError("Plane too large");a.push(p),p>i&&(i=p);let _=0;for(;_<o;){let w=s[_];if(!(p<=w.destinationOffset||a[_]<=l.destinationOffset))throw new TypeError("Invalid plane layout");_++}s.push(l),o++}return{computedLayouts:s,allocationSize:i}}_verifyRectOffsetAlignment(e){if(!this.format)return!0;let t=0,n=Xi(this.format);for(;t<n;){let i=hu(this.format,t),s=Lo(this.format,t),a=e.x/i;if(a!==~~a)return!1;let o=e.y/s;if(o!==~~o)return!1;t++}return!0}copyTo(e,t={}){return pA(this,void 0,void 0,function*(){let n=new Uint8Array(e.buffer||e,e.byteOffset||0);if(this._data===null)throw new DOMException("Detached","InvalidStateError");if(!this.format)throw new DOMException("No format","NotSupportedError");let i=this._parseVideoFrameCopyToOptions(t);if(e.byteLength<i.allocationSize)throw new TypeError("Insufficient space");let s=[];{let a=Xi(this.format),o=0;for(;o<i.computedLayouts.length;){let c=this._layout[o].stride,u=i.computedLayouts[o],d=u.sourceTop*c;d+=u.sourceLeftBytes;let f=u.destinationOffset,l=u.sourceWidthBytes,h={offset:u.destinationOffset,stride:u.destinationStride},p=0;for(;p<u.sourceHeight;)n.set(this._data.subarray(d,d+l),f),d+=c,f+=u.destinationStride,p++;o++,s.push(h)}}return s})}clone(){return new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,layout:this._layout,transfer:[this._data.buffer]})}close(){this._data=null}}});var Qi,or,pu=ge(()=>{ji();Fr();Wi();Vn();Qi=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},or=class extends ht{constructor(e){super(),this._p=Promise.all([]),this._libav=null,this._codec=this._c=this._pkt=this._frame=0,this._output=e.output,this._error=e.error,this.state="unconfigured",this.decodeQueueSize=0}configure(e){if(this.state==="closed")throw new DOMException("Decoder is closed","InvalidStateError");this._libav&&(this._p=this._p.then(()=>this._free())),this.state="configured",this._p=this._p.then(()=>Qi(this,void 0,void 0,function*(){let t=Dn(e.codec,e);if(!t){this._closeVideoDecoder(new DOMException("Unsupported codec","NotSupportedError"));return}let n=this._libav=yield Le();[this._codec,this._c,this._pkt,this._frame]=yield n.ff_init_decoder(t.codec),yield n.AVCodecContext_time_base_s(this._c,1,1e3)})).catch(this._error)}_free(){return Qi(this,void 0,void 0,function*(){this._c&&(yield this._libav.ff_free_decoder(this._c,this._pkt,this._frame),this._codec=this._c=this._pkt=this._frame=0),this._libav&&(Ue(this._libav),this._libav=null)})}_closeVideoDecoder(e){this._resetVideoDecoder(e),this.state="closed",this._p=this._p.then(()=>this._free()),e.name!=="AbortError"&&(this._p=this._p.then(()=>{this._error(e)}))}_resetVideoDecoder(e){if(this.state==="closed")throw new DOMException("Decoder closed","InvalidStateError");this.state="unconfigured",this._p=this._p.then(()=>this._free())}decode(e){let t=this;if(this.state!=="configured")throw new DOMException("Unconfigured","InvalidStateError");this.decodeQueueSize++,this._p=this._p.then(function(){return Qi(this,void 0,void 0,function*(){let n=t._libav,i=t._c,s=t._pkt,a=t._frame,o=null;t.decodeQueueSize--,t.dispatchEvent(new CustomEvent("dequeue"));try{let c=Math.floor(e.timestamp/1e3),[u,d]=n.f64toi64(c),f={data:e._libavGetData(),pts:u,ptshi:d,dts:u,dtshi:d};e.duration&&(f.duration=Math.floor(e.duration/1e3),f.durationhi=0),o=yield n.ff_decode_multi(i,s,a,[f])}catch(c){t._p=t._p.then(()=>{t._closeVideoDecoder(c)})}o&&t._outputVideoFrames(o)})}).catch(this._error)}_outputVideoFrames(e){let t=this._libav;for(let n of e){let i;switch(n.format){case t.AV_PIX_FMT_YUV420P:i="I420";break;case 62:i="I420P10";break;case 123:i="I420P12";break;case t.AV_PIX_FMT_YUVA420P:i="I420A";break;case 87:i="I420AP10";break;case t.AV_PIX_FMT_YUV422P:i="I422";break;case 64:i="I422P10";break;case 127:i="I422P12";break;case 78:i="I422A";break;case 89:i="I422AP10";break;case 186:i="I422AP12";break;case t.AV_PIX_FMT_YUV444P:i="I444";break;case 68:i="I444P10";break;case 131:i="I444P12";break;case 79:i="I444A";break;case 91:i="I444AP10";break;case 188:i="I444AP12";break;case t.AV_PIX_FMT_NV12:i="NV12";break;case t.AV_PIX_FMT_RGBA:i="RGBA";break;case 119:i="RGBX";break;case t.AV_PIX_FMT_BGRA:i="BGRA";break;case 121:i="BGRX";break;default:throw new DOMException("Unsupported libav format!","EncodingError")}let s=n.width,a=n.height,o;n.crop?o=new DOMRect(n.crop.left,n.crop.top,s-n.crop.left-n.crop.right,a-n.crop.top-n.crop.bottom):o=new DOMRect(0,0,s,a);let c=s,u=a;if(n.sample_aspect_ratio&&n.sample_aspect_ratio[0]){let l=n.sample_aspect_ratio;l[0]>l[1]?c=~~(s*l[0]/l[1]):u=~~(a*l[1]/l[0])}let d=t.i64tof64(n.pts,n.ptshi)*1e3,f=new Be(n.data,{layout:n.layout,format:i,codedWidth:s,codedHeight:a,visibleRect:o,displayWidth:c,displayHeight:u,timestamp:d});this._output(f)}}flush(){if(this.state!=="configured")throw new DOMException("Invalid state","InvalidStateError");let e=this._p.then(()=>Qi(this,void 0,void 0,function*(){if(!this._c)return;let t=this._libav,n=this._c,i=this._pkt,s=this._frame,a=null;try{a=yield t.ff_decode_multi(n,i,s,[],!0)}catch(o){this._p=this._p.then(()=>{this._closeVideoDecoder(o)})}a&&this._outputVideoFrames(a)}));return this._p=e,e}reset(){this._resetVideoDecoder(new DOMException("Reset","AbortError"))}close(){this._closeVideoDecoder(new DOMException("Close","AbortError"))}static isConfigSupported(e){return Qi(this,void 0,void 0,function*(){let t=Dn(e.codec,e),n=!1;if(t){let i=yield Le();try{let[,s,a,o]=yield i.ff_init_decoder(t.codec);yield i.ff_free_decoder(s,a,o),n=!0}catch{}yield Ue(i)}return{supported:n,config:tr(e,["codec","codedWidth","codedHeight"])}})}}});var Ln,ar,mu=ge(()=>{Vo();ji();Fr();Wi();Vn();Ln=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},ar=class extends ht{constructor(e){super(),this._extradataSet=!1,this._extradata=null,this._nonSquarePixels=!1,this._sar_num=1,this._sar_den=1,this._p=Promise.all([]),this._libav=null,this._codec=this._c=this._frame=this._pkt=0,this._output=e.output,this._error=e.error,this._metadata=null,this.state="unconfigured",this.encodeQueueSize=0}configure(e){if(this.state==="closed")throw new DOMException("Encoder is closed","InvalidStateError");this._libav&&(this._p=this._p.then(()=>this._free())),this.state="configured",this._p=this._p.then(()=>Ln(this,void 0,void 0,function*(){let t=Cn(e.codec,e);if(!t){this._closeVideoEncoder(new DOMException("Unsupported codec","NotSupportedError"));return}let n=this._libav=yield Le();this._metadata={decoderConfig:{codec:t.codec}},[this._codec,this._c,this._frame,this._pkt]=yield n.ff_init_encoder(t.codec,t),this._extradataSet=!1,this._extradata=null,yield n.AVCodecContext_time_base_s(this._c,1,1e3);let i=e.width,s=e.height;this._sws=0,this._swsFrame=0,this._swsOut={width:i,height:s,format:t.ctx.pix_fmt};let a=e.displayWidth||i,o=e.displayHeight||s;a!==i||o!==s?(this._nonSquarePixels=!0,this._sar_num=a*s,this._sar_den=o*i):this._nonSquarePixels=!1})).catch(this._error)}_free(){return Ln(this,void 0,void 0,function*(){this._sws&&(yield this._libav.av_frame_free_js(this._swsFrame),yield this._libav.sws_freeContext(this._sws),this._sws=this._swsFrame=0,this._swsIn=this._swsOut=void 0),this._c&&(yield this._libav.ff_free_encoder(this._c,this._frame,this._pkt),this._codec=this._c=this._frame=this._pkt=0),this._libav&&(Ue(this._libav),this._libav=null)})}_closeVideoEncoder(e){this._resetVideoEncoder(e),this.state="closed",this._p=this._p.then(()=>this._free()),e.name!=="AbortError"&&(this._p=this._p.then(()=>{this._error(e)}))}_resetVideoEncoder(e){if(this.state==="closed")throw new DOMException("Encoder closed","InvalidStateError");this.state="unconfigured",this._p=this._p.then(()=>this._free())}encode(e,t={}){if(e._libavGetData()===null)throw new TypeError("Detached");if(this.state!=="configured")throw new DOMException("Unconfigured","InvalidStateError");let n=e.clone();this.encodeQueueSize++,this._p=this._p.then(()=>Ln(this,void 0,void 0,function*(){let i=this._libav,s=this._c,a=this._pkt,o=this._frame,c=this._swsOut,u=null;this.encodeQueueSize--,this.dispatchEvent(new CustomEvent("dequeue"));try{let d=Yi(i,n.format),f=n._libavGetData(),l=n._libavGetLayout(),h=Math.floor(n.timestamp/1e3),[p,_]=i.f64toi64(h),w={data:f,layout:l,format:d,pts:p,ptshi:_,width:n.codedWidth,height:n.codedHeight,crop:{left:n.visibleRect.left,right:n.visibleRect.right,top:n.visibleRect.top,bottom:n.visibleRect.bottom},key_frame:t.keyFrame?1:0,pict_type:t.keyFrame?1:0};if(w.width!==c.width||w.height!==c.height||w.format!==c.format){n._nonSquarePixels&&(w.sample_aspect_ratio=[n._sar_num,n._sar_den]);let y=this._sws,b=this._swsIn,g=this._swsFrame;(!y||w.width!==b.width||w.height!==b.height||w.format!==b.format)&&(y&&(yield i.sws_freeContext(y)),b={width:w.width,height:w.height,format:w.format},y=yield i.sws_getContext(b.width,b.height,b.format,c.width,c.height,c.format,2,0,0,0),this._sws=y,this._swsIn=b,g||(this._swsFrame=g=yield i.av_frame_alloc()));let[,x,,,,,,P]=yield Promise.all([i.ff_copyin_frame(o,w),i.sws_scale_frame(y,g,o),this._nonSquarePixels?i.AVFrame_sample_aspect_ratio_s(g,this._sar_num,this._sar_den):null,i.AVFrame_pts_s(g,p),i.AVFrame_ptshi_s(g,_),i.AVFrame_key_frame_s(g,t.keyFrame?1:0),i.AVFrame_pict_type_s(g,t.keyFrame?1:0),i.avcodec_send_frame(s,g)]);if(x<0||P<0)throw new Error("Encoding failed!");for(u=[];;){let I=yield i.avcodec_receive_packet(s,a);if(I===-i.EAGAIN)break;if(I<0)throw new Error("Encoding failed!");u.push(yield i.ff_copyout_packet(a))}}else this._nonSquarePixels&&(w.sample_aspect_ratio=[this._sar_num,this._sar_den]),u=yield i.ff_encode_multi(s,o,a,[w]);u.length&&!this._extradataSet&&(yield this._getExtradata())}catch(d){this._p=this._p.then(()=>{this._closeVideoEncoder(d)});return}u&&this._outputEncodedVideoChunks(u)})).catch(this._error)}_getExtradata(){return Ln(this,void 0,void 0,function*(){let e=this._libav,t=this._c,n=yield e.AVCodecContext_extradata(t),i=yield e.AVCodecContext_extradata_size(t);n&&i&&(this._metadata.decoderConfig.description=this._extradata=yield e.copyout_u8(n,i)),this._extradataSet=!0})}_outputEncodedVideoChunks(e){let t=this._libav;for(let n of e){let i=n.flags&1?"key":"delta",s=t.i64tof64(n.pts,n.ptshi)*1e3,a=new ir({type:i,timestamp:s,data:n.data});this._extradataSet?this._output(a,this._metadata||void 0):this._output(a)}}flush(){if(this.state!=="configured")throw new DOMException("Invalid state","InvalidStateError");let e=this._p.then(()=>Ln(this,void 0,void 0,function*(){if(!this._c)return;let t=this._libav,n=this._c,i=this._frame,s=this._pkt,a=null;try{a=yield t.ff_encode_multi(n,i,s,[],!0),this._extradataSet||(yield this._getExtradata())}catch(o){this._p=this._p.then(()=>{this._closeVideoEncoder(o)})}a&&this._outputEncodedVideoChunks(a)}));return this._p=e,e}reset(){this._resetVideoEncoder(new DOMException("Reset","AbortError"))}close(){this._closeVideoEncoder(new DOMException("Close","AbortError"))}static isConfigSupported(e){return Ln(this,void 0,void 0,function*(){let t=Cn(e.codec,e),n=!1;if(t){let i=yield Le();try{let[,s,a,o]=yield i.ff_init_encoder(t.codec,t);yield i.ff_free_encoder(s,a,o),n=!0}catch{}yield Ue(i)}return{supported:n,config:tr(e,["codec","width","height","bitrate","framerate","latencyMode"])}})}}});function Kp(r,e){return Xp(this,void 0,void 0,function*(){"importScripts"in globalThis&&(er.nolibavworker=!0),je=yield er.LibAV(Object.assign(Object.assign({},r),{noworker:!0,yesthreads:!1})),We=yield er.LibAV(r),"CanvasRenderingContext2D"in globalThis&&(wu=CanvasRenderingContext2D.prototype.drawImage,e&&(CanvasRenderingContext2D.prototype.drawImage=_A)),"OffscreenCanvasRenderingContext2D"in globalThis&&(Yp=OffscreenCanvasRenderingContext2D.prototype.drawImage,e&&(OffscreenCanvasRenderingContext2D.prototype.drawImage=wA)),_u=globalThis.createImageBitmap,e&&(globalThis.createImageBitmap=gu)})}function Uo(r,e,t,n,i,s,a,o,c,u){if(!e._data)return wu.apply(r,Array.prototype.slice.call(arguments,1));let d,f;typeof i>"u"?(a=t,o=n):typeof a>"u"?(a=t,o=n,c=i,u=s,d=void 0,f=void 0,i=void 0,s=void 0):(d=t,f=n),typeof c>"u"&&(c=e.displayWidth,u=e.displayHeight);let l=Yi(je,e.format),h=je.sws_getContext_sync(e.visibleRect.width,e.visibleRect.height,l,c,u,je.AV_PIX_FMT_RGBA,2,0,0,0),p=je.av_frame_alloc_sync(),_=je.av_frame_alloc_sync(),w,y;e._libavGetData?(w=e._libavGetData(),y=e._libavGetLayout()):(w=e._data,y=e._layout),je.ff_copyin_frame_sync(p,{data:w,layout:y,format:l,width:e.codedWidth,height:e.codedHeight,crop:{left:e.visibleRect.left,right:e.visibleRect.right,top:e.visibleRect.top,bottom:e.visibleRect.bottom}}),je.sws_scale_frame_sync(h,_,p);let b=je.ff_copyout_frame_video_imagedata_sync(_);r.putImageData(b,a,o),je.av_frame_free_js_sync(_),je.av_frame_free_js_sync(p),je.sws_freeContext_sync(h)}function _A(r,e,t,n,i,s,a,o,c){return r instanceof Be?Uo(this,r,e,t,n,i,s,a,o,c):wu.apply(this,arguments)}function wA(r,e,t,n,i,s,a,o,c){return r instanceof Be?Uo(this,r,e,t,n,i,s,a,o,c):Yp.apply(this,arguments)}function gu(r,e={}){if(!r._data)return _u.apply(globalThis,arguments);let t=Yi(We,r.format),n=typeof e.resizeWidth=="number"?e.resizeWidth:r.displayWidth,i=typeof e.resizeHeight=="number"?e.resizeHeight:r.displayHeight;return Xp(this,void 0,void 0,function*(){let[s,a,o]=yield Promise.all([We.sws_getContext(r.visibleRect.width,r.visibleRect.height,t,n,i,We.AV_PIX_FMT_RGBA,2,0,0,0),We.av_frame_alloc(),We.av_frame_alloc()]),c,u;r._libavGetData?(c=r._libavGetData(),u=r._libavGetLayout()):r._data?(c=r._data,u=r._layout):(c=new Uint8Array(r.allocationSize()),yield r.copyTo(c)),yield We.ff_copyin_frame(a,{data:c,layout:u,format:t,width:r.codedWidth,height:r.codedHeight,crop:{left:r.visibleRect.left,right:r.visibleRect.right,top:r.visibleRect.top,bottom:r.visibleRect.bottom}}),yield We.sws_scale_frame(s,o,a);let d=yield We.ff_copyout_frame_video_imagedata(o);return yield Promise.all([We.av_frame_free_js(o),We.av_frame_free_js(a),We.sws_freeContext(s)]),yield _u(d)})}var Xp,je,We,wu,Yp,_u,Qp=ge(()=>{Fr();Vn();Rn();Xp=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},je=null,We=null,wu=null,Yp=null,_u=null});function Jp(r){return Bo(this,void 0,void 0,function*(){try{if(typeof globalThis.AudioDecoder<"u"&&(yield globalThis.AudioDecoder.isConfigSupported(r)).supported)return{AudioDecoder:globalThis.AudioDecoder,EncodedAudioChunk:globalThis.EncodedAudioChunk,AudioData:globalThis.AudioData}}catch{}if((yield rr.isConfigSupported(r)).supported)return{AudioDecoder:rr,EncodedAudioChunk:Ge,AudioData:ft};throw new cr})}function em(r){return Bo(this,void 0,void 0,function*(){try{if(typeof globalThis.VideoDecoder<"u"&&(yield globalThis.VideoDecoder.isConfigSupported(r)).supported)return{VideoDecoder:globalThis.VideoDecoder,EncodedVideoChunk:globalThis.EncodedVideoChunk,VideoFrame:globalThis.VideoFrame}}catch{}if((yield or.isConfigSupported(r)).supported)return{VideoDecoder:or,EncodedVideoChunk:ir,VideoFrame:Be};throw new cr})}function tm(r){return Bo(this,void 0,void 0,function*(){try{if(typeof globalThis.AudioEncoder<"u"&&(yield globalThis.AudioEncoder.isConfigSupported(r)).supported)return{AudioEncoder:globalThis.AudioEncoder,EncodedAudioChunk:globalThis.EncodedAudioChunk,AudioData:globalThis.AudioData}}catch{}if((yield nr.isConfigSupported(r)).supported)return{AudioEncoder:nr,EncodedAudioChunk:Ge,AudioData:ft};throw new cr})}function rm(r){return Bo(this,void 0,void 0,function*(){try{if(typeof globalThis.VideoEncoder<"u"&&(yield globalThis.VideoEncoder.isConfigSupported(r)).supported)return{VideoEncoder:globalThis.VideoEncoder,EncodedVideoChunk:globalThis.EncodedVideoChunk,VideoFrame:globalThis.VideoFrame}}catch{}if((yield ar.isConfigSupported(r)).supported)return{VideoEncoder:ar,EncodedVideoChunk:ir,VideoFrame:Be};throw new cr})}var Bo,cr,nm=ge(()=>{Zi();Gi();du();lu();Vo();Vn();pu();mu();Rn();Bo=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},cr=class extends Error{constructor(){super("The requested configuration is not supported")}}});var im={};ke(im,{AudioData:()=>xA,AudioDecoder:()=>SA,AudioEncoder:()=>EA,EncodedAudioChunk:()=>AA,EncodedVideoChunk:()=>kA,UnsupportedException:()=>RA,VideoDecoder:()=>MA,VideoEncoder:()=>IA,VideoFrame:()=>TA,canvasDrawImage:()=>PA,createImageBitmap:()=>zA,getAudioDecoder:()=>FA,getAudioEncoder:()=>CA,getVideoDecoder:()=>DA,getVideoEncoder:()=>OA,load:()=>vA});function vA(r={}){return bA(this,void 0,void 0,function*(){let e={};if(r.libavOptions&&Object.assign(e,r.libavOptions),!r.LibAV&&typeof globalThis.LibAV>"u"&&(yield new Promise((t,n)=>{e.noworker=!0;let i="https://cdn.jsdelivr.net/npm/@libav.js/variant-webm-vp9@6.7.7/dist";globalThis.LibAV={base:i};let s="libav-6.7.7.1.1-webm-vp9.js";if(typeof importScripts<"u")importScripts(`${i}/${s}`),t(void 0);else{let a=document.createElement("script");a.src=`${i}/${s}`,a.onload=t,a.onerror=n,document.body.appendChild(a)}})),r.LibAV&&Np(r.LibAV),qp(e),yield Zp(),r.polyfill)for(let t of[["EncodedAudioChunk",Ge],["AudioData",ft],["AudioDecoder",rr],["AudioEncoder",nr],["EncodedVideoChunk",ir],["VideoFrame",Be],["VideoDecoder",or],["VideoEncoder",ar]])globalThis[t[0]]||(globalThis[t[0]]=t[1]);yield Kp(e,!!r.polyfill)})}var bA,AA,xA,SA,EA,kA,TA,MA,IA,PA,zA,RA,FA,DA,CA,OA,sm=ge(()=>{Zi();Gi();du();lu();Vo();Vn();pu();mu();Qp();nm();Fr();Rn();bA=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})};AA=Ge,xA=ft,SA=rr,EA=nr,kA=ir,TA=Be,MA=or,IA=ar,PA=Uo,zA=gu,RA=cr,FA=Jp,DA=em,CA=tm,OA=rm});var ye=typeof import.meta.env<"u"&&import.meta.env?.MODE!=="production",qo=Symbol.for("@moq/signals"),ns=Symbol.for("@moq/signals.getter");function Zo(r,e){return typeof r=="object"&&r!==null&&e in r}var A=class r{#e;#t=new Set;#r=new Set;#n=!1;#i;#s=!1;#o=!1;[qo]=!0;[ns]=!0;constructor(e){this.#e=e}static from(e){return Zo(e,qo)?e:new r(e)}peek(){return this.#e}set(e,t){if(this.#s||(this.#i=this.#e,this.#s=!0),this.#e=e,t!==!1){if(t===!0&&(this.#o=!0),this.#t.size===0&&this.#r.size===0){this.#s=!1,this.#i=void 0,this.#o=!1;return}this.#n||(this.#n=!0,queueMicrotask(()=>this.#a()))}}#a(){this.#n=!1,this.#s=!1;let e=this.#i;this.#i=void 0;let t=this.#o;if(this.#o=!1,!t&&ku(e,this.#e))return;let n=this.#e,i=this.#r;this.#r=new Set;for(let s of this.#t)try{s(n)}catch(a){console.error("signal subscriber error",a)}for(let s of i)try{s(n)}catch(a){console.error("signal changed error",a)}}update(e,t=!0){let n=e(this.#e);this.set(n,t)}mutate(e,t=!0){let n=e(this.#e);return this.set(this.#e,t),n}subscribe(e){if(this.#t.add(e),ye&&this.#t.size>=100&&Number.isInteger(Math.log10(this.#t.size)))throw new Error("signal has too many subscribers; may be leaking");return()=>this.#t.delete(e)}changed(e){return e?(this.#r.add(e),()=>this.#r.delete(e)):new Promise(t=>{this.#r.add(t)})}watch(e){let t=this.subscribe(e);return queueMicrotask(()=>e(this.#e)),t}static async race(...e){let t=[],n=await new Promise(i=>{for(let s of e)t.push(s.changed(i))});for(let i of t)i();return n}},et=class{#e=new A(void 0);[ns]=!0;set(e){if(this.#e.peek()!==void 0)throw new Error("Once has already settled");this.#e.set(e)}peek(){return this.#e.peek()}changed(e){return e?this.#e.changed(e):this.#e.changed()}subscribe(e){return this.#e.subscribe(e)}then(e,t){let n=this.#e.peek();return(n!==void 0?Promise.resolve(n):this.#e.changed().then(s=>s)).then(e,t)}};function N(r){if(Zo(r,ns)||Zo(r,qo))return r;if($m(r))throw new Error("getter() requires a Signal, Computed, or Once; a foreign readable would become a constant");return new A(r)}function $m(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.peek=="function"&&typeof e.subscribe=="function"&&typeof e.changed=="function"}var j=class r{static#e=new FinalizationRegistry(e=>{console.warn(`Signals was garbage collected without being closed:
|
|
2
|
+
${e}`)});#t;#r=[];#n=[];#i=[];#s;#o=!1;#a;#c;#d=new AbortController;#l=!1;#u=!1;constructor(e){if(ye){let t=new Error("created here:").stack??"No stack";r.#e.register(this,t,this)}this.#t=e,ye&&(this.#s=new Error().stack),this.#a=Promise.withResolvers(),this.#c=Promise.withResolvers(),e&&this.#f()}#f(){this.#o||(this.#o=!0,queueMicrotask(()=>this.#p().catch(e=>{console.error("effect error",e,this.#s)})))}async#p(){if(this.#r!==void 0){this.#u=!0,this.#a.resolve(),this.#d.abort();for(let e of this.#n)e();this.#n.length=0;for(let e of this.#r)e();if(this.#r.length=0,this.#i.length>0){let e=ye?setTimeout(()=>{this.#r!==void 0&&console.warn("spawn is still running after 5s; the effect cannot rerun until it settles",this.#s)},5e3):void 0;try{for(;this.#r!==void 0&&this.#i.length>0;){let t=this.#i;this.#i=[],await Promise.race([Promise.all(t),this.#c.promise])}}catch(t){console.error("async effect error",t),this.#s&&console.error("stack",this.#s)}finally{e!==void 0&&clearTimeout(e)}}this.#r!==void 0&&(this.#o=!1,this.#u=!1,this.#a=Promise.withResolvers(),this.#d=new AbortController,this.#l=!1,this.#t&&(this.#t(this),ye&&this.#r!==void 0&&this.#n.length===0&&this.#r.length===0&&this.#i.length===0&&!this.#l&&console.warn("Effect did not subscribe to any signals; it will never rerun.",this.#s)))}}get(e){if(this.#r===void 0)return ye&&console.warn("Effect.get called when closed, returning current value"),e.peek();let t=e.peek(),n=e.changed(()=>this.#f());return this.#n.push(n),t}set(e,t,...n){if(this.#r===void 0){ye&&console.warn("Effect.set called when closed, ignoring");return}e.set(t);let i=n[0],s=i===void 0?void 0:i;this.cleanup(()=>e.set(s))}spawn(e){let t=e().catch(n=>{console.error("spawn error",n)});if(this.#r===void 0){ye&&console.warn("Effect.spawn called when closed");return}this.#i.push(t)}timer(e,t){if(this.#r===void 0){ye&&console.warn("Effect.timer called when closed, ignoring");return}let n;n=setTimeout(()=>{n=void 0,e()},t),this.cleanup(()=>n&&clearTimeout(n))}timeout(e,t){if(this.#r===void 0){ye&&console.warn("Effect.timeout called when closed, ignoring");return}let n=new r(e),i=setTimeout(()=>{n.close(),i=void 0},t);this.#r.push(()=>{i&&(clearTimeout(i),n.close())})}animate(e){if(this.#r===void 0){ye&&console.warn("Effect.animate called when closed, ignoring");return}let t=requestAnimationFrame(n=>{e(n),t=void 0});this.cleanup(()=>{t&&cancelAnimationFrame(t)})}interval(e,t){if(this.#r===void 0){ye&&console.warn("Effect.interval called when closed, ignoring");return}let n=setInterval(()=>{e()},t);this.cleanup(()=>clearInterval(n))}run(e){if(this.#r===void 0)return ye&&console.warn("Effect.run called when closed, ignoring"),()=>{};let t=new r(e),n=()=>t.close();return this.#r.push(n),()=>{t.close();let i=this.#r,s=i?.indexOf(n)??-1;s!==-1&&i?.splice(s,1)}}computed(e){let t=new Go(e);return this.cleanup(()=>t.close()),t}getAll(e){let t=[];for(let n of e){let i=this.get(n);if(!i)return;t.push(i)}return t}subscribe(e,t){if(this.#r===void 0){ye&&console.warn("Effect.subscribe called when closed, running once"),t(e.peek());return}this.run(n=>{let i=n.get(e);t(i)})}event(e,t,n,i){if(this.#r===void 0){ye&&console.warn("Effect.eventListener called when closed, ignoring");return}let s=this.abort,a=typeof i!="boolean"&&i?.signal?AbortSignal.any([s,i.signal]):s,o=typeof i=="boolean"?{capture:i,signal:a}:{...i,signal:a};e.addEventListener(t,n,o)}cleanup(e){if(this.#r===void 0||this.#u){e();return}this.#r.push(e)}close(){if(this.#r!==void 0){this.#c.resolve(),this.#a.resolve(),this.#d.abort();for(let e of this.#r)e();this.#r=void 0;for(let e of this.#n)e();this.#n.length=0,this.#i.length=0,ye&&r.#e.unregister(this)}}get closed(){return this.#c.promise}get cancel(){return this.#a.promise}get abort(){return this.#l=!0,this.#d.signal}proxy(e,t){this.subscribe(t,n=>e.update(()=>n))}},Go=class{#e=new A(void 0);#t;[ns]=!0;constructor(e){this.#t=new j(t=>{this.#e.set(e(t))})}peek(){return this.#e.peek()}changed(e){return e?this.#e.changed(e):this.#e.changed()}subscribe(e){return this.#e.subscribe(e)}close(){this.#t.close()}};function ku(r,e){if(r===e)return!0;if(r===null||e===null||typeof r!="object"||typeof e!="object")return!1;let t=Object.getPrototypeOf(r),n=Object.getPrototypeOf(e);if(t!==n||t!==Object.prototype&&t!==Array.prototype)return!1;let i=Object.keys(r),s=Object.keys(e);if(i.length!==s.length)return!1;for(let a of i)if(!ku(r[a],e[a]))return!1;return!0}var W={};ke(W,{MAX_PARTS:()=>Or,decode:()=>$e,empty:()=>Me,encode:()=>Te,from:()=>is,hasPrefix:()=>Tu,join:()=>De,normalizeRelative:()=>Nm,parts:()=>ss,relative:()=>Gm,resolve:()=>qm,stripPrefix:()=>tt,tryResolve:()=>Zm});var Or=32;function is(...r){return r.join("/").replace(/\/+/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function ss(r){return r===""?[]:r.split("/")}function $e(r){let e=is(r);return Te(e)}function Te(r){if(ss(r).length>32)throw new Error("path exceeds 32 parts");return r}function Tu(r,e){return r===""?!0:e.startsWith(r)?e.length===r.length?!0:e[r.length]==="/":!1}function tt(r,e){return Tu(r,e)?r===""?e:e.length===r.length?"":e.slice(r.length+1):null}function De(r,e){return r===""?e:e===""?r:`${r}/${e}`}function Me(){return""}function Nm(r){let e=r.split("/"),t=e.filter(n=>n!==""&&n!==".").join("/");return t===""&&e.includes(".")?".":t}function qm(r,e){if(e==="")return r;let t=r===""?[]:r.split("/");t.pop();for(let n of e.split("/"))n===""||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function Zm(r,e){if(e==="")return r;let t=r===""?[]:r.split("/");t.pop();for(let n of e.split("/"))if(!(n===""||n==="."))if(n===".."){if(t.pop()===void 0)return}else t.push(n);return t.join("/")}function Gm(r,e){if(r===e)return"";let t=e===""?[]:e.split("/");t.pop();let n=r===""?[]:r.split("/"),i=0;for(;i<t.length&&i<n.length&&t[i]===n[i];)i+=1;let s=n.slice(i);if(s.some(o=>o==="."||o===".."))return;let a=Array(t.length-i).fill("..").concat(s);return a.length===0?".":a.join("/")}var jo=class{queue=new A([]);closed=new et};function Pu(r,e){r.closed.peek()===void 0&&(r.closed.set(e??null),r.queue.mutate(t=>{t.length=0}))}var Pt=class{prefix;#e=new jo;constructor(e=Me()){this.prefix=e}get closed(){return this.#e.closed}consume(){return zu(this.prefix,this.#e)}append(e){if(this.#e.closed.peek()!==void 0)throw new Error("announcements are closed");this.#e.queue.mutate(t=>{t.push(e)})}close(e){Pu(this.#e,e)}},zu,Mu=class r{prefix;#e;constructor(e,t){this.prefix=e,this.#e=t}get closed(){return this.#e.closed}static{zu=(e,t)=>new r(e,t)}async next(){for(;;){let e=this.#e.queue.peek().shift();if(e)return e;let t=this.#e.closed.peek();if(t instanceof Error)throw t;if(t!==void 0)return;await A.race(this.#e.queue,this.#e.closed)}}close(e){Pu(this.#e,e)}},Iu=new WeakSet,zt=class{path;active;#e=new A(void 0);#t=new j;constructor({connection:e,path:t}){this.path=t,this.active=this.#e;let n=N(e);this.#t.run(i=>{let s=i.get(n);if(!s)return;if(!s.discovery){Iu.has(s)||(Iu.add(s),console.warn("relay does not support broadcast discovery; consuming without waiting."));let u=s.consume(t);i.cleanup(()=>u.close()),i.set(this.#e,u,void 0),i.spawn(async()=>{await Promise.race([i.cancel,s.closed]),this.#e.peek()===u&&this.#e.set(void 0)});return}let a=s.announced(t);i.cleanup(()=>a.close());let o,c=()=>{let u=o;o?.close(),o=void 0,this.#e.peek()===u&&this.#e.set(void 0)};i.cleanup(c),i.spawn(async()=>{try{for(;;){let u=await Promise.race([i.cancel,a.next()]);if(!u)break;if(u.path===Me())if(u.active){if(o&&o.closed.peek()===void 0)continue;o?.close(),o=s.consume(t),this.#e.set(o)}else c()}}catch(u){console.warn("broadcast discovery failed",u)}c()})})}close(){this.#t.close()}};var $n={makeRequest:()=>{throw new Error("track.ts not loaded")}};var E={};ke(E,{Micro:()=>Wm,Milli:()=>Nn,Nano:()=>jm,Second:()=>Hm,Timescale:()=>ne,Timestamp:()=>xe});var jm=Object.assign(r=>r,{zero:0,fromMicro:r=>r*1e3,fromMilli:r=>r*1e6,fromSecond:r=>r*1e9,toMicro:r=>r/1e3,toMilli:r=>r/1e6,toSecond:r=>r/1e9,now:()=>performance.now()*1e6,add:(r,e)=>r+e,sub:(r,e)=>r-e,mul:(r,e)=>r*e,div:(r,e)=>r/e,max:(r,e)=>Math.max(r,e),min:(r,e)=>Math.min(r,e)}),Wm=Object.assign(r=>r,{zero:0,fromNano:r=>r/1e3,fromMilli:r=>r*1e3,fromSecond:r=>r*1e6,toNano:r=>r*1e3,toMilli:r=>r/1e3,toSecond:r=>r/1e6,now:()=>performance.now()*1e3,add:(r,e)=>r+e,sub:(r,e)=>r-e,mul:(r,e)=>r*e,div:(r,e)=>r/e,max:(r,e)=>Math.max(r,e),min:(r,e)=>Math.min(r,e)}),Nn=Object.assign(r=>r,{zero:0,fromNano:r=>r/1e6,fromMicro:r=>r/1e3,fromSecond:r=>r*1e3,toNano:r=>r*1e6,toMicro:r=>r*1e3,toSecond:r=>r/1e3,now:()=>performance.now(),add:(r,e)=>r+e,sub:(r,e)=>r-e,mul:(r,e)=>r*e,div:(r,e)=>r/e,max:(r,e)=>Math.max(r,e),min:(r,e)=>Math.min(r,e)}),ne=Object.assign(r=>{if(!Number.isInteger(r)||r<=0)throw new Error(`invalid timescale: ${r}`);return r},{SECOND:1,MILLI:1e3,MICRO:1e6,NANO:1e9}),xe=class r{value;scale;constructor(e,t){if(!Number.isFinite(e)||e<0)throw new Error(`invalid timestamp: ${e}`);this.value=e,this.scale=t}static now(){return new r(performance.now(),ne.MILLI)}static fromMillis(e){return new r(e,ne.MILLI)}static fromMicros(e){return new r(e,ne.MICRO)}as(e){return e===this.scale?this.value:this.value*e/this.scale}asMillis(){return this.as(ne.MILLI)}asMicros(){return this.as(ne.MICRO)}},Hm=Object.assign(r=>r,{zero:0,fromNano:r=>r/1e9,fromMicro:r=>r/1e6,fromMilli:r=>r/1e3,toNano:r=>r*1e9,toMicro:r=>r*1e6,toMilli:r=>r*1e3,now:()=>performance.now()/1e3,add:(r,e)=>r+e,sub:(r,e)=>r-e,mul:(r,e)=>r*e,div:(r,e)=>r/e,max:(r,e)=>Math.max(r,e),min:(r,e)=>Math.min(r,e)});var Xm=32*1024*1024,Ym=1024,dr=class extends Error{constructor(){super("lagged: frames were evicted before being read"),this.name="Lagged"}},as=class{sequence;frames=new A([]);closed=new et;total=new A(0);offset=0;cacheBytes=0;constructor(e){this.sequence=e}};function Wo(r,e){if(r.closed.peek()!==void 0)throw new Error("group is closed");r.cacheBytes+=e.payload.byteLength,r.frames.mutate(t=>{for(t.push(e);t.length>Ym||r.cacheBytes>Xm;){let n=t.shift();if(!n)break;r.cacheBytes-=n.payload.byteLength,r.offset++}}),r.total.update(t=>t+1)}var wt=class{sequence;#e;#t;#r=new A(!1);constructor(e){this.#e=new as(e),this.sequence=e}get closed(){return this.#e.closed}consume(){return os(this.#e)}mirror(){let e=new as(this.sequence);for(let i of this.#e.frames.peek())Wo(e,i);e.offset=this.#e.offset;let t=this.#e.closed.peek();if(t!==void 0)return e.closed.set(t),os(e);this.#t??=new Set,this.#t.add(e),this.#r.set(!0);let n=e.closed.subscribe(i=>{i!==void 0&&(this.#t?.delete(e),this.#r.set((this.#t?.size??0)>0),n())});return os(e)}get used(){return this.#r}async unused(){for(;this.#r.peek()&&this.#e.closed.peek()===void 0;)await A.race(this.#r,this.#e.closed)}writeFrame(e){if(Wo(this.#e,e),this.#t)for(let t of this.#t)t.closed.peek()!==void 0?this.#t.delete(t):Wo(t,e)}writeString(e){this.writeFrame({payload:new TextEncoder().encode(e),timestamp:xe.now()})}writeJson(e){this.writeString(JSON.stringify(e))}writeBool(e){this.writeFrame({payload:new Uint8Array([e?1:0]),timestamp:xe.now()})}get isClosed(){return this.#e.closed.peek()!==void 0}close(e){if(this.#e.closed.peek()===void 0&&(this.#e.closed.set(e??null),this.#t)){for(let t of this.#t)t.closed.peek()===void 0&&t.closed.set(e??null);this.#t.clear()}}},os,Ru=class r{sequence;#e;constructor(e){this.#e=e,this.sequence=e.sequence}get closed(){return this.#e.closed}static{os=e=>new r(e)}#t(){let e=this.#e.frames.peek(),t=e.shift();if(t)return this.#e.cacheBytes-=t.payload.byteLength,{sequence:this.#e.total.peek()-e.length-1,frame:t}}get done(){return this.#e.frames.peek().length===0&&this.#e.closed.peek()!==void 0}get isClosed(){return this.#e.closed.peek()!==void 0}get skipped(){return this.#e.offset>0}tryReadFrame(){return this.#t()?.frame}tryReadFrameSequence(){let e=this.#t();if(e)return{sequence:e.sequence,payload:e.frame.payload,timestamp:e.frame.timestamp}}async readable(){for(;;){if(this.#e.frames.peek().length>0||this.#e.closed.peek()!==void 0)return;await A.race(this.#e.frames,this.#e.closed)}}async readFrame(){for(;;){if(this.#e.offset>0)throw new dr;let e=this.#t();if(e)return e.frame;let t=this.#e.closed.peek();if(t instanceof Error)throw t;if(t!==void 0)return;await A.race(this.#e.frames,this.#e.closed)}}async readFrameSequence(){for(;;){if(this.#e.offset>0)throw new dr;let e=this.#t();if(e)return{sequence:e.sequence,payload:e.frame.payload,timestamp:e.frame.timestamp};let t=this.#e.closed.peek();if(t instanceof Error)throw t;if(t!==void 0)return;await A.race(this.#e.frames,this.#e.closed)}}async readString(){let e=await this.readFrame();return e?new TextDecoder().decode(e.payload):void 0}async readJson(){let e=await this.readString();return e?JSON.parse(e):void 0}async readBool(){let e=await this.readFrame();return e?e.payload[0]===1:void 0}close(e){this.#e.closed.peek()===void 0&&this.#e.closed.set(e??null)}};var Vu=5e3,Lu=50,Du=65535;function Km(r={}){return{timescale:r.timescale??ne.MILLI,latencyMax:r.latencyMax??Vu,priority:r.priority??0,ordered:r.ordered??!1}}function Ho(r={}){return{priority:r.priority??0,ordered:r.ordered??!1,latencyMax:r.latencyMax??0,startGroup:r.startGroup,endGroup:r.endGroup}}function Qm(r){let e;for(let t of r){let n=t.update.peek();if(n){if(!e){e={...n};continue}e.priority=Math.max(e.priority??0,n.priority??0),e.ordered=(e.ordered??!1)&&(n.ordered??!1),e.latencyMax=Math.max(e.latencyMax??0,n.latencyMax??0),n.startGroup!==void 0&&(e.startGroup=e.startGroup===void 0?n.startGroup:Math.min(e.startGroup,n.startGroup)),e.endGroup===void 0||n.endGroup===void 0?e.endGroup=void 0:e.endGroup=Math.max(e.endGroup,n.endGroup)}}return e}var Cu=class r{name;#e;#t;constructor(e){this.name=e.name,this.#e=e.producer,this.#t=e.sequences}static{$n.makeRequest=e=>new r(e)}get subscription(){return this.#e.subscription.peek()??Ho()}get priority(){return this.subscription.priority??0}accept(e={}){return Jm(this.name,this.#e,this.#t),this.#e.accept(e)}reject(e){this.#e.close(e)}},us=class{name;#e;constructor(e,t){this.name=e,this.#e=t}subscribe(e){return this.#e.subscribe(this.name,e)}info(){return this.#e.resolveTrackInfo(this.name)}fetchGroup(e,t){return this.#e.fetchGroup(this.name,e,t)}},ds=class{groups=new A([]);datagrams=new A([]);latest;closed=new et;update;info=new A(void 0);constructor(e){this.update=new A(e===void 0?void 0:Ho(e))}};function cs(r,e){return r.closed.peek()!==void 0?!1:(r.closed.set(e??null),!0)}async function Uu(r){for(;;){let e=r.info.peek();if(e)return e;let t=r.closed.peek();if(t instanceof Error)throw t;if(t!==void 0)throw new Error("track closed before info was known");await A.race(r.info,r.closed)}}function Jm(r,e,t){let n=t.get(r);n||(n={next:0},t.set(r,n)),Bu(e,n)}var Bu,$u,qn=class{name;#e=new ds;#t={next:0};#r=[];#n=new Set;#i=new A(!1);constructor(e){this.name=e}static{Bu=(e,t)=>{e.#t=t}}info(){return Uu(this.#e)}get closed(){return this.#e.closed}get subscription(){return this.#e.update}accept(e={}){let t=Km(e);this.#e.info.set(t);for(let n of this.#n)n.info.set(t);return this}subscribe(e={}){let t=new ds(e);return this.#s(t),$u(this.name,t)}get used(){return this.#i}async unused(){for(;this.#i.peek()&&this.#e.closed.peek()===void 0;)await A.race(this.#i,this.#e.closed)}#s(e){let t=this.#e.info.peek();t&&e.info.set(t);let n=this.#e.closed.peek();if(n===void 0){this.#n.add(e),this.#i.set(!0);let i=e.update.subscribe(()=>this.#o());this.#o();let s=e.closed.subscribe(a=>{if(a===void 0)return;let o=a instanceof Error?a:void 0;i(),this.#n.delete(e),this.#o();for(let c of this.#r){let u=c.mirrors.get(e);u&&(u.close(o),c.mirrors.delete(e))}for(let c of e.groups.peek())c.close(o);s(),this.#i.set(this.#n.size>0)})}this.#d();for(let i of this.#r)this.#a(i,e);n!==void 0&&cs(e,n instanceof Error?n:void 0)}#o(){this.#e.update.set(Qm(this.#n))}#a(e,t){let n=e.group.mirror();e.mirrors.set(t,n),t.latest=Math.max(t.latest??0,n.sequence),t.groups.mutate(i=>{i.push(n),i.sort((s,a)=>s.sequence-a.sequence)})}#c(e){for(let[t,n]of e.mirrors)t.groups.mutate(i=>{let s=i.indexOf(n);s>=0&&i.splice(s,1)}),n.close();e.mirrors.clear()}#d(){let e=this.#e.info.peek()?.latencyMax??Vu,t=Date.now()-e,n=[];for(let i of this.#r){if(i.time>t||i.group.closed.peek()===void 0){n.push(i);continue}this.#c(i)}this.#r=n}#l(e){let t={group:e,time:Date.now(),mirrors:new Map};this.#r.push(t),this.#d();for(let n of this.#n)this.#a(t,n)}appendGroup(){if(this.#e.closed.peek()!==void 0)throw new Error("track is closed");let e=this.#t,t=new wt(e.next);return e.next=t.sequence+1,this.#l(t),t}writeGroup(e){if(this.#e.closed.peek()!==void 0)throw new Error("track is closed");let t=this.#r.findIndex(i=>i.group.sequence===e.sequence);if(t>=0){let i=this.#r[t];if(!(i.group.closed.peek()instanceof Error))throw new Error(`duplicate group: sequence=${e.sequence}`);this.#c(i),this.#r.splice(t,1)}let n=this.#t;e.sequence>=n.next&&(n.next=e.sequence+1),this.#l(e)}#u(e){let t=performance.now();for(let n of this.#n)n.datagrams.mutate(i=>{for(i.push({datagram:e,time:t});i.length>0&&t-i[0].time>Lu;)i.shift()})}appendDatagram(e,t){if(this.#e.closed.peek()!==void 0)throw new Error("track is closed");if(t.byteLength>Du)throw new Error("datagram payload too large");let n=this.#t,i=n.next;return n.next=i+1,this.#u({sequence:i,timestamp:e,payload:t}),i}writeDatagram(e){if(this.#e.closed.peek()!==void 0)throw new Error("track is closed");if(e.payload.byteLength>Du)throw new Error("datagram payload too large");let t=this.#t;e.sequence>=t.next&&(t.next=e.sequence+1),this.#u(e)}close(e){cs(this.#e,e);for(let{group:t}of this.#r)t.close(e);for(let t of this.#n){for(let n of t.groups.peek())n.close(e);cs(t,e)}this.#n.clear()}writeFrame(e){let t=this.appendGroup();t.writeFrame(e),t.close()}writeString(e){let t=this.appendGroup();t.writeString(e),t.close()}writeJson(e){let t=this.appendGroup();t.writeJson(e),t.close()}writeBool(e){let t=this.appendGroup();t.writeBool(e),t.close()}},Ou=class r{name;#e;#t=0;#r=new A({start:0});constructor(e,t){this.name=e,this.#e=t}static{$u=(e,t)=>new r(e,t)}info(){return Uu(this.#e)}get closed(){return this.#e.closed}get subscription(){return this.#e.update}latest(){return this.#e.latest}startAt(e){this.#r.update(t=>({...t,start:e}))}endAt(e){this.#r.update(t=>({...t,end:e}))}close(e){cs(this.#e,e),this.#e.groups.mutate(t=>{for(let n of t)n.close(e);t.length=0})}async recvGroup(){for(;;){let e=this.#e.groups.peek(),{start:t,end:n}=this.#r.peek();for(;e.length>0&&e[0].sequence<t;)e.shift()?.close();let i=e[0];if(i&&(n===void 0||i.sequence<=n))return e.shift(),i;let s=this.#e.closed.peek();if(s instanceof Error)throw s;if(s!==void 0&&!i)return;await A.race(this.#e.groups,this.#r,this.#e.closed)}}async recvDatagram(){for(;;){let e=this.#e.datagrams.peek(),t=performance.now()-Lu;for(;e.length>0&&e[0].time<t;)e.shift();if(e.length>0){let i=e.shift()?.datagram;return i&&(this.#t=Math.max(this.#t,i.sequence+1)),i}let n=this.#e.closed.peek();if(n instanceof Error)throw n;if(n!==void 0)return;await A.race(this.#e.datagrams,this.#e.closed)}}async nextGroup(){for(;;){let e=this.#e.groups.peek(),t=this.#r.peek(),n=Math.max(t.start,this.#t);for(;e.length>0&&e[0].sequence<n;)e.shift()?.close();let i=e[0];if(i&&(t.end===void 0||i.sequence<=t.end))return e.shift(),this.#t=i.sequence+1,i;let s=this.#e.closed.peek();if(s instanceof Error)throw s;if(s!==void 0&&!i)return;await A.race(this.#e.groups,this.#r,this.#e.closed)}}async readFrame(){let e=await this.readFrameSequence();return e?{payload:e.payload,timestamp:e.timestamp}:void 0}async readFrameSequence(){for(;;){let e=this.#e.groups.peek(),{start:t}=this.#r.peek();for(;e.length>0&&e[0].sequence<t;)e.shift()?.close();for(;e.length>1;){if(e[0].skipped)throw e.shift()?.close(),new dr;let a=e[0].tryReadFrameSequence();if(a)return{group:e[0].sequence,frame:a.sequence,payload:a.payload,timestamp:a.timestamp};e.shift()?.close()}if(e.length===0){let a=this.#e.closed.peek();if(a instanceof Error)throw a;if(a!==void 0)return;await A.race(this.#e.groups,this.#r,this.#e.closed);continue}let n=e[0];if(n.skipped)throw e.shift()?.close(),new dr;let i=n.tryReadFrameSequence();if(i)return{group:n.sequence,frame:i.sequence,payload:i.payload,timestamp:i.timestamp};let s=this.#e.closed.peek();if(s instanceof Error)throw s;if(s!==void 0)return;if(n.done){e.shift()?.close();continue}await Promise.race([A.race(this.#e.groups,this.#r,this.#e.closed),n.readable()])}}async readString(){let e=await this.readFrame();if(e)return new TextDecoder().decode(e.payload)}async readJson(){let e=await this.readString();if(e)return JSON.parse(e)}async readBool(){let e=await this.readFrame();if(!e)return;let t=e.payload;if(t.byteLength!==1||!(t[0]===0||t[0]===1))throw new Error("invalid bool frame");return t[0]===1}update(e){this.#e.update.set(Ho(e))}};var Xo=class{requested=new A([]);closed=new et;tracks=new Map;sequences=new Map;consumers=0};function t_(r){let e=r.requested.peek();return e.sort((t,n)=>t.priority-n.priority),e.pop()}function r_(r,e){r.closed.peek()===void 0&&(r.closed.set(e??null),r.requested.mutate(t=>{for(let n of t)n.reject(e);t.length=0}))}function Nu(r,e,t={},n=!1){if(r.closed.peek()!==void 0)throw new Error(`broadcast is closed: ${r.closed.peek()}`);let i=r.tracks.get(e);if(i){if(i.closed.peek()===void 0)return i.subscribe(t);r.tracks.delete(e)}let s=new qn(e),a=s.subscribe(t);return n&&(r.tracks.set(e,s),s.closed.then(()=>{r.tracks.get(e)===s&&r.tracks.delete(e)})),r.requested.mutate(o=>{o.push($n.makeRequest({name:e,producer:s,sequences:r.sequences}))}),a}async function n_(r,e){let t=r.tracks.get(e);if(t&&t.closed.peek()===void 0)return t.info();if(r.closed.peek()!==void 0)return Promise.reject(new Error(`broadcast is closed: ${r.closed.peek()}`));let n=new qn(e);r.requested.mutate(i=>{i.push($n.makeRequest({name:e,producer:n,sequences:r.sequences}))});try{return await n.info()}finally{n.close()}}async function i_(r,e,t,n={}){let i=Nu(r,e,{priority:n.priority});try{for(;;){let s=await i.recvGroup();if(!s)throw new Error(`group not found: ${t}`);if(s.sequence===t)return s.closed.then(()=>i.close()),s;if(s.close(),s.sequence>t)throw new Error(`group not found: ${t}`)}}catch(s){throw i.close(),s}}var s_,Vr=class r{#e;#t=!1;constructor(e){this.#e=e??new Xo,this.#e.consumers++}static{s_=e=>new r(e)}get closed(){return this.#e.closed}clone(){return new r(this.shareState())}shareState(){return this.#e}track(e){return new us(e,this)}subscribe(e,t){return Nu(this.#e,e,t,!0)}async requested(){for(;;){let e=t_(this.#e);if(e)return e;let t=this.#e.closed.peek();if(t instanceof Error)throw t;if(t!==void 0)return;await A.race(this.#e.requested,this.#e.closed)}}resolveTrackInfo(e){return n_(this.#e,e)}fetchGroup(e,t,n){return i_(this.#e,e,t,n)}close(e){this.#t||(this.#t=!0,!(--this.#e.consumers>0)&&r_(this.#e,e))}};var ao={};ke(ao,{Reload:()=>cc,accept:()=>tg,certificateHash:()=>uf,connect:()=>ac,isWebTransportSupported:()=>oo});var Nx=new Error("timeout while waiting for mutex to become available"),qx=new Error("mutex already locked"),o_=new Error("request for lock canceled"),a_=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},Yo=class{constructor(e,t=o_){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{let s={resolve:n,reject:i,weight:e,priority:t},a=Zu(this._queue,o=>t<=o.priority);a===-1&&e<=this._value?this._dispatchItem(s):this._queue.splice(a+1,0,s)})}runExclusive(e){return a_(this,arguments,void 0,function*(t,n=1,i=0){let[s,a]=yield this.acquire(n,i);try{return yield t(s)}finally{a()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),c_(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let i=n.findIndex(s=>s.priority<=e);(i===-1?n:n.splice(0,i)).forEach((s=>s.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function c_(r,e){let t=Zu(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Zu(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var u_=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(d){try{u(n.next(d))}catch(f){a(f)}}function c(d){try{u(n.throw(d))}catch(f){a(f)}}function u(d){d.done?s(d.value):i(d.value).then(o,c)}u((n=n.apply(r,e||[])).next())})},ls=class{constructor(e){this._semaphore=new Yo(1,e)}acquire(){return u_(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var Ko=class extends Error{code;constructor(e,t){super(`remote error: ${e}`,t),this.name="RemoteError",this.code=e}},Ne=class extends Error{constructor(e,t){super(e,t),this.name="ProtocolViolation"}};function d_(r){if(typeof r!="object"||r===null)return;let{source:e,streamErrorCode:t}=r;if(!(e!=="stream"||typeof t!="number"))return t}function Zn(r){let e=d_(r);return e===void 0?L(r):new Ko(e,{cause:r})}function L(r){return r instanceof Error?r:new Error(String(r))}function ee(r){let e=L(r);if(typeof WebTransportError<"u"&&e instanceof WebTransportError){let t=[`source=${e.source}`];e.streamErrorCode!==null&&t.push(`code=${e.streamErrorCode}`);let n=t.join(" ");return e.message?`${e.message} (${n})`:`WebTransportError: ${n}`}return e.message||e.name||"unknown error"}var m={DRAFT_07:4278190087,DRAFT_14:4278190094,DRAFT_15:4278190095,DRAFT_16:4278190096,DRAFT_17:4278190097,DRAFT_18:4278190098,DRAFT_19:4278190099},te={DRAFT_14:"moq-00",DRAFT_15:"moqt-15",DRAFT_16:"moqt-16",DRAFT_17:"moqt-17",DRAFT_18:"moqt-18",DRAFT_19:"moqt-19"},l_={[m.DRAFT_07]:"moq-transport-07",[m.DRAFT_14]:"moq-transport-14",[m.DRAFT_15]:"moq-transport-15",[m.DRAFT_16]:"moq-transport-16",[m.DRAFT_17]:"moq-transport-17",[m.DRAFT_18]:"moq-transport-18",[m.DRAFT_19]:"moq-transport-19"};function Gu(r){return l_[r]??`unknown(0x${r.toString(16)})`}var Gn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};function Rt(r,e,t){let n,i=new Promise((s,a)=>{n=setTimeout(()=>a(new Gn(t)),e)});return Promise.race([r,i]).finally(()=>clearTimeout(n))}var ie={};ke(ie,{MAX_U14:()=>h_,MAX_U30:()=>p_,MAX_U53:()=>jn,MAX_U6:()=>f_,decode:()=>rt,decodeBigInt:()=>Hn,decodeLeadingOnes:()=>Lr,encode:()=>Ur,encodeLeadingOnes:()=>fs,encodeLeadingOnesTo:()=>Wn,encodeTo:()=>Xe,size:()=>__,sizeLeadingOnes:()=>m_});var f_=63,h_=16383,p_=1073741823,jn=Number.MAX_SAFE_INTEGER,ju=(1n<<64n)-1n;function m_(r){let e=BigInt(r);if(e<0n)throw new RangeError(`value is negative: ${r}`);if(e>ju)throw new RangeError(`value exceeds 64 bits: ${r}`);return e<1n<<7n?1:e<1n<<14n?2:e<1n<<21n?3:e<1n<<28n?4:e<1n<<35n?5:e<1n<<42n?6:e<1n<<56n?8:9}function Wn(r,e){let t=BigInt(e);if(t<0n)throw new RangeError(`underflow, value is negative: ${e}`);if(t>ju)throw new RangeError(`value exceeds 64 bits: ${e}`);let n=new DataView(r);return t<1n<<7n?(n.setUint8(0,Number(t)),new Uint8Array(r,0,1)):t<1n<<14n?(n.setUint8(0,128|Number(t>>8n)),n.setUint8(1,Number(t&0xffn)),new Uint8Array(r,0,2)):t<1n<<21n?(n.setUint8(0,192|Number(t>>16n)),n.setUint16(1,Number(t&0xffffn)),new Uint8Array(r,0,3)):t<1n<<28n?(n.setUint8(0,224|Number(t>>24n)),n.setUint8(1,Number(t>>16n&0xffn)),n.setUint16(2,Number(t&0xffffn)),new Uint8Array(r,0,4)):t<1n<<35n?(n.setUint8(0,240|Number(t>>32n)),n.setUint32(1,Number(t&0xffffffffn)),new Uint8Array(r,0,5)):t<1n<<42n?(n.setUint8(0,248|Number(t>>40n)),n.setUint8(1,Number(t>>32n&0xffn)),n.setUint32(2,Number(t&0xffffffffn)),new Uint8Array(r,0,6)):t<1n<<56n?(n.setUint8(0,254),n.setUint8(1,Number(t>>48n&0xffn)),n.setUint16(2,Number(t>>32n&0xffffn)),n.setUint32(4,Number(t&0xffffffffn)),new Uint8Array(r,0,8)):(n.setUint8(0,255),n.setBigUint64(1,t),new Uint8Array(r,0,9))}function fs(r){return Wn(new ArrayBuffer(9),r)}function Lr(r){if(r.length===0)throw new Error("buffer is empty");let e=r[0],t=0;for(let o=7;o>=0&&e&1<<o;o--)t++;let n;if(t<=5?n=t+1:t===6?n=7:t===7?n=8:n=9,r.length<n)throw new Error(`buffer too short: need ${n} bytes, have ${r.length}`);let i=new DataView(r.buffer,r.byteOffset,n),s=r.subarray(n),a;switch(t){case 0:a=BigInt(e);break;case 1:a=BigInt(e&63)<<8n|BigInt(r[1]);break;case 2:a=BigInt(e&31)<<16n|BigInt(i.getUint16(1));break;case 3:a=BigInt(e&15)<<24n|BigInt(r[1])<<16n|BigInt(r[2])<<8n|BigInt(r[3]);break;case 4:a=BigInt(e&7)<<32n|BigInt(i.getUint32(1));break;case 5:a=BigInt(e&3)<<40n|BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);break;case 6:{a=BigInt(e&1)<<48n|BigInt(r[1])<<40n|BigInt(r[2])<<32n|BigInt(r[3])<<24n|BigInt(r[4])<<16n|BigInt(r[5])<<8n|BigInt(r[6]);break}case 7:{let o=new Uint8Array(8);o[0]=0,o.set(r.subarray(1,8),1),a=new DataView(o.buffer).getBigUint64(0);break}case 8:{a=new DataView(r.buffer,r.byteOffset+1,8).getBigUint64(0);break}default:throw new Error("impossible")}return[a,s]}function __(r){if(r<=63)return 1;if(r<=16383)return 2;if(r<=1073741823)return 4;if(r<=jn)return 8;throw new Error(`overflow, value larger than 53-bits: ${r}`)}function w_(r,e){let t=new Uint8Array(r,0,1);return t[0]=e,t}function g_(r,e){let t=new DataView(r,0,2);return t.setUint16(0,e),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function y_(r,e){let t=new DataView(r,0,4);return t.setUint32(0,e),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function b_(r,e){let t=new DataView(r,0,8);return t.setBigUint64(0,e),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}var v_=2n**62n-1n;function Xe(r,e){let t=BigInt(e);if(t<0n)throw new Error(`underflow, value is negative: ${e}`);if(t>v_)throw new Error(`overflow, value larger than 62-bits: ${e}`);let n=Number(t);return n<=63?w_(r,n):n<=16383?g_(r,n|16384):n<=1073741823?y_(r,n|2147483648):b_(r,t|0xc000000000000000n)}function Ur(r){return Xe(new ArrayBuffer(8),r)}function Hn(r){if(r.length===0)throw new Error("buffer is empty");let e=1<<((r[0]&192)>>6);if(r.length<e)throw new Error(`buffer too short: need ${e} bytes, have ${r.length}`);let t=new DataView(r.buffer,r.byteOffset,e),n=r.subarray(e),i;if(e===1)i=BigInt(r[0]&63);else if(e===2)i=BigInt(t.getUint16(0)&16383);else if(e===4)i=BigInt(t.getUint32(0)&1073741823);else if(e===8)i=t.getBigUint64(0)&0x3fffffffffffffffn;else throw new Error("impossible");return[i,n]}function rt(r){let[e,t]=Hn(r);return[Number(e),t]}var A_=2**31-1,Wu=1024*1024*64;function Xu(r){return{sendOrder:r?.sendOrder,waitUntilAvailable:r?.waitUntilAvailable??!0}}var Yu=1e4;async function Ku(r,e,t){try{return await Rt(r,e,`stream open timed out after ${e}ms waiting for a slot`)}catch(n){throw r.then(t).catch(()=>{}),n}}function Qo(r){return r!==void 0&&r!==m.DRAFT_14&&r!==m.DRAFT_15&&r!==m.DRAFT_16}var H=class r{reader;writer;constructor(e){let t=e.writer??(e.writable&&new me(e.writable,e.version)),n=e.reader??(e.readable&&new ae(e.readable,void 0,e.version));if(!t||!n)throw new Error("stream needs both halves");this.writer=t,this.reader=n}static async accept(e,t){for(;;){let n=e.incomingBidirectionalStreams.getReader(),i=await n.read();if(n.releaseLock(),i.done)return;let{readable:s,writable:a}=i.value;return new r({readable:s,writable:a,version:t})}}static async open(e,t){let{readable:n,writable:i}=await Ku(e.createBidirectionalStream(Xu(t)),t?.timeout??Yu,s=>{s.writable.abort().catch(()=>{}),s.readable.cancel().catch(()=>{})});return new r({readable:n,writable:i,version:t?.version})}close(){this.writer.close(),this.reader.stop(new Error("cancel"))}abort(e){this.writer.reset(e),this.reader.stop(e)}},ae=class{#e;#t;#r;#n;version;constructor(e,t,n){this.#e=t??new Uint8Array,this.#t=e,this.#r=this.#t?.getReader(),this.version=n}async#i(){if(!this.#r)return!1;let e=await this.#r.read().catch(n=>{throw Zn(n)});if(e.done)return!1;if(e.value.byteLength===0)throw new Error("unexpected empty chunk");let t=new Uint8Array(e.value);if(this.#e.byteLength===0)this.#e=t;else{let n=new Uint8Array(this.#e.byteLength+t.byteLength);n.set(this.#e),n.set(t,this.#e.byteLength),this.#e=n}return!0}async#s(e){if(e>Wu)throw new Error(`read size ${e} exceeds max size ${Wu}`);for(;this.#e.byteLength<e;)if(!await this.#i())throw new Error("unexpected end of stream")}#o(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset,e);return this.#e=new Uint8Array(this.#e.buffer,this.#e.byteOffset+e,this.#e.byteLength-e),t}async read(e){return e===0?new Uint8Array:(await this.#s(e),this.#o(e))}async readAll(){for(;await this.#i(););return this.#o(this.#e.byteLength)}async string(){let e=await this.u53(),t=await this.read(e);return new TextDecoder().decode(t)}async bool(){let e=await this.u8();if(e===0)return!1;if(e===1)return!0;throw new Error("invalid bool value")}async u8(){return await this.#s(1),this.#o(1)[0]}async u16(){await this.#s(2);let t=new DataView(this.#e.buffer,this.#e.byteOffset,2).getUint16(0);return this.#o(2),t}async u53(){let e=await this.u62();return e>jn&&console.warn(`value larger than 53-bits; use u62 instead (precision lost): ${e.toString()}`),Number(e)}async u62(){return Qo(this.version)?this.#c():this.#a()}async#a(){await this.#s(1);let e=(this.#e[0]&192)>>6;if(e===0){let i=this.#o(1)[0];return BigInt(i)&0x3fn}if(e===1){await this.#s(2);let i=this.#o(2),s=new DataView(i.buffer,i.byteOffset,i.byteLength);return BigInt(s.getUint16(0))&0x3fffn}if(e===2){await this.#s(4);let i=this.#o(4),s=new DataView(i.buffer,i.byteOffset,i.byteLength);return BigInt(s.getUint32(0))&0x3fffffffn}await this.#s(8);let t=this.#o(8);return new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(0)&0x3fffffffffffffffn}async#c(){await this.#s(1);let e=this.#e[0],t=0;for(let a=7;a>=0&&e&1<<a;a--)t++;if(t===6&&this.version===m.DRAFT_17)throw new Error("invalid leading-ones varint: 1111110x prefix is reserved on draft-17");let n;t<=5?n=t+1:t===6?n=7:t===7?n=8:n=9,await this.#s(n);let i=this.#o(n),[s]=Lr(i);return s}async done(){return this.#e.byteLength>0?!1:!await this.#i()}stop(e){this.#r?.cancel(e).catch(()=>{})}get closed(){return this.#n??=(this.#r?.closed??Promise.resolve()).catch(e=>{throw Zn(e)}),this.#n}},me=class r{#e;#t;#r;#n;version;constructor(e,t){this.#t=e,this.#n=new ArrayBuffer(9),this.#e=this.#t.getWriter(),this.version=t}setPriority(e){this.#t.sendOrder=e}async bool(e){await this.write(Hu(this.#n,e?1:0))}async u8(e){await this.write(Hu(this.#n,e))}async u16(e){await this.write(x_(this.#n,e))}async i32(e){if(Math.abs(e)>A_)throw new Error(`overflow, value larger than 32-bits: ${e.toString()}`);await this.write(S_(this.#n,e))}async u53(e){e>jn&&console.warn(`value larger than 53-bits; use u62 instead (precision lost): ${e.toString()}`),Qo(this.version)?await this.write(Wn(this.#n,e)):await this.write(Xe(this.#n,e))}async u62(e){Qo(this.version)?await this.write(Wn(this.#n,e)):await this.write(Xe(this.#n,e))}async write(e){await this.#e.write(e).catch(t=>{throw Zn(t)})}async string(e){let t=new TextEncoder().encode(e);await this.u53(t.byteLength),await this.write(t)}close(){this.#e.close().catch(()=>{})}get closed(){return this.#r??=this.#e.closed.catch(e=>{throw Zn(e)}),this.#r}reset(e){this.#e.abort(e).catch(()=>{})}static async open(e,t){let n=await Ku(e.createUnidirectionalStream(Xu(t)),t?.timeout??Yu,i=>{i.abort().catch(()=>{})});return new r(n,t?.version)}static async tryOpen(e,t){let n=t.cancel.then(()=>{},()=>{}),i=r.open(e,t);try{let a=await Promise.race([n,i]);if(a)return a}catch(a){if(!(a instanceof Gn))throw a;return}let s=new Error("abandoned waiting for a stream slot");i.then(a=>a.reset(s)).catch(()=>{})}};function Hu(r,e){let t=new Uint8Array(r,0,1);return t[0]=e,t}function x_(r,e){let t=new DataView(r,0,2);return t.setUint16(0,e),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function S_(r,e){let t=new DataView(r,0,4);return t.setInt32(0,e),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}var Br=class{#e;#t;constructor(e,t){this.#e=e.incomingUnidirectionalStreams.getReader(),this.#t=t}async next(){let e=await this.#e.read();if(!e.done)return new ae(e.value,void 0,this.#t)}close(){this.#e.cancel()}};async function be(r,e){let t=ss(e);if(t.length>32)throw new Error(`namespace exceeds ${32} parts`);await r.u53(t.length);for(let n of t)await r.string(n)}async function se(r){let e=await r.u53();if(e>32)throw new Error(`namespace exceeds ${32} parts`);let t=[];for(let n=0;n<e;n++)t.push(await r.string());return is(...t)}var hs=class{#e;#t;version;constructor(e,t,n){this.#e=e,this.version=t,this.#t=n?0n:1n}async openBi(){return H.open(this.#e,{version:this.version})}async acceptBi(){return H.accept(this.#e,this.version)}async nextRequestId(){let e=this.#t;return this.#t+=2n,e}close(){this.#e.close()}},V={NewRequest:0,Response:1,ErrorResponse:2,CloseStream:3,FollowUp:4,MaxRequestId:5,Ignore:6,GoAway:7},ps=class{#e;#t;#r;#n=new ls;version;#i=new Map;#s=new Map;#o=new Map;#a=new Set;#c=[];#d=[];#l;#u;#f=[];#p=!1;constructor(e,t,n,i,s){this.#e=e,this.#t=t.reader,this.#t.version=n,this.#r=t.writer,this.#r.version=n,this.version=n,this.#u=i,this.#l=s?0n:1n}async acceptBi(){if(this.#p)return;let e=this.#c.shift();return e||new Promise(t=>{this.#d.push(t)})}openBi(){let e,t,n=new ReadableStream({start(c){e=c},cancel:()=>{t!==void 0&&this.#i.delete(t)}}),i=new Uint8Array(0),s=!1,a=new WritableStream({write:async c=>{let u=new Uint8Array(i.length+c.length);for(u.set(i),u.set(c,i.length),i=u;;){let d=this.#g(i);if(d===void 0)break;let f=i.subarray(0,d);if(i=i.subarray(d),!s){let l=this.#T(f);l&&(t=l.requestId,this.#i.set(l.requestId,{controller:e}),s=!0)}await this.#n.runExclusive(()=>this.#r.write(f))}}}),o=new H({readable:n,writable:a});return o.reader.version=this.version,o.writer.version=this.version,o}async openNativeBi(){return H.open(this.#e,{version:this.version})}async nextRequestId(){for(;;){if(this.#p)return;let e=this.#l;if(e<this.#u)return this.#l+=2n,e;await new Promise(t=>{this.#f.push(t)})}}async run(){try{for(this.version===m.DRAFT_16&&this.#m();!await this.#t.done();){let t=await this.#t.u53(),n=await this.#t.u16(),i=await this.#t.read(n),s=await this.#E(t,i);if(s.route===V.GoAway){console.warn("received GOAWAY on control stream");return}let{route:a,requestId:o}=s;switch(a){case V.NewRequest:this.#b(t,n,i,o);break;case V.Response:this.#x(o,t,n,i);break;case V.ErrorResponse:this.#x(o,t,n,i),this.#v(o);break;case V.CloseStream:this.#v(o);break;case V.FollowUp:this.#x(o,t,n,i);break;case V.MaxRequestId:this.#u=o;for(let c of this.#f)c();this.#f=[];break}}}finally{this.close()}}async#m(){try{for(;;){let e=await H.accept(this.#e,this.version);if(!e)break;let t=this.#d.shift();t?t(e):this.#c.push(e)}}catch{}}#b(e,t,n,i){let s,a=new ReadableStream({start(d){s=d},cancel:()=>{this.#i.delete(i)}}),o=this.#S(),c=new H({readable:a,writable:o});c.reader.version=this.version,c.writer.version=this.version,this.#i.set(i,{controller:s}),s.enqueue(this.#_(e,t,n));let u=this.#d.shift();u?u(c):this.#c.push(c)}#x(e,t,n,i){let s=this.#i.get(e);if(!s){console.warn(`adapter: no stream for requestId=${e} typeId=0x${t.toString(16)}`);return}try{s.controller.enqueue(this.#_(t,n,i))}catch{}}#v(e){let t=this.#i.get(e);if(!t)return;console.debug(`adapter: closing stream requestId=${e}`),this.#i.delete(e),this.#a.delete(e);let n=this.#o.get(e);n!==void 0&&(this.#s.delete(n),this.#o.delete(e));try{t.controller.close()}catch{}}#g(e){if(e.length===0)return;let t=1<<((e[0]&192)>>6);if(e.length<t)return;let[,n]=rt(e);if(n.length<2)return;let i=n[0]<<8|n[1],s=e.length-n.length+2+i;if(!(e.length<s))return s}#T(e){if(e.length===0)return;let t=1<<((e[0]&192)>>6);if(e.length<t)return;let[n,i]=rt(e);if(i.length<2)return;let s=i[0]<<8|i[1],a=i.subarray(2);if(a.length<s)return;let o=a.subarray(0,s),[c]=rt(o),u=BigInt(c);if(n===6)try{let[,d]=rt(o);this.#h(d,u)}catch{}return n===17&&this.#a.add(u),{requestId:u}}#h(e,t){let n=new TextDecoder,[i,s]=rt(e),a=s,o=[];for(let u=0;u<i;u++){let[d,f]=rt(a);o.push(n.decode(f.subarray(0,d))),a=f.subarray(d)}let c=o.join("/");this.#s.set(c,t),this.#o.set(t,c)}#S(){let e=new Uint8Array(0);return new WritableStream({write:async t=>{let n=new Uint8Array(e.length+t.length);for(n.set(e),n.set(t,e.length),e=n;;){let i=this.#g(e);if(i===void 0)break;let s=e.subarray(0,i);e=e.subarray(i),await this.#n.runExclusive(()=>this.#r.write(s))}}})}#_(e,t,n){let i=Xe(new ArrayBuffer(9),e),s=new Uint8Array(i.byteLength+2+n.byteLength);return s.set(i,0),new DataView(s.buffer,i.byteLength,2).setUint16(0,t),s.set(n,i.byteLength+2),s}async#E(e,t){let n=async()=>await new ae(void 0,t,this.version).u62(),i=async()=>{let s=new ae(void 0,t,this.version),a=await se(s),o=this.#s.get(a);if(o===void 0)throw new Error(`unknown namespace: ${a}`);return this.#s.delete(a),o};switch(e){case 2:{let s=await n();return{route:V.FollowUp,requestId:s}}case 3:case 22:case 29:case 13:{let s=await n();return{route:V.NewRequest,requestId:s}}case 6:{let s=new ae(void 0,t,this.version),a=await s.u62(),o=await se(s);return this.#s.set(o,a),this.#o.set(a,o),{route:V.NewRequest,requestId:a}}case 17:{if(this.version!==m.DRAFT_14&&this.version!==m.DRAFT_15)throw new Error("unexpected SubscribeNamespace on control stream");let s=await n();return{route:V.NewRequest,requestId:s}}case 4:{let s=await n();return{route:V.Response,requestId:s}}case 24:{let s=await n();return{route:V.Response,requestId:s}}case 30:{let s=await n();return{route:V.Response,requestId:s}}case 7:{let s=await n();return{route:V.Response,requestId:s}}case 18:{if(this.version!==m.DRAFT_14)throw new Error("unexpected SubscribeNamespaceOk");let s=await n();return{route:V.Response,requestId:s}}case 5:{let s=await n();return{route:V.ErrorResponse,requestId:s}}case 25:{if(this.version!==m.DRAFT_14)throw new Error("unexpected FetchError");let s=await n();return{route:V.ErrorResponse,requestId:s}}case 31:{if(this.version!==m.DRAFT_14)throw new Error("unexpected PublishError");let s=await n();return{route:V.ErrorResponse,requestId:s}}case 8:{if(this.version===m.DRAFT_14){let a=await n();return{route:V.ErrorResponse,requestId:a}}let s=this.#a.values().next().value;if(s===void 0)throw new Error("unexpected message 0x08: no SubscribeNamespace stream");return{route:V.FollowUp,requestId:s}}case 14:{let s=this.#a.values().next().value;if(s===void 0)throw new Error("unexpected message 0x0e: no SubscribeNamespace stream");return{route:V.FollowUp,requestId:s}}case 19:{if(this.version!==m.DRAFT_14)throw new Error("unexpected SubscribeNamespaceError");let s=await n();return{route:V.ErrorResponse,requestId:s}}case 10:{let s=await n();return{route:V.CloseStream,requestId:s}}case 11:{let s=await n();return{route:V.CloseStream,requestId:s}}case 23:{let s=await n();return{route:V.CloseStream,requestId:s}}case 9:{if(this.version===m.DRAFT_16){let a=await n();return{route:V.CloseStream,requestId:a}}let s=await i();return{route:V.CloseStream,requestId:s}}case 12:{if(this.version===m.DRAFT_16){let a=await n();return{route:V.CloseStream,requestId:a}}let s=await i();return{route:V.CloseStream,requestId:s}}case 20:{if(this.version!==m.DRAFT_14&&this.version!==m.DRAFT_15)throw new Error("unexpected UnsubscribeNamespace");let s=await n();return{route:V.CloseStream,requestId:s}}case 21:{let s=await n();return{route:V.MaxRequestId,requestId:s}}case 26:return await n(),{route:V.Ignore,requestId:0n};case 16:return{route:V.GoAway};default:throw new Error(`unknown control message type: 0x${e.toString(16)}`)}}close(){if(!this.#p){this.#p=!0,console.debug("adapter: close() called");for(let e of this.#i.values())try{e.controller.close()}catch{}this.#i.clear();for(let e of this.#d)e(void 0);this.#d=[],this.#s.clear(),this.#o.clear(),this.#a.clear();for(let e of this.#f)e();this.#f=[]}}};var ot={};ke(ot,{advertise:()=>Ca,decodeParams:()=>ii,fromParams:()=>cl,fromSetup:()=>aw,intoParams:()=>ni,intoSetup:()=>cw,loops:()=>Oa,negotiated:()=>Gr,supported:()=>Da});function Qu(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function Ju(r,e){return typeof e=="bigint"?e.toString():e}function ea(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function ta(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function ra(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var na="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Yn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ia(r){if(Yn(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Yn(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function sa(r){return ia(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}var ed=new Set(["string","number","symbol"]);function Kn(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ms(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function re(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function td(r){return Object.keys(r).filter(e=>r[e]._zod.optin!==void 0&&r[e]._zod.optout==="optional")}var rd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Nr(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function nd(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue===!1)return!0;return!1}function Dt(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function Xn(r){return typeof r=="string"?r:r?.message}function oa(r,e,t){var n;for(let i=e;i<r.length;i++)(n=r[i]).schema??(n.schema=t)}function gt(r,e,t){var n;let i=r.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(n=r).schema??(n.schema=r.inst):r.schema=r.inst);let s=r.schema!==r.inst?r.schema?._zod.def?.error:void 0,a=r.message?r.message:Xn(r.inst?._zod.def?.error?.(r))??Xn(s?.(r))??Xn(e?.error?.(r))??Xn(t.customError?.(r))??Xn(t.localeError?.(r))??"Invalid input",{inst:o,schema:c,continue:u,input:d,...f}=r;return f.path??(f.path=[]),f.message=a,e?.reportInput&&(f.input=d),f}function aa(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}function id(r,e){for(let t in e){let n=Object.getOwnPropertyDescriptor(e,t);n.get?Object.defineProperty(r,t,{...n,enumerable:!1}):E_(r,t,n.value)}}function lr(r,e,t,n=!0){return Object.defineProperty(r,e,{configurable:!0,writable:!0,enumerable:n,value:t}),t}function sd(r,e,t){return lr(r,e,t,!1)}function E_(r,e,t){Object.defineProperty(r,e,{configurable:!0,get(){return this==null?t:lr(this,e,t.bind(this))},set(n){lr(this,e,n)}})}function k_(r,e){let t=Object.getPrototypeOf(r);return e in t?void 0:t}var Jo,Ft=!1,T_={configurable:!0,get(){Ft=!0}};function Se(r,e,t){let n=Object.getPrototypeOf(r._zod);if(e in n&&Jo!==r._zod){Jo=void 0;return}Jo=r._zod,Object.defineProperty(n,e,{configurable:!0,get(){Object.defineProperty(this,e,T_);let i=Ft;Ft=!1;try{let s=t(this);return Ft?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:s}),Ft=Ft||i,s}catch(s){throw delete this[e],Ft=Ft||i,s}},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i})}})}function od(r,e,t,n){let i=k_(r,e);i&&Object.defineProperty(i,e,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,e,s),s.value=t(this),Object.defineProperty(this,e,s),s.value},set(s){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var ad;var ca={value:void 0,enumerable:!1},cd="captureStackTrace"in Error?Error:null;function M_(r){let e=cd;if(e){let t=e.stackTraceLimit;if(typeof t=="number"){try{e.stackTraceLimit=0}catch{return cd=null,new r}try{return new r}finally{e.stackTraceLimit=t}}}return new r}function z(r,e,t,n){let i={};function s(l){this.def=l,this.constr=f,this.traits=new Set}s.prototype=i;let a=t,o=a&&new WeakSet;function c(l,h){if(!l._zod){ca.value=new s(h);try{Object.defineProperty(l,"_zod",ca)}finally{ca.value=void 0}}if(l._zod.traits.has(r))return;if(l._zod.traits.add(r),e(l,h),o){let _=Object.getPrototypeOf(l),w=l._zod.constr.prototype,y=_;for(;y&&y!==w;)y=Object.getPrototypeOf(y);let b=y??_;o.has(b)||(o.add(b),id(b,a))}let p=f.prototype;for(let _ in p)Object.prototype.hasOwnProperty.call(p,_)&&(_ in l||(l[_]=p[_].bind(l)))}let u=n?.Parent??Object;class d extends u{}Object.defineProperty(d,"name",{value:r});function f(l){let h=n?.Parent?M_(d):this;c(h,l);let p=h._zod.deferred;if(p){for(let w of p)w();h._zod.deferred=void 0}let _=globalThis.__zod_globalConfig?.postProcessor;return _&&_(h),h}return Object.defineProperty(f,"init",{value:c}),Object.defineProperty(f,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(r)}),Object.defineProperty(f,"name",{value:r}),f}var nt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_s=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(ad=globalThis).__zod_globalConfig??(ad.__zod_globalConfig={});var hr=globalThis.__zod_globalConfig;function yt(r){return r&&Object.assign(hr,r),hr}function I_(){let r=this._zod;return r.message??(r.message=JSON.stringify(r.def,Ju,2)),r.message}function P_(r){this._zod.message=r}var z_={get:I_,set:P_,enumerable:!0,configurable:!0},da={value:void 0,enumerable:!1},la={value:void 0,enumerable:!1},ud=new WeakSet([Object.prototype,Error.prototype]),dd=(r,e)=>{r.name="$ZodError",da.value=r._zod,Object.defineProperty(r,"_zod",da),la.value=e,Object.defineProperty(r,"issues",la),da.value=void 0,la.value=void 0,Object.defineProperty(r,"message",z_);let t=Object.getPrototypeOf(r);ud.has(t)||(ud.add(t),Object.defineProperty(t,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},ld=z("$ZodError",dd),Qn=z("$ZodError",dd,void 0,{Parent:Error});var F_=r=>{let e=(t,n,i,s)=>{let a=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new nt;if(o.issues.length){let c=new(s?.Err??r)(o.issues.map(u=>gt(u,a,yt())));throw na(c,s?.callee??e),c}return o.value};return e},ws=F_(Qn),D_=r=>{let e=async(t,n,i,s)=>{let a=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let c=new(s?.Err??r)(o.issues.map(u=>gt(u,a,yt())));throw na(c,s?.callee??e),c}return o.value};return e},gs=D_(Qn),C_=r=>(e,t,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new nt;return s.issues.length?{success:!1,error:new(r??ld)(s.issues.map(a=>gt(a,i,yt())))}:{success:!0,data:s.value}},Jn=C_(Qn),O_=r=>async(e,t,n)=>{let i=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:t,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new r(s.issues.map(a=>gt(a,i,yt())))}:{success:!0,data:s.value}},ei=O_(Qn);var fd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;var hd=r=>{let e=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},pd=/^-?\d+n?$/,md=/^-?\d+$/,fa=/^-?\d+(?:\.\d+)?$/,_d=/^(?:true|false)$/i;var Ct=z("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])});var ys={number:"number",bigint:"bigint",object:"date"},wd=z("$ZodCheckLessThan",(r,e)=>{Ct.init(r,e);let t=ys[typeof e.value];r._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),r._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:ys[typeof n.value]??t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}}),gd=z("$ZodCheckGreaterThan",(r,e)=>{Ct.init(r,e);let t=ys[typeof e.value];r._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),r._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:ys[typeof n.value]??t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}});var yd=z("$ZodCheckNumberFormat",(r,e)=>{Ct.init(r,e),e.format=e.format||"float64";let t=e.format?.includes("int"),n=t?"int":"number",[i,s]=rd[e.format];r._zod.onattach.push(a=>{let o=a._zod.bag;o.format=e.format,o.minimum=i,o.maximum=s,t&&(o.pattern=md)}),r._zod.check=a=>{let o=a.value;if(t){if(!Number.isInteger(o)){a.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:o,inst:r});return}if(!Number.isSafeInteger(o)){o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:n,inclusive:!0,continue:!e.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:n,inclusive:!0,continue:!e.abort});return}}o<i&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:r,continue:!e.abort}),o>s&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inclusive:!0,inst:r,continue:!e.abort})}});var pa=z("$ZodCheckStringFormat",(r,e)=>{var t,n;Ct.init(r,e),r._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(t=r._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),bd=z("$ZodCheckRegex",(r,e)=>{pa.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}});var Ad={major:4,minor:5,patch:4};var ce=z("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=Ad;let n=r._zod.def.checks,i=r._zod.traits.has("$ZodCheck")?[r,...n??[]]:n?.length?[...n]:[];for(let s of i)for(let a of s._zod.onattach)a(r);if(i.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let s=(o,c,u)=>{if(o.memo)return o;let d=Nr(o),f;for(let l of c){if(l._zod.def.when){if(nd(o)||!l._zod.def.when(o))continue}else if(d)continue;let h=o.issues.length,p=l._zod.check(o);if(p instanceof Promise&&u?.async===!1)throw new nt;if(f||p instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await p,o.issues.length!==h&&(oa(o.issues,h,r),d||(d=Nr(o,h)))});else{if(o.issues.length===h)continue;oa(o.issues,h,r),d||(d=Nr(o,h))}}return f?f.then(()=>o):o},a=(o,c,u)=>{if(Nr(o))return o.aborted=!0,o;let d=s(c,i,u);if(d instanceof Promise){if(u.async===!1)throw new nt;return d.then(f=>r._zod.parse(f,u))}return r._zod.parse(d,u)};r._zod.run=(o,c)=>{if(c.skipChecks)return r._zod.parse(o,c);if(c.direction==="backward"){let d=r._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(f=>a(f,o,c)):a(d,o,c)}let u=r._zod.parse(o,c);if(u instanceof Promise){if(c.async===!1)throw new nt;return u.then(d=>s(d,i,c))}return s(u,i,c)}}},{get"~standard"(){return sd(this,"~standard",V_(this))},set"~standard"(r){lr(this,"~standard",r)}}),xd=r=>r.success?{value:r.data}:{issues:r.error?.issues};function V_(r){return{validate:e=>{try{return xd(Jn(r,e))}catch{return ei(r,e).then(xd)}},vendor:"zod",version:1}}var _a=z("$ZodString",(r,e)=>{ce.init(r,e),r._zod.pattern=[...r?._zod.bag?.patterns??[]].pop()??hd(r._zod.bag),r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}}),wa=z("$ZodStringFormat",(r,e)=>{pa.init(r,e),_a.init(r,e)});function L_(r){if(r==="")return!0;if(/\s/.test(r)||r.length%4!==0)return!1;try{return atob(r),!0}catch{return!1}}var Id=z("$ZodBase64",(r,e)=>{e.pattern??(e.pattern=fd),wa.init(r,e),r._zod.bag.contentEncoding="base64",r._zod.check=t=>{L_(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:r,continue:!e.abort})}});var ga=z("$ZodNumber",(r,e)=>{ce.init(r,e),r._zod.pattern=r._zod.bag.pattern??fa,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let i=t.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return t;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return t.issues.push({expected:"number",code:"invalid_type",input:i,inst:r,...s?{received:s}:{}}),t}}),Pd=z("$ZodNumberFormat",(r,e)=>{yd.init(r,e),ga.init(r,e)}),zd=z("$ZodBoolean",(r,e)=>{ce.init(r,e),r._zod.pattern=_d,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=!!t.value}catch{}let i=t.value;return typeof i=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:r}),t}}),Rd=z("$ZodBigInt",(r,e)=>{ce.init(r,e),r._zod.pattern=pd,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=BigInt(t.value)}catch{}return typeof t.value=="bigint"||t.issues.push({expected:"bigint",code:"invalid_type",input:t.value,inst:r}),t}});var Fd=z("$ZodUnknown",(r,e)=>{ce.init(r,e),r._zod.parse=t=>t});function Sd(r,e,t){r.issues.length&&e.issues.push(...Dt(t,r.issues)),e.value[t]=r.value}var Dd=z("$ZodArray",(r,e)=>{ce.init(r,e);let t=hr.memoizer;t?.attach(r),r._zod.parse=(n,i)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:r}),n;n.value=t?t.alloc(r,n,Array(s.length),i):Array(s.length);let a=[];for(let o=0;o<s.length;o++){let c=s[o],u=e.element._zod.run({value:c,issues:[]},i);u instanceof Promise?a.push(u.then(d=>Sd(d,n,o))):Sd(u,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function vs(r,e,t,n,i,s){let a=t in n,o=s==="optional";if(!(!a&&o&&i==="optional")){if(r.issues.length){if(i!==void 0&&o&&!a)return;e.issues.push(...Dt(t,r.issues))}if(!a&&i===void 0){r.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}r.value===void 0?a&&(e.value[t]=void 0):e.value[t]=r.value}}var U_=[];function B_(r){let e=Object.keys(r.shape),t=Object.getOwnPropertySymbols(r.shape),n=t.length?t:U_,i=n.length?[...e,...n]:e;for(let a of i)if(!r.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(a)}": expected a Zod schema`);let s=td(r.shape);return{...r,allKeys:i,symbolKeys:n,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(s)}}function $_(r,e,t,n,i,s){let a=[],o=i.keySet,c=i.catchall._zod,u=c.def.type,d=c.optin,f=c.optout;for(let l in e){if(o.has(l))continue;if(l==="__proto__"){u==="never"&&a.push(l);continue}if(u==="never"){a.push(l);continue}let h=c.run({value:e[l],issues:[]},n);h instanceof Promise?r.push(h.then(p=>vs(p,t,l,e,d,f))):vs(h,t,l,e,d,f)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:s,continue:!0}),r.length?Promise.all(r).then(()=>t):t}var ma=new WeakMap,Cd=z("$ZodObject",(r,e)=>{if(ce.init(r,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let c=e.shape;ma.set(e,c),Object.defineProperty(e,"shape",{get:()=>{let u={...c};return Object.defineProperty(e,"shape",{value:u}),ma.set(e,u),u}})}let n=ea(()=>B_(e));Se(r,"propValues",c=>{let u=c.def.shape,d={};for(let f in u){let l=u[f]._zod;if(l.values){Object.prototype.hasOwnProperty.call(d,f)||ra(d,f,new Set);for(let h of l.values)d[f].add(h);l.optin!==void 0&&d[f].add(void 0)}}return d});let i=Yn,s=e.catchall,a,o=hr.memoizer;o?.attach(r),r._zod.parse=(c,u)=>{a??(a=n.value);let d=c.value;if(!i(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:r}),c;c.value=o?o.alloc(r,c,{},u):{};let f=[],l=a.shape;for(let h of a.allKeys){if(h==="__proto__")continue;let p=l[h],_=p._zod.optin,w=p._zod.optout,y=p._zod.run({value:d[h],issues:[]},u);y instanceof Promise?f.push(y.then(b=>vs(b,c,h,d,_,w))):vs(y,c,h,d,_,w)}return s?$_(f,d,c,u,n.value,r):f.length?Promise.all(f).then(()=>c):c}});function Ed(r,e,t,n){for(let s of r)if(s.issues.length===0)return e.value=s.value,e;let i=r.filter(s=>!Nr(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:r.map(s=>s.issues.map(a=>gt(a,n,yt())))}),e)}var ya=z("$ZodUnion",(r,e)=>{ce.init(r,e),Se(r,"optin",n=>n.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":n.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),Se(r,"optout",n=>n.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Se(r,"values",n=>{if(n.def.options.every(i=>i._zod.values))return new Set(n.def.options.flatMap(i=>Array.from(i._zod.values)))}),Se(r,"pattern",n=>{if(n.def.options.every(i=>i._zod.pattern)){let i=n.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>ta(s.source)).join("|")})$`)}});let t=e.options.length===1?e.options[0]._zod.run:null;r._zod.parse=(n,i)=>{if(t)return t(n,i);let s=!1,a=[];for(let o of e.options){let c=o._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(o=>Ed(o,n,r,i)):Ed(a,n,r,i)}});var Od=z("$ZodDiscriminatedUnion",(r,e)=>{e.inclusive=!1,ya.init(r,e);let t=r._zod.parse;Se(r,"propValues",i=>{let s={};for(let a of i.def.options){let o=a._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);for(let[c,u]of Object.entries(o)){Object.prototype.hasOwnProperty.call(s,c)||ra(s,c,new Set);for(let d of u)s[c].add(d)}}return s}),e.options.forEach((i,s)=>{let a=ma.get(i._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,e.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});let n=ea(()=>{let i=e.options,s=new Map;for(let a of i){let o=a._zod.propValues?.[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let c of o){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,a)}}return s});r._zod.parse=(i,s)=>{let a=i.value;if(!Yn(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:r}),i;let o=n.value.get(a?.[e.discriminator]);return o?o._zod.run(i,s):e.unionFallback||s.direction==="backward"?t(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:a,path:[e.discriminator],inst:r}),i)}});var Vd=z("$ZodRecord",(r,e)=>{ce.init(r,e);let t=hr.memoizer;t?.attach(r),r._zod.parse=(n,i)=>{let s=n.value;if(!ia(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:r}),n;let a=[],o=e.keyType._zod.values;if(o&&!e.partial){n.value=t?t.alloc(r,n,{},i):{};let c=new Set;for(let d of o)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){if(c.add(typeof d=="number"?d.toString():d),d==="__proto__")continue;let f=e.keyType._zod.run({value:d,issues:[]},i);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(p=>gt(p,i,yt())),input:d,path:[d],inst:r});continue}let l=f.value;if(l==="__proto__")continue;let h=e.valueType._zod.run({value:s[d],issues:[]},i);h instanceof Promise?a.push(h.then(p=>{p.issues.length&&n.issues.push(...Dt(d,p.issues)),n.value[l]=p.value})):(h.issues.length&&n.issues.push(...Dt(d,h.issues)),n.value[l]=h.value)}let u;for(let d in s)if(!c.has(d))if(e.mode==="loose"){if(d==="__proto__")continue;n.value[d]=s[d]}else u=u??[],u.push(d);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:r,keys:u,continue:!0})}else{n.value=t?t.alloc(r,n,{},i):{};let c;for(let u of Reflect.ownKeys(s)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,u))continue;let d=e.keyType._zod.run({value:u,issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&fa.test(u)&&d.issues.length){let p=e.keyType._zod.run({value:Number(u),issues:[]},i);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(d=p)}if(d.issues.length){e.mode==="loose"?n.value[u]=s[u]:o?(c=c??[],c.push(u)):n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>gt(p,i,yt())),input:u,path:[u],inst:r});continue}let l=d.value;if(l==="__proto__")continue;let h=e.valueType._zod.run({value:s[u],issues:[]},i);h instanceof Promise?a.push(h.then(p=>{p.issues.length&&n.issues.push(...Dt(u,p.issues)),n.value[l]=p.value})):(h.issues.length&&n.issues.push(...Dt(u,h.issues)),n.value[l]=h.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:r,keys:c,continue:!0})}return a.length?Promise.all(a).then(()=>n):n}});var Ld=z("$ZodEnum",(r,e)=>{ce.init(r,e);let t=Qu(e.entries),n=new Set(t);r._zod.values=n;let i=t.filter(s=>ed.has(typeof s));r._zod.pattern=new RegExp(i.length?`^(${i.map(s=>Kn(s.toString())).join("|")})$`:"^[^\\s\\S]$"),r._zod.parse=(s,a)=>{let o=s.value;return n.has(o)||s.issues.push({code:"invalid_value",values:t,input:o,inst:r}),s}}),Ud=z("$ZodLiteral",(r,e)=>{ce.init(r,e);let t=new Set(e.values);r._zod.values=t,r._zod.pattern=new RegExp(e.values.length?`^(${e.values.map(n=>typeof n=="string"?Kn(n):n?Kn(n.toString()):String(n)).join("|")})$`:"^[^\\s\\S]$"),r._zod.parse=(n,i)=>{let s=n.value;return t.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:r}),n}});var Bd=z("$ZodTransform",(r,e)=>{ce.init(r,e),r._zod.optin="optional",hr.memoizer?.guard(r),r._zod.parse=(t,n)=>{if(n.direction==="backward")throw new _s(r.constructor.name);let i=e.transform(t.value,t);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(a=>(t.value=a,t));if(i instanceof Promise)throw new nt;return t.value=i,t}});function kd(r,e){return r.value=e.issues.length?void 0:e.value,r}var $d=z("$ZodOptional",(r,e)=>{ce.init(r,e),Se(r,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),r._zod.optout="optional",Se(r,"values",t=>{let n=t.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),Se(r,"pattern",t=>{let n=t.def.innerType._zod.pattern;return n?new RegExp(`^(${ta(n.source)})?$`):void 0}),r._zod.parse=(t,n)=>{if(t.value===void 0){if(e.innerType._zod.optin!=="defaulted")return t;let i=e.innerType._zod.run({value:t.value,issues:[]},n);return i instanceof Promise?i.then(s=>kd(t,s)):kd(t,i)}return e.innerType._zod.run(t,n)}});var Nd=z("$ZodDefault",(r,e)=>{ce.init(r,e),r._zod.optin="defaulted",Se(r,"values",t=>t.def.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);if(t.value===void 0)return t.value=e.defaultValue,t;let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(s=>Td(s,e)):Td(i,e)}});function Td(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}var qd=z("$ZodPipe",(r,e)=>{ce.init(r,e),Se(r,"values",t=>t.def.in._zod.values),Se(r,"optin",t=>t.def.in._zod.optin),Se(r,"optout",t=>t.def.out._zod.optout),Se(r,"propValues",t=>t.def.in._zod.propValues),r._zod.parse=(t,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(t,n);return s instanceof Promise?s.then(a=>bs(a,e.in,n)):bs(s,e.in,n)}let i=e.in._zod.run(t,n);return i instanceof Promise?i.then(s=>bs(s,e.out,n)):bs(i,e.out,n)}});function bs(r,e,t){return r.issues.some(n=>n.code!=="unrecognized_keys")?(r.aborted=!0,r):e._zod.run({value:r.value,issues:r.issues},t)}var Zd=z("$ZodCustom",(r,e)=>{Ct.init(r,e),ce.init(r,e),r._zod.parse=(t,n)=>t,r._zod.check=t=>{let n=t.value,i=e.fn(n);if(i instanceof Promise)return i.then(s=>Md(s,t,n,r));Md(i,t,n,r)}});function Md(r,e,t,n){if(!r){let i={code:"custom",input:t,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(aa(i))}}function Gd(r,e){return new r({type:"string",...re(e)})}function jd(r,e){return new r({type:"string",format:"base64",check:"string_format",abort:!1,...re(e)})}function Wd(r,e){return new r({type:"number",checks:[],...re(e)})}function Hd(r,e){return new r({type:"number",check:"number_format",abort:!1,format:"safeint",...re(e)})}function Xd(r,e){return new r({type:"boolean",...re(e)})}function Yd(r,e){return new r({type:"bigint",...re(e)})}function Kd(r){return new r({type:"unknown"})}function ti(r,e){return new wd({check:"less_than",...re(e),value:r,inclusive:!0})}function ba(r,e){return new gd({check:"greater_than",...re(e),value:r,inclusive:!0})}function As(r){return ba(0,r)}function va(r,e){return new bd({check:"string_format",format:"regex",...re(e),pattern:r})}function Qd(r,e,t){return new r({type:"custom",check:"custom",fn:e,...re(t)})}var _e=z("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");ce.init(r,e),r.def=e,r.type=e.type},{get with(){return this.check},set with(r){lr(this,"with",r)},parse(r,e){return ws(this,r,e,{callee:this.parse})},parseAsync(r,e){return gs(this,r,e,{callee:this.parseAsync})},safeParse(r,e){return Jn(this,r,e)},safeParseAsync(r,e){return ei(this,r,e)},check(...r){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...r.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]},{parent:!0})},clone(r,e){return ms(this,r,e)},brand(){return this},register(r,e){return r.add(this,e),this},apply(r,...e){return e.length===0?r(this):r(this,...e)}}),el=z("ZodMiniString",(r,e)=>{_a.init(r,e),_e.init(r,e)});function q(r){return Gd(el,r)}var q_=z("ZodMiniStringFormat",(r,e)=>{wa.init(r,e),el.init(r,e)});var Z_=z("ZodMiniBase64",(r,e)=>{Id.init(r,e),q_.init(r,e)});function tl(r){return jd(Z_,r)}var rl=z("ZodMiniNumber",(r,e)=>{ga.init(r,e),_e.init(r,e)});function we(r){return Wd(rl,r)}var G_=z("ZodMiniNumberFormat",(r,e)=>{Pd.init(r,e),rl.init(r,e)});function Aa(r){return Hd(G_,r)}var j_=z("ZodMiniBoolean",(r,e)=>{zd.init(r,e),_e.init(r,e)});function pr(r){return Xd(j_,r)}var W_=z("ZodMiniBigInt",(r,e)=>{Rd.init(r,e),_e.init(r,e)});function nl(r){return Yd(W_,r)}var H_=z("ZodMiniUnknown",(r,e)=>{Fd.init(r,e),_e.init(r,e)});function X_(){return Kd(H_)}var Y_=z("ZodMiniArray",(r,e)=>{Dd.init(r,e),_e.init(r,e)});function qr(r,e){return new Y_({type:"array",element:r,...re(e)})}var il=z("ZodMiniObject",(r,e)=>{Cd.init(r,e),_e.init(r,e),od(r,"shape",t=>t._zod.def.shape,!1)});function K(r,e){let t={type:"object",shape:r??{},...re(e)};return new il(t)}function xs(r,e){return new il({type:"object",shape:r,catchall:X_(),...re(e)})}var K_=z("ZodMiniUnion",(r,e)=>{ya.init(r,e),_e.init(r,e)});function it(r,e){return new K_({type:"union",options:r,...re(e)})}var Q_=z("ZodMiniDiscriminatedUnion",(r,e)=>{Od.init(r,e),_e.init(r,e)});function sl(r,e,t){return new Q_({type:"union",options:e,discriminator:r,...re(t)})}var Jd=z("ZodMiniRecord",(r,e)=>{Vd.init(r,e),_e.init(r,e)});function Ss(r,e,t){return!e||!e._zod?new Jd({type:"record",keyType:q(),valueType:r,...re(e)}):new Jd({type:"record",keyType:r,valueType:e,...re(t)})}var J_=z("ZodMiniEnum",(r,e)=>{Ld.init(r,e),_e.init(r,e),r.options=Object.values(e.entries)});function xa(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new J_({type:"enum",entries:t,...re(e)})}var ew=z("ZodMiniLiteral",(r,e)=>{Ud.init(r,e),_e.init(r,e)});function Zr(r,e){return new ew({type:"literal",values:Array.isArray(r)?r:[r],...re(e)})}var tw=z("ZodMiniTransform",(r,e)=>{Bd.init(r,e),_e.init(r,e)});function Ot(r){return new tw({type:"transform",transform:r})}var rw=z("ZodMiniOptional",(r,e)=>{$d.init(r,e),_e.init(r,e)});function F(r){return new rw({type:"optional",innerType:r})}var nw=z("ZodMiniDefault",(r,e)=>{Nd.init(r,e),_e.init(r,e)});function Es(r,e){return new nw({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():sa(e)}})}var iw=z("ZodMiniPipe",(r,e)=>{qd.init(r,e),_e.init(r,e)});function Vt(r,e){return new iw({type:"pipe",in:r,out:e})}var sw=z("ZodMiniCustom",(r,e)=>{Zd.init(r,e),_e.init(r,e)});function ks(r,e={}){return Qd(sw,r,e)}var st=nl().check(ks(r=>r>=0n&&r<1n<<62n,"Origin must be a non-negative 62-bit integer")).brand("Origin"),ri=st.parse(0n),qe=32;function Ts(){let r=new BigUint64Array(1);crypto.getRandomValues(r);let e=r[0]&0x1fffffffffffffn;return st.parse(e===0n?1n:e)}var de={Path:1n,MaxRequestId:2n,AuthorizationToken:3n,MaxAuthTokenCacheSize:4n,Authority:5n,Implementation:7n,RelayHops:0x40b55n,RelayCost:0x40b56n,Solicit:0x40b5an},ue=class r{vars;bytes;constructor(){this.vars=new Map,this.bytes=new Map}get size(){return this.vars.size+this.bytes.size}setBytes(e,t){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);this.bytes.set(e,t)}setVarint(e,t){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);this.vars.set(e,t)}getBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.get(e)}getVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.get(e)}removeBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.delete(e)}removeVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.delete(e)}async encode(e,t){if(t!==m.DRAFT_14&&t!==m.DRAFT_15){t===m.DRAFT_16&&await e.u53(this.vars.size+this.bytes.size);let n=[];for(let s of this.vars.keys())n.push({key:s,isVar:!0});for(let s of this.bytes.keys())n.push({key:s,isVar:!1});n.sort((s,a)=>s.key<a.key?-1:s.key>a.key?1:0);let i=0n;for(let s=0;s<n.length;s++){let{key:a,isVar:o}=n[s],c=s===0?a:a-i;if(i=a,await e.u62(c),o)await e.u62(this.vars.get(a));else{let u=this.bytes.get(a);await e.u53(u.length),await e.write(u)}}}else{await e.u53(this.vars.size+this.bytes.size);for(let[n,i]of this.vars)await e.u62(n),await e.u62(i);for(let[n,i]of this.bytes)await e.u62(n),await e.u53(i.length),await e.write(i)}}static async decode(e,t){let n=new r;if(t!==m.DRAFT_14&&t!==m.DRAFT_15&&t!==m.DRAFT_16){let i=0n,s=0;for(;!await e.done();){let a=await e.u62(),o=s===0?a:i+a;if(i=o,s++,o%2n===0n){if(n.vars.has(o))throw new Error(`duplicate parameter id: ${o.toString()}`);let c=await e.u62();n.setVarint(o,c)}else{if(n.bytes.has(o))throw new Error(`duplicate parameter id: ${o.toString()}`);let c=await e.u53(),u=await e.read(c);n.setBytes(o,u)}}}else{let i=await e.u53(),s=0n;for(let a=0;a<i;a++){let o;if(t===m.DRAFT_16){let c=await e.u62();o=a===0?c:s+c,s=o}else o=await e.u62();if(o%2n===0n){if(n.vars.has(o))throw new Error(`duplicate parameter id: ${o.toString()}`);let c=await e.u62();n.setVarint(o,c)}else{if(n.bytes.has(o))throw new Error(`duplicate parameter id: ${o.toString()}`);let c=await e.u53(),u=await e.read(c);n.setBytes(o,u)}}}return n}},Sa=0x02n,Ea=0x04n,ka=0x08n,Ta=0x0en,Ma=0x10n,Ia=0x20n,Pa=0x22n,za=0x40b58n,Ms=0x09n,Ra=0x21n,Fa=0x40b57n;function ol(r){switch(r){case Sa:case Ea:case ka:case za:return"varint";case Ta:case Ia:case Pa:return"uint8";case Ma:return"bool";case Ms:return"location";case Ra:case Fa:return"bytes";default:throw new Error(`unknown message parameter id: ${r.toString()}`)}}function ow(r){let[e,t]=Hn(r),[n,i]=Hn(t);if(i.length!==0)throw new Error("trailing bytes in message parameter Location");return{groupId:e,objectId:n}}function al({groupId:r,objectId:e}){let t=Ur(r),n=Ur(e),i=new Uint8Array(t.length+n.length);return i.set(t,0),i.set(n,t.length),i}var D=class r{vars;bytes;#e;constructor(){this.vars=new Map,this.bytes=new Map,this.#e=new Map}get subscriberPriority(){let e=this.vars.get(Ia);return e!==void 0?Number(e):void 0}set subscriberPriority(e){this.vars.set(Ia,BigInt(e))}get groupOrder(){let e=this.vars.get(Pa);return e!==void 0?Number(e):void 0}set groupOrder(e){this.vars.set(Pa,BigInt(e))}get forward(){let e=this.vars.get(Ma);return e!==void 0?e!==0n:void 0}set forward(e){this.vars.set(Ma,e?1n:0n)}get publisherPriority(){let e=this.vars.get(Ta);return e!==void 0?Number(e):void 0}set publisherPriority(e){this.vars.set(Ta,BigInt(e))}get expires(){return this.vars.get(ka)}set expires(e){this.vars.set(ka,e)}get deliveryTimeout(){return this.vars.get(Sa)}set deliveryTimeout(e){this.vars.set(Sa,e)}get maxCacheDuration(){return this.vars.get(Ea)}set maxCacheDuration(e){this.vars.set(Ea,e)}get largest(){let e=this.#e.get(Ms);return e&&{...e}}set largest(e){this.#e.set(Ms,{...e})}get subscriptionFilter(){let e=this.bytes.get(Ra);if(!(!e||e.length===0))return e[0]}set subscriptionFilter(e){this.bytes.set(Ra,new Uint8Array([e]))}get hopPath(){return this.bytes.get(Fa)}set hopPath(e){this.bytes.set(Fa,e)}get routeCost(){return this.vars.get(za)}set routeCost(e){this.vars.set(za,e)}async encode(e,t){if(await e.u53(this.vars.size+this.bytes.size+this.#e.size),t===m.DRAFT_14||t===m.DRAFT_15){for(let[n,i]of this.vars)await e.u62(n),await e.u62(i);for(let[n,i]of this.bytes)await e.u62(n),await e.u53(i.length),await e.write(i);for(let[n,i]of this.#e){let s=al(i);await e.u62(n),await e.u53(s.length),await e.write(s)}}else{let n=[];for(let s of this.vars.keys())n.push({key:s,storage:"var"});for(let s of this.bytes.keys())n.push({key:s,storage:"bytes"});for(let s of this.#e.keys())n.push({key:s,storage:"location"});n.sort((s,a)=>s.key<a.key?-1:s.key>a.key?1:0);let i=0n;for(let s=0;s<n.length;s++){let{key:a,storage:o}=n[s],c=s===0?a:a-i;if(i=a,await e.u62(c),t===m.DRAFT_16){if(o==="var")await e.u62(this.vars.get(a));else{let u=o==="bytes"?this.bytes.get(a):al(this.#e.get(a));await e.u53(u.length),await e.write(u)}continue}switch(ol(a)){case"varint":{let u=this.vars.get(a);if(u===void 0)throw new Error(`invalid varint message parameter: ${a.toString()}`);await e.u62(u);break}case"uint8":{let u=this.vars.get(a);if(u===void 0||u<0n||u>0xffn)throw new Error(`invalid uint8 message parameter: ${a.toString()}`);await e.u8(Number(u));break}case"bool":{let u=this.vars.get(a);if(u!==0n&&u!==1n)throw new Error(`invalid bool message parameter: ${a.toString()}`);await e.bool(u===1n);break}case"location":{let u=this.#e.get(a);if(u===void 0)throw new Error(`invalid Location message parameter: ${a.toString()}`);await e.u62(u.groupId),await e.u62(u.objectId);break}case"bytes":{let u=this.bytes.get(a);if(u===void 0)throw new Error(`invalid bytes message parameter: ${a.toString()}`);await e.u53(u.length),await e.write(u);break}}}}}static async decode(e,t){let n=await e.u53(),i=new r,s=0n;for(let a=0;a<n;a++){let o;if(t===m.DRAFT_14||t===m.DRAFT_15)o=await e.u62();else{let c=await e.u62();o=a===0?c:s+c,s=o}if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16){if(o%2n===0n){if(i.vars.has(o))throw new Error(`duplicate message parameter id: ${o.toString()}`);let c=await e.u62();i.vars.set(o,c)}else{let c=await e.u53(),u=await e.read(c);if(o===Ms){if(i.#e.has(o))throw new Error(`duplicate message parameter id: ${o.toString()}`);i.#e.set(o,ow(u))}else{if(i.bytes.has(o))throw new Error(`duplicate message parameter id: ${o.toString()}`);i.bytes.set(o,u)}}continue}if(i.vars.has(o)||i.bytes.has(o)||i.#e.has(o))throw new Error(`duplicate message parameter id: ${o.toString()}`);switch(ol(o)){case"varint":i.vars.set(o,await e.u62());break;case"uint8":i.vars.set(o,BigInt(await e.u8()));break;case"bool":i.vars.set(o,await e.bool()?1n:0n);break;case"location":{let c=await e.u62(),u=await e.u62();i.#e.set(o,{groupId:c,objectId:u});break}case"bytes":{let c=await e.u53();i.bytes.set(o,await e.read(c));break}}}return i}};function Da(r){return r!==m.DRAFT_14&&r!==m.DRAFT_15&&r!==m.DRAFT_16}function aw(r,e){if(!Da(e))return;let t=r.getBytes(de.RelayHops);if(t===void 0)return;let[n,i]=Lr(t);if(i.length!==0)throw new Error("trailing bytes in RELAY_HOPS");return st.parse(n)}function cw(r,e,t){Da(t)&&r.setBytes(de.RelayHops,fs(e))}function Gr(r){return r?.peer!==void 0}function Ca(r){if(!(r===void 0||r.peer===void 0))return{hops:[r.self],cost:0n}}function Oa(r,e){return e!==ri&&r.hops.includes(e)}function ni(r){ul(r.hops);let e=new D,t=r.hops.map(s=>fs(s)),n=new Uint8Array(t.reduce((s,a)=>s+a.length,0)),i=0;for(let s of t)n.set(s,i),i+=s.length;return e.hopPath=n,r.cost!==0n&&(e.routeCost=r.cost),e}async function ii(r,e){let t;try{t=await D.decode(r,e)}catch(n){throw new Ne(ee(n),{cause:n})}return cl(t)}function cl(r){try{let e=r.hopPath;if(e===void 0)throw new Error("advertisement is missing HOP_PATH");let t=[],n=e;for(;n.length>0;){let[i,s]=Lr(n);if(t.push(st.parse(i)),n=s,t.length>qe)throw new Error(`hop count exceeds maximum ${qe}`)}return ul(t),{hops:t,cost:r.routeCost??0n}}catch(e){throw new Ne(ee(e),{cause:e})}}function ul(r){if(r.length===0)throw new Error("hop path is empty");if(r.length>qe)throw new Error(`hop count ${r.length} exceeds maximum ${qe}`);for(let e=0;e<r.length;e++){let t=r[e];if(t!==ri&&r.indexOf(t,e+1)!==-1)throw new Error(`hop ${t} appears twice in the hop path`)}}async function Is(r){let e=r.getStats;if(typeof e!="function")return{};try{let t=await e.call(r);return{rtt:t.smoothedRtt!==void 0?Nn(t.smoothedRtt):void 0,estimatedSendRate:t.estimatedSendRate??void 0,bytesSent:t.bytesSent,bytesReceived:t.bytesReceived,bytesLost:t.bytesLost,packetsSent:t.packetsSent,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost}}catch{return{}}}function uw(r){return r!==void 0&&(r===1e3||r>=3e3&&r<=4999)}function dw(r,e){if(!(r.bufferedAmount<=e()))return(async()=>{for(;r.bufferedAmount>e();){if(r.readyState>1)throw new Error("WebSocket is closing");await new Promise(t=>setTimeout(t,10))}})()}var jr=class r{url;opened;closed;#e;#t;constructor(e,t={}){let n;if(typeof e=="string"){let d=t.webSocket??globalThis.WebSocket;if(!d)throw new Error("No WebSocket implementation found; pass options.webSocket");n=new d(e,t.protocols),this.url=e}else n=e,this.url=e.url??"";n.binaryType="arraybuffer",this.#e=n,this.#t=Math.max(1,Math.floor(t.highWaterMark??65536));let i=Promise.withResolvers(),s=Promise.withResolvers();this.opened=i.promise,this.closed=s.promise,this.opened.catch(()=>{});let a,o=new ReadableStream({start:d=>{a=d},cancel:()=>n.close()}),c=new WritableStream({write:d=>(n.send(d),dw(n,()=>this.#t)),close:()=>n.close(),abort:()=>n.close()});if(n.onopen=()=>{i.resolve({readable:o,writable:c,extensions:n.extensions,protocol:n.protocol})},n.onmessage=d=>{let f=d.data;if(typeof f=="string")a?.enqueue(f);else if(f instanceof ArrayBuffer)a?.enqueue(new Uint8Array(f));else if(ArrayBuffer.isView(f)){let l=f;a?.enqueue(new Uint8Array(l.buffer,l.byteOffset,l.byteLength))}},n.onerror=()=>{let d=new Error("WebSocket connection error");i.reject(d);try{a?.error(d)}catch{}},n.onclose=d=>{i.reject(new Error("WebSocket closed before opening"));try{a?.close()}catch{}s.resolve({closeCode:d.code??1006,reason:d.reason??""})},n.readyState!==0)if(n.readyState===1)i.resolve({readable:o,writable:c,extensions:n.extensions,protocol:n.protocol});else{i.reject(new Error("WebSocket is already closed"));try{a?.close()}catch{}s.resolve({closeCode:1006,reason:""})}let{signal:u}=t;u&&(u.aborted?n.close():u.addEventListener("abort",()=>n.close(),{once:!0}))}static adopt(e,t={}){return new r(e,t)}close(e={}){uw(e.closeCode)?this.#e.close(e.closeCode,e.reason):this.#e.close()}get highWaterMark(){return this.#t}setHighWaterMark(e){this.#t=Math.max(1,Math.floor(e))}};function dl(r,e={}){let t=typeof r=="string"?r:r.toString(),n=globalThis.WebSocketStream;if(n&&n!==jr&&!e.webSocket){let i=new n(t,{protocols:e.protocols,signal:e.signal});return{url:i.url,opened:i.opened.then(s=>({...s,readable:s.readable.pipeThrough(new TransformStream({transform(a,o){o.enqueue(a instanceof ArrayBuffer?new Uint8Array(a):a)}}))})),closed:i.closed,close:s=>i.close(s)}}return new jr(t,e)}function Va(r,e,t){return t===0n?null:e-r<=t/2n?r+t:null}var Ie=class{#e;#t;#r=0n;#n=!1;#i;#s=[];constructor(e){this.#e=0n,this.#t=e}tryClaim(e){if(e===0n)return 0n;let t=this.#t-this.#e;if(t<=0n)return 0n;let n=e<t?e:t;return this.#e+=n,n}async claim(e){if(e===0n)return 0n;for(;;){if(this.#n)throw this.#i??new Error("closed");let t=this.tryClaim(e);if(t>0n)return t;await new Promise((n,i)=>{this.#s.push({resolve:n,reject:i})})}}release(e){this.#e=this.#e>e?this.#e-e:0n,this.#o()}increaseMax(e){return e<this.#t?!1:(e===this.#t||(this.#t=e,this.#o()),!0)}close(e){this.#n=!0,this.#i??=e??new Error("closed");let t=this.#s;this.#s=[];for(let{reject:n}of t)n(this.#i)}receiveUpTo(e){return e>this.#t?!1:(e>this.#e&&(this.#e=e),!0)}consume(e){if(this.#r+=e,this.#e+2n*this.#r>this.#t){let t=this.#t+this.#r;return this.#t=t,this.#r=0n,this.#o(),t}return null}get available(){let e=this.#t-this.#e;return e>0n?e:0n}get max(){return this.#t}get used(){return this.#e}#o(){let e=this.#s;this.#s=[];for(let{resolve:t}of e)t()}};var si=class extends Error{source="session";streamErrorCode=null;constructor(e,t){super(e,t),this.name="WebTransportError"}},Wr=class extends Error{source="stream";streamErrorCode;constructor(e,t="stream reset"){super(`${t}: ${e}`),this.name="WebTransportError",this.streamErrorCode=e}};function Hr(r){if(typeof r!="object"||r===null)return 0;let{streamErrorCode:e}=r;return typeof e!="number"?0:e>>>0}function La(r){return Number(BigInt.asUintN(32,r))}var v=class r{static MAX=(1n<<62n)-1n;static MAX_SIZE=8;value;constructor(e){if(e<0n||e>r.MAX)throw new Error(`VarInt value out of range: ${e}`);this.value=e}static from(e){return new r(BigInt(e))}size(){let e=this.value;if(e<2n**6n)return 1;if(e<2n**14n)return 2;if(e<2n**30n)return 4;if(e<2n**62n)return 8;throw new Error("VarInt value too large")}encode(e){let t=this.value,n=this.size();if(e.byteOffset+e.byteLength+n>e.buffer.byteLength)throw new Error("destination buffer too small");let i=new DataView(e.buffer,e.byteOffset+e.byteLength,n);if(n===1)i.setUint8(0,Number(t));else if(n===2)i.setUint16(0,16384|Number(t),!1);else if(n===4)i.setUint32(0,2<<30|Number(t),!1);else if(n===8)i.setBigUint64(0,3n<<62n|t,!1);else throw new Error("VarInt value too large");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength+n)}static decode(e){if(e.byteLength<1)throw new Error("Unexpected end of buffer");let t=new DataView(e.buffer,e.byteOffset),n=t.getUint8(0),i=n>>6,s,a;switch(i){case 0:s=BigInt(n&63),a=1;break;case 1:if(2>e.length)throw new Error("Unexpected end of buffer");s=BigInt(t.getUint16(0,!1)&16383),a=2;break;case 2:if(4>e.length)throw new Error("Unexpected end of buffer");s=BigInt(t.getUint32(0,!1)&1073741823),a=4;break;case 3:if(8>e.length)throw new Error("Unexpected end of buffer");s=t.getBigUint64(0,!1)&0x3fffffffffffffffn,a=8;break;default:throw new Error("Invalid VarInt tag")}let o=new Uint8Array(e.buffer,e.byteOffset+a,e.byteLength-a);return[new r(s),o]}};var oe={Bi:0,Uni:1},Q=class r{value;constructor(e){this.value=e}static create(e,t,n){let i=e<<2n;return t===oe.Uni&&(i|=0x02n),n&&(i|=0x01n),new r(v.from(i))}get dir(){return(this.value.value&0x02n)!==0n?oe.Uni:oe.Bi}get serverInitiated(){return(this.value.value&0x01n)!==0n}get index(){return this.value.value>>2n}canRecv(e){return this.dir===oe.Uni?this.serverInitiated!==e:!0}canSend(e){return this.dir===oe.Uni?this.serverInitiated===e:!0}};var oi=16384,hl=oi-32,lw=[63n,16383n,1073741823n,4611686018427387903n];function fw(r){let e=0n;for(let t of lw){let n=BigInt(v.from(t).size());if(r<n)break;let i=r-n<t?r-n:t;v.from(i).size()===Number(n)&&i>e&&(e=i)}return e}function pl(r,e,t,n){let i=BigInt(1+t.value.size());if(r==="webtransport")return e>i?e-i:0n;let s=i+BigInt(v.from(n).size());return fw(e>s?e-s:0n)}var mr=16382n,Ua={maxIdleTimeout:0n,initialMaxData:0n,initialMaxStreamDataBidiLocal:0n,initialMaxStreamDataBidiRemote:0n,initialMaxStreamDataUni:0n,initialMaxStreamsBidi:0n,initialMaxStreamsUni:0n,maxDatagramFrameSize:0n,maxRecordSize:mr,resetStreamAt:!1};function Ps(r,e="webtransport"){return e==="webtransport"?hw(r):pw(r)}function le(r){return r==="qmux-00"||r==="qmux-01"||r==="qmux-02"}function Ut(r){return r==="qmux-01"||r==="qmux-02"}var Ba=0x348c67529ef8c7bdn,$a=0x348c67529ef8c7ben,ml=0x24n,Na=0x0571c59429cd0845n,_l=0x3d4f9c2a8b1e6075n,qa=0x1dn,fl=new Set([0x01n,0x04n,0x05n,0x06n,0x07n,0x08n,0x09n,0x20n,Na,_l,qa]);function hw(r){switch(r.type){case"stream":{let e=new Uint8Array(new ArrayBuffer(9+r.data.length),0,1);return e[0]=r.fin?9:8,e=r.id.value.encode(e),e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength+r.data.length),e.set(r.data,e.byteLength-r.data.length),e}case"reset_stream":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=4,e=r.id.value.encode(e),e=r.code.encode(e),e}case"stop_sending":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=5,e=r.id.value.encode(e),e=r.code.encode(e),e}case"connection_close":case"application_close":{let e=new TextEncoder().encode(r.reason),t=new Uint8Array(new ArrayBuffer(9+e.length),0,1);return t[0]=r.type==="application_close"?29:28,t=r.code.encode(t),t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength+e.length),t.set(e,t.byteLength-e.length),t}default:throw new Error("flow control frames are not supported in WebTransport version")}}function pw(r){switch(r.type){case"stream":{let e=v.from(14|(r.fin?1:0)),t=v.from(r.offset??0n),n=v.from(r.data.length),i=32+r.data.length,s=new Uint8Array(new ArrayBuffer(i),0,0);return s=e.encode(s),s=r.id.value.encode(s),s=t.encode(s),s=n.encode(s),s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength+r.data.length),s.set(r.data,s.byteLength-r.data.length),s}case"reset_stream":{let e=v.from(4),t=v.from(r.finalSize),n=new Uint8Array(new ArrayBuffer(32),0,0);return n=e.encode(n),n=r.id.value.encode(n),n=r.code.encode(n),n=t.encode(n),n}case"stop_sending":{let e=v.from(5),t=new Uint8Array(new ArrayBuffer(24),0,0);return t=e.encode(t),t=r.id.value.encode(t),t=r.code.encode(t),t}case"connection_close":{let e=v.from(28),t=v.from(0),n=new TextEncoder().encode(r.reason),i=v.from(n.length),s=new Uint8Array(new ArrayBuffer(32+n.length),0,0);return s=e.encode(s),s=r.code.encode(s),s=t.encode(s),s=i.encode(s),s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength+n.length),s.set(n,s.byteLength-n.length),s}case"application_close":{let e=v.from(29),t=new TextEncoder().encode(r.reason),n=v.from(t.length),i=new Uint8Array(new ArrayBuffer(24+t.length),0,0);return i=e.encode(i),i=r.code.encode(i),i=n.encode(i),i=new Uint8Array(i.buffer,i.byteOffset,i.byteLength+t.length),i.set(t,i.byteLength-t.length),i}case"max_data":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(16).encode(e),e=v.from(r.max).encode(e),e}case"max_stream_data":{let e=new Uint8Array(new ArrayBuffer(24),0,0);return e=v.from(17).encode(e),e=r.id.value.encode(e),e=v.from(r.max).encode(e),e}case"max_streams_bidi":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(18).encode(e),e=v.from(r.max).encode(e),e}case"max_streams_uni":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(19).encode(e),e=v.from(r.max).encode(e),e}case"data_blocked":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(20).encode(e),e=v.from(r.limit).encode(e),e}case"stream_data_blocked":{let e=new Uint8Array(new ArrayBuffer(24),0,0);return e=v.from(21).encode(e),e=r.id.value.encode(e),e=v.from(r.limit).encode(e),e}case"streams_blocked_bidi":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(22).encode(e),e=v.from(r.limit).encode(e),e}case"streams_blocked_uni":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(23).encode(e),e=v.from(r.limit).encode(e),e}case"transport_parameters":{let e=mw(r.params),t=new Uint8Array(new ArrayBuffer(16+e.byteLength),0,0);return t=v.from(0x3f5153300d0a0d0an).encode(t),t=v.from(e.byteLength).encode(t),t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength+e.byteLength),t.set(e,t.byteLength-e.byteLength),t}case"ping_request":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from(Ba).encode(e),e=v.from(r.sequence).encode(e),e}case"ping_response":{let e=new Uint8Array(new ArrayBuffer(16),0,0);return e=v.from($a).encode(e),e=v.from(r.sequence).encode(e),e}case"datagram":{let e=v.from(r.data.length),t=new Uint8Array(new ArrayBuffer(16+r.data.length),0,0);return t=v.from(49).encode(t),t=e.encode(t),t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength+r.data.length),t.set(r.data,t.byteLength-r.data.length),t}}}function mw(r){let e=new Uint8Array(new ArrayBuffer(256),0,0);function t(n,i,s){if(s===0n)return n;let a=v.from(s);return n=v.from(i).encode(n),n=v.from(a.size()).encode(n),n=a.encode(n),n}return e=t(e,1,r.maxIdleTimeout),e=t(e,4,r.initialMaxData),e=t(e,5,r.initialMaxStreamDataBidiLocal),e=t(e,6,r.initialMaxStreamDataBidiRemote),e=t(e,7,r.initialMaxStreamDataUni),e=t(e,8,r.initialMaxStreamsBidi),e=t(e,9,r.initialMaxStreamsUni),e=t(e,32,r.maxDatagramFrameSize),e=t(e,Na,r.maxRecordSize),r.resetStreamAt&&(e=v.from(qa).encode(e),e=v.from(0).encode(e)),e}function wl(r){let e={...Ua},t=new Set,n;for(;r.byteLength>0;){[n,r]=v.decode(r);let i=n.value;[n,r]=v.decode(r);let s=Number(n.value);if(r.byteLength<s)throw new Error("transport parameter truncated");let a=r.slice(0,s);if(r=r.slice(s),fl.has(i)){if(t.has(i))throw new Error(`duplicate transport parameter 0x${i.toString(16)}`);t.add(i)}if(i===_l)throw new Error("unexpected application_protocols parameter over WebSocket");if(i===qa){if(a.byteLength!==0)throw new Error("reset_stream_at transport parameter must be empty");e.resetStreamAt=!0;continue}if(i===0x00n||i===0x02n||i===0x03n||i>=0x0an&&i<=0x10n)throw new Error(`forbidden QUIC v1 transport parameter 0x${i.toString(16)}`);if(!fl.has(i))continue;let[o,c]=v.decode(a);if(c.byteLength!==0)throw new Error(`transport parameter 0x${i.toString(16)} has trailing bytes`);let u=o.value;switch(i){case 0x01n:e.maxIdleTimeout=u;break;case 0x04n:e.initialMaxData=u;break;case 0x05n:e.initialMaxStreamDataBidiLocal=u;break;case 0x06n:e.initialMaxStreamDataBidiRemote=u;break;case 0x07n:e.initialMaxStreamDataUni=u;break;case 0x08n:e.initialMaxStreamsBidi=u;break;case 0x09n:e.initialMaxStreamsUni=u;break;case 0x20n:e.maxDatagramFrameSize=u;break;case Na:e.maxRecordSize=u;break;default:throw new Error(`unhandled recognized transport parameter 0x${i.toString(16)}`)}}return e}function gl(r,e="webtransport"){if(r.length===0)throw new Error("Invalid frame: empty buffer");return e==="webtransport"?_w(r):ww(r)}function Lt(r,e){if(r.byteLength<e)throw new Error(`frame truncated: need ${e} bytes, have ${r.byteLength}`);return[r.slice(0,e),r.slice(e)]}function yl(r){let e=[];for(;r.byteLength>0;){let t=gw(r);if(t===null)break;let[n,i]=t;n!==null&&e.push(n),r=i}return e}function _w(r){let e=r[0];r=r.slice(1);let t;if(e===4){[t,r]=v.decode(r);let n=new Q(t);return[t,r]=v.decode(r),{type:"reset_stream",id:n,code:t,finalSize:0n}}if(e===5){[t,r]=v.decode(r);let n=new Q(t);return[t,r]=v.decode(r),{type:"stop_sending",id:n,code:t}}if(e===29||e===28){[t,r]=v.decode(r);let n=t,i=new TextDecoder().decode(r);return e===29?{type:"application_close",code:n,reason:i}:{type:"connection_close",code:n,reason:i}}if(e===8||e===9)return[t,r]=v.decode(r),{type:"stream",id:new Q(t),data:r,fin:e===9};throw new Error(`Invalid frame type: ${e}`)}function ww(r){let e;[e,r]=v.decode(r);let t=e.value;if(t===0x00n)return null;if(t>=0x08n&&t<=0x0fn){let n=(t&0x04n)!==0n,i=(t&0x02n)!==0n,s=(t&0x01n)!==0n;[e,r]=v.decode(r);let a=new Q(e),o=0n;n&&([e,r]=v.decode(r),o=e.value);let c;if(i){[e,r]=v.decode(r);let u=Number(e.value);[c,r]=Lt(r,u)}else c=r;return{type:"stream",id:a,offset:o,data:c,fin:s}}if(t===0x04n){[e,r]=v.decode(r);let n=new Q(e);[e,r]=v.decode(r);let i=e;[e,r]=v.decode(r);let s=e.value;return{type:"reset_stream",id:n,code:i,finalSize:s}}if(t===ml){[e,r]=v.decode(r);let n=new Q(e);[e,r]=v.decode(r);let i=e;[e,r]=v.decode(r);let s=e.value;[e,r]=v.decode(r);let a=e.value;if(a>s)throw new Error("RESET_STREAM_AT reliable_size exceeds final_size");return{type:"reset_stream",id:n,code:i,finalSize:s,reliableSize:a}}if(t===0x05n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),{type:"stop_sending",id:n,code:e}}if(t===0x1cn||t===0x1dn){[e,r]=v.decode(r);let n=e;t===0x1cn&&([e,r]=v.decode(r)),[e,r]=v.decode(r);let i=Number(e.value),s;[s,r]=Lt(r,i);let a=new TextDecoder().decode(s);return t===0x1dn?{type:"application_close",code:n,reason:a}:{type:"connection_close",code:n,reason:a}}if(t===0x10n)return[e,r]=v.decode(r),{type:"max_data",max:e.value};if(t===0x11n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),{type:"max_stream_data",id:n,max:e.value}}if(t===0x12n)return[e,r]=v.decode(r),{type:"max_streams_bidi",max:e.value};if(t===0x13n)return[e,r]=v.decode(r),{type:"max_streams_uni",max:e.value};if(t===0x14n)return[e,r]=v.decode(r),{type:"data_blocked",limit:e.value};if(t===0x15n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),{type:"stream_data_blocked",id:n,limit:e.value}}if(t===0x16n)return[e,r]=v.decode(r),{type:"streams_blocked_bidi",limit:e.value};if(t===0x17n)return[e,r]=v.decode(r),{type:"streams_blocked_uni",limit:e.value};if(t===0x3f5153300d0a0d0an){[e,r]=v.decode(r);let n=Number(e.value),i;return[i,r]=Lt(r,n),{type:"transport_parameters",params:wl(i)}}if(t===Ba)return[e,r]=v.decode(r),{type:"ping_request",sequence:e.value};if(t===$a)return[e,r]=v.decode(r),{type:"ping_response",sequence:e.value};if(t===0x30n)return{type:"datagram",data:r,lengthPrefixed:!1};if(t===0x31n){[e,r]=v.decode(r);let n=Number(e.value),i;return[i,r]=Lt(r,n),{type:"datagram",data:i,lengthPrefixed:!0}}throw new Error(`Invalid QMux frame type: 0x${t.toString(16)}`)}function gw(r){if(r.byteLength===0)return null;let e;[e,r]=v.decode(r);let t=e.value;if(t===0x00n)return[null,r];if(t>=0x08n&&t<=0x0fn){let n=(t&0x04n)!==0n,i=(t&0x02n)!==0n,s=(t&0x01n)!==0n;[e,r]=v.decode(r);let a=new Q(e),o=0n;n&&([e,r]=v.decode(r),o=e.value);let c;if(i){[e,r]=v.decode(r);let u=Number(e.value);[c,r]=Lt(r,u)}else c=r,r=r.slice(r.byteLength);return[{type:"stream",id:a,offset:o,data:c,fin:s},r]}if(t===0x04n){[e,r]=v.decode(r);let n=new Q(e);[e,r]=v.decode(r);let i=e;[e,r]=v.decode(r);let s=e.value;return[{type:"reset_stream",id:n,code:i,finalSize:s},r]}if(t===ml){[e,r]=v.decode(r);let n=new Q(e);[e,r]=v.decode(r);let i=e;[e,r]=v.decode(r);let s=e.value;[e,r]=v.decode(r);let a=e.value;if(a>s)throw new Error("RESET_STREAM_AT reliable_size exceeds final_size");return[{type:"reset_stream",id:n,code:i,finalSize:s,reliableSize:a},r]}if(t===0x05n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),[{type:"stop_sending",id:n,code:e},r]}if(t===0x1cn||t===0x1dn){[e,r]=v.decode(r);let n=e;t===0x1cn&&([e,r]=v.decode(r)),[e,r]=v.decode(r);let i=Number(e.value),s;[s,r]=Lt(r,i);let a=new TextDecoder().decode(s);return[t===0x1dn?{type:"application_close",code:n,reason:a}:{type:"connection_close",code:n,reason:a},r]}if(t===0x10n)return[e,r]=v.decode(r),[{type:"max_data",max:e.value},r];if(t===0x11n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),[{type:"max_stream_data",id:n,max:e.value},r]}if(t===0x12n)return[e,r]=v.decode(r),[{type:"max_streams_bidi",max:e.value},r];if(t===0x13n)return[e,r]=v.decode(r),[{type:"max_streams_uni",max:e.value},r];if(t===0x14n)return[e,r]=v.decode(r),[{type:"data_blocked",limit:e.value},r];if(t===0x15n){[e,r]=v.decode(r);let n=new Q(e);return[e,r]=v.decode(r),[{type:"stream_data_blocked",id:n,limit:e.value},r]}if(t===0x16n)return[e,r]=v.decode(r),[{type:"streams_blocked_bidi",limit:e.value},r];if(t===0x17n)return[e,r]=v.decode(r),[{type:"streams_blocked_uni",limit:e.value},r];if(t===0x3f5153300d0a0d0an){[e,r]=v.decode(r);let n=Number(e.value),i;return[i,r]=Lt(r,n),[{type:"transport_parameters",params:wl(i)},r]}if(t===Ba)return[e,r]=v.decode(r),[{type:"ping_request",sequence:e.value},r];if(t===$a)return[e,r]=v.decode(r),[{type:"ping_response",sequence:e.value},r];if(t===0x30n)return[{type:"datagram",data:r,lengthPrefixed:!1},r.slice(r.byteLength)];if(t===0x31n){[e,r]=v.decode(r);let n=Number(e.value),i;return[i,r]=Lt(r,n),[{type:"datagram",data:i,lengthPrefixed:!0},r]}throw new Error(`Invalid QMux frame type: 0x${t.toString(16)}`)}var ai=class{#e=[];#t=!1;#r;#n;#i=!1;#s;readable;constructor(e,t,n=()=>{}){this.#s=n,this.readable=new ReadableStream({pull:async i=>{for(;this.#e.length===0;){if(this.#r){i.error(this.#r);return}if(this.#t){i.close();return}await new Promise(a=>{this.#n=a})}let s=this.#e.shift();i.enqueue(s),e(s.byteLength)},cancel:i=>{this.#r??=new Error("stream cancelled"),t(this.#o(),i),this.#a(),this.#c()}},{highWaterMark:0})}push(e){return this.#t||this.#r?!1:(this.#e.push(e),this.#c(),!0)}finish(){this.#t=!0,this.#a(),this.#c()}reset(e){let t=this.error(e);return this.#a(),t}error(e){if(this.#r)return 0;this.#r=e;let t=this.#o();return this.#c(),t}#o(){let e=0;for(let t of this.#e)e+=t.byteLength;return this.#e=[],e}#a(){this.#i||(this.#i=!0,this.#s())}#c(){let e=this.#n;e&&(this.#n=void 0,e())}};var zs=class{#e;constructor(e){this.#e=e.getWriter()}ready(){return this.#e.ready}write(e){return this.#e.write(e)}wantsMore(){let e=this.#e.desiredSize;return e!==null&&e>0}},ci=0,bw=1024,Rs=class{#e;#t;#r;#n;#i=[];#s=0;#o=[];#a=new Map;#c=new Map;#d=0;#l;constructor(e,t){this.#e=e,this.#t=t?.onActivity??(()=>{}),this.#r=t?.controlHighWater??256*1024,this.#p()}enqueueControl(e){if(this.#n)throw this.#n;this.#i.push(e),this.#s+=e.byteLength,this.#s>this.#r&&console.warn(`qmux: control backlog ${this.#s} bytes exceeds high-water`),this.#u()}enqueueDatagram(e){this.#n||this.#e.wantsMore()&&(this.#o.length>=bw||(this.#o.push(e),this.#u()))}setSendOrder(e,t){this.#a.set(e,t)}enqueueStream(e,t){return this.#n?Promise.reject(this.#n):this.#c.has(e)?Promise.reject(new Error(`stream ${e} already has a queued frame`)):new Promise((n,i)=>{this.#c.set(e,{seq:this.#d++,bytes:t,resolve:n,reject:i}),this.#u()})}dropStream(e,t){this.#a.delete(e);let n=this.#c.get(e);n&&(this.#c.delete(e),n.reject(t))}forget(e){this.#a.delete(e)}close(e){if(!this.#n){this.#n=e;for(let t of this.#c.values())t.reject(e);this.#c.clear(),this.#a.clear(),this.#o.length=0,this.#u()}}#u(){let e=this.#l;e&&(this.#l=void 0,e())}#f(){let e,t=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY;for(let[i,s]of this.#c){let a=this.#a.get(i)??ci;(a>t||a===t&&s.seq<n)&&(t=a,n=s.seq,e=i)}return e}async#p(){try{for(;;){if(this.#i.length===0&&this.#o.length===0&&this.#c.size===0){if(this.#n)return;await new Promise(n=>{this.#l=n});continue}if(await this.#e.ready(),this.#i.length>0){let n=this.#i.shift();this.#s-=n.byteLength,await this.#e.write(n),this.#t();continue}if(this.#o.length>0){let n=this.#o.shift();await this.#e.write(n),this.#t();continue}if(this.#n)return;if(this.#c.size===0)continue;let e=this.#f(),t=this.#c.get(e);this.#c.delete(e);try{await this.#e.write(t.bytes)}catch(n){throw t.reject(n instanceof Error?n:new Error(String(n))),n}this.#t(),t.resolve()}}catch(e){this.#m(e instanceof Error?e:new Error(String(e)))}}#m(e){this.#n??=e;for(let t of this.#c.values())t.reject(e);this.#c.clear(),this.#i.length=0,this.#s=0,this.#o.length=0}};var vw={maxStreamsBidi:100n,maxStreamsUni:100n,maxData:1048576n,maxStreamDataBidiLocal:262144n,maxStreamDataBidiRemote:262144n,maxStreamDataUni:262144n,maxIdleTimeout:30000n,maxRecordSize:mr,maxDatagramFrameSize:mr};function Aw(r){return{maxIdleTimeout:r.maxIdleTimeout,initialMaxData:r.maxData,initialMaxStreamDataBidiLocal:r.maxStreamDataBidiLocal,initialMaxStreamDataBidiRemote:r.maxStreamDataBidiRemote,initialMaxStreamDataUni:r.maxStreamDataUni,initialMaxStreamsBidi:r.maxStreamsBidi,initialMaxStreamsUni:r.maxStreamsUni,maxDatagramFrameSize:r.maxDatagramFrameSize<r.maxRecordSize?r.maxDatagramFrameSize:r.maxRecordSize,maxRecordSize:r.maxRecordSize,resetStreamAt:!1}}var Za=class{send;incomingHighWaterMark=1024;incomingMaxAge=null;outgoingHighWaterMark=1024;outgoingMaxAge=null;readable;writable;#e;#t=0;constructor(e){this.send=e,this.readable=new ReadableStream({start:t=>{this.#e=t}},{highWaterMark:this.incomingHighWaterMark}),this.writable=new WritableStream({write:t=>{this.#t>0&&t.byteLength<=this.#t&&this.send(t)}})}get maxDatagramSize(){return this.#t}setMaxDatagramSize(e){this.#t=e}push(e){this.#e.desiredSize===null||this.#e.desiredSize<=0||this.#e.enqueue(e)}close(e){try{e?this.#e.error(e):this.#e.close()}catch{}}},Fs=class{readable;#e;#t=[];#r;#n=!1;#i=!1;constructor(){this.readable=new ReadableStream({start:e=>{this.#e=e},pull:()=>{if(!this.#s())return new Promise(e=>{this.#r=e})},cancel:()=>{this.#n=!0,this.#o(new Error("incoming stream acceptor cancelled")),this.#a()}},{highWaterMark:0})}push(e,t,n){return this.#n||this.#i?!1:(this.#t.push({value:e,onAccept:t,onDrop:n}),this.#r&&(this.#s(),this.#a()),!0)}close(e){if(!(this.#i||this.#n)){this.#i=!0,this.#o(e??new Error("session closed"));try{e?this.#e.error(e):this.#e.close()}catch{}this.#a()}}#s(){let e=this.#t.shift();if(!e)return!1;try{this.#e.enqueue(e.value),e.onAccept()}catch{e.onDrop(new Error("incoming stream acceptor cancelled"))}return!0}#o(e){let t=this.#t;this.#t=[];for(let n of t)n.onDrop(e)}#a(){let e=this.#r;this.#r=void 0,e?.()}},xw=64*1024;function Sw(r,e){return"opened"in r?r:jr.adopt(r,{highWaterMark:e})}function Ds(r){switch(r){case"qmux-02":return"qmux-02.";case"qmux-01":return"qmux-01.";case"qmux-00":return"qmux-00."}}var Ga=["qmux-02","qmux-01","qmux-00"];function Ew(r){let e=typeof r=="string"?new URL(r):r,t;switch(e.protocol){case"https:":case"wss:":t="wss:";break;case"http:":case"ws:":t="ws:";break;default:throw new Error(`Unsupported protocol: ${e.protocol}`)}return`${t}//${e.host}${e.pathname}${e.search}`}var kw=["qmux-02","qmux-01","qmux-00","webtransport"];function Tw(r,e,t){let n=[];for(let i of r){if(Ga.find(c=>i.startsWith(Ds(c)))!==void 0){n.push(i);continue}if(!(i in e))throw new Error(`Sec-WebSocket-Protocol entry ${JSON.stringify(i)} has no qmux prefix and no versions mapping`);let a=e[i],o=a===null?Ga:Array.isArray(a)?a:[a];for(let c of o)n.push(`${Ds(c)}${i}`)}return t||n.push(...kw),n}function Mw(r){for(let e of Ga)if(r===e||r.startsWith(Ds(e)))return e;return"webtransport"}function Iw(r,e){if(r===""||e==="webtransport"||r===e)return"";let t=Ds(e);return r.startsWith(t)?r.slice(t.length):""}var Cs=class{#e;#t=new Set;isClosed(e){return this.#e!==void 0&&e<=this.#e&&!this.#t.has(e)}record(e){if(this.#e!==void 0&&e<=this.#e){this.#t.delete(e);return}for(let t=(this.#e??-1n)+1n;t<e;t++)this.#t.add(t);this.#e=e}},ui=class r{#e;#t;#r;#n=!1;#i;#s;#o;#a=new Map;#c=new Map;#d=0n;#l=0n;#u="webtransport";#f="";get protocol(){return this.#f}ready;#p;#m;closed;#b;#x;incomingBidirectionalStreams;#v;incomingUnidirectionalStreams;#g;datagrams=new Za(e=>this.#Te(e));#T;#h;#S={...Ua};#_=!1;#E=new Ie(BigInt(Number.MAX_SAFE_INTEGER));#O=0n;#F=0n;#Q=0n;#w=new Map;#oe=new Cs;#ae=new Cs;#P=new Ie(BigInt(Number.MAX_SAFE_INTEGER));#z=new Ie(BigInt(Number.MAX_SAFE_INTEGER));#D;#C;#$=Date.now();#V=Date.now();#N=0;#q=0;#Z=!0;#G=0;#j;#R;constructor(e,t){if(t?.requireUnreliable)throw new Error("not allowed to use WebSocket; requireUnreliable is true");t?.serverCertificateHashes&&console.warn("serverCertificateHashes is not supported; trying anyway");let n=typeof e=="string"||e instanceof URL,i=n?Tw(t?.protocols??[],t?.versions??{},t?.requireProtocol??!1):[];this.#T={...vw,...t?.config},this.#h=Aw(this.#T),this.#r=t?.sendBufferSize??xw,this.#D=new Ie(this.#T.maxStreamsBidi),this.#C=new Ie(this.#T.maxStreamsUni);let s=Promise.withResolvers();this.ready=s.promise,this.#p=s.resolve,this.#m=s.reject,this.ready.catch(()=>{});let a=Promise.withResolvers();this.closed=a.promise,this.#b=a.resolve,this.#x=a.reject,this.closed.catch(()=>{}),this.#v=new Fs,this.incomingBidirectionalStreams=this.#v.readable,this.#g=new Fs,this.incomingUnidirectionalStreams=this.#g.readable,this.#ce(n?dl(Ew(e),{protocols:i,highWaterMark:this.#r}):Sw(e,this.#r))}static accept(e,t){let n=new r(e,t);return n.#n=!0,n.#i=t?.protocol,n}#ce(e){this.#e=e,e.opened.then(t=>{this.#s||(this.#de(this.#i??t.protocol,new zs(t.writable)),this.#ue(t.readable.getReader()))},t=>{this.#o??=t instanceof Error?t:new Error("WebSocketStream failed to open"),this.#A(1006,"WebSocketStream error")}),e.closed.then(t=>{this.#o??=new Error(`Connection closed: ${t.closeCode??0} ${t.reason??""}`),this.#A(t.closeCode??1006,t.reason??"")},t=>{this.#o??=t instanceof Error?t:new Error("WebSocketStream closed"),this.#A(1006,"WebSocketStream error")})}async#ue(e){try{for(;;){let{value:t,done:n}=await e.read();if(n)break;if(typeof t=="string"){this.#I(1003,"text frames are not valid for QMux"),this.#A(1003,"text frames are not valid for QMux");return}this.#le(t instanceof ArrayBuffer?new Uint8Array(t):t)}}catch(t){this.#o??=t instanceof Error?t:new Error("WebSocketStream read error"),this.#A(1006,"WebSocketStream read error")}}#de(e,t){let n=Mw(e);this.#u=n,this.#f=Iw(e,n),this.#h={...this.#h,maxDatagramFrameSize:Ut(n)?this.#h.maxDatagramFrameSize:0n,resetStreamAt:n==="qmux-02"},this.#t=new Rs(t,{onActivity:()=>{this.#V=Date.now()}}),le(n)&&(this.#E.close(),this.#P.close(),this.#z.close(),this.#E=new Ie(0n),this.#P=new Ie(0n),this.#z=new Ie(0n),this.#F=this.#h.initialMaxData,this.#Se()),this.#p()}#le(e){this.#$=Date.now();try{if(Ut(this.#u)){if(BigInt(e.byteLength)>this.#h.maxRecordSize)throw new Error(`record exceeds our max_record_size (${e.byteLength} > ${this.#h.maxRecordSize})`);let t=yl(e);for(let n of t)this.#J(n)}else{if(this.#u==="qmux-00"&&e.byteLength>oi)throw new Error(`frame exceeds max_frame_size (${e.byteLength} > ${oi})`);let t=gl(e,this.#u);t!==null&&this.#J(t)}}catch(t){console.error("Protocol violation:",t),this.#I(1002,"Protocol violation"),this.#A(1002,"Protocol violation",t)}}#J(e){if(this.#u==="qmux-02"&&e.type==="transport_parameters"===this.#_)throw new Error("QX_TRANSPORT_PARAMETERS must be the first frame");if(e.type==="stream")this.#ve(e);else if(e.type==="reset_stream")this.#Ae(e);else if(e.type==="stop_sending")this.#xe(e);else if(e.type==="application_close"||e.type==="connection_close")this.#o??=new Error(`Connection closed: ${e.code.value} ${e.reason}`),e.type==="application_close"?this.#se(Number(e.code.value),e.reason):this.#A(Number(e.code.value),e.reason),this.#B();else if(e.type==="transport_parameters")this.#fe(e.params);else if(e.type==="max_data")this.#E.increaseMax(e.max);else if(e.type==="max_stream_data"){let t=this.#w.get(e.id.value.value);t&&t.sendCredit.increaseMax(e.max)}else if(e.type==="max_streams_bidi")this.#P.increaseMax(e.max);else if(e.type==="max_streams_uni")this.#z.increaseMax(e.max);else if(e.type==="datagram"){if(this.#h.maxDatagramFrameSize===0n)throw new Error("received a DATAGRAM but did not advertise datagram support");let t=e.data.byteLength,n=e.lengthPrefixed===!1?1:1+v.from(t).size();if(BigInt(n+t)>this.#h.maxDatagramFrameSize)throw new Error("received a DATAGRAM larger than our advertised max_datagram_frame_size");this.datagrams.push(e.data)}else if(e.type==="ping_request"){if(this.#u==="qmux-02"){if(this.#j!==void 0&&e.sequence<=this.#j)throw new Error("QX_PING request sequence must strictly increase");this.#j=e.sequence}this.#y({type:"ping_response",sequence:e.sequence})}else if(e.type==="ping_response"){if(this.#u==="qmux-02"&&e.sequence>=BigInt(this.#G))throw new Error("QX_PING response echoed a sequence we never sent")}else e.type==="data_blocked"||e.type==="stream_data_blocked"||e.type==="streams_blocked_bidi"||e.type}#fe(e){if(!this.#_){if(Ut(this.#u)&&e.maxRecordSize<mr)throw new Error("max_record_size below the default minimum");if(this.#_=!0,this.#S=e,this.#E.increaseMax(e.initialMaxData),this.#P.increaseMax(e.initialMaxStreamsBidi),this.#z.increaseMax(e.initialMaxStreamsUni),Ut(this.#u)&&e.maxDatagramFrameSize>0n){let t=e.maxRecordSize<e.maxDatagramFrameSize?e.maxRecordSize:e.maxDatagramFrameSize,n=BigInt(1+v.from(t).size()),i=t>n?t-n:0n;this.datagrams.setMaxDatagramSize(Number(i))}for(let[t,n]of this.#w){let s=new Q(v.from(t)).dir===oe.Bi?e.initialMaxStreamDataBidiRemote:e.initialMaxStreamDataUni;n.sendCredit.increaseMax(s)}this.#pe()}}#he(){if(!Ut(this.#u))return 0n;let e=this.#h.maxIdleTimeout,t=this.#S.maxIdleTimeout;return e===0n&&t===0n?0n:e===0n?t:t===0n||e<t?e:t}#pe(){let e=this.#he();if(e===0n)return;let t=Math.max(50,Number(e)/6);this.#R=setInterval(()=>this.#_e(Number(e)),t)}#me(){return this.#$>this.#N&&(this.#N=this.#$,this.#Z=!0),this.#Z&&this.#V>this.#q&&(this.#q=this.#V,this.#Z=!1),Math.max(this.#N,this.#q)}#_e(e){if(this.#s){this.#R&&clearInterval(this.#R);return}let t=Date.now();if(t-this.#me()>e){this.#o??=new Error("idle timeout"),this.#A(0,"idle timeout"),this.#B();return}if(t-this.#V>e/3){let n=this.#G;this.#G+=1;try{this.#y({type:"ping_request",sequence:BigInt(n)})}catch(i){console.warn("qmux: keep-alive ping failed",i)}}}async#we(e,t){let n=this.#w.get(e);if(!n)return t;for(;;){let i=n.sendCredit.tryClaim(t);if(i===0n){if(this.#s)throw this.#s;let a=await n.sendCredit.claim(t);n.sendCredit.release(a);continue}let s=this.#E.tryClaim(i);if(s===0n){if(n.sendCredit.release(i),this.#s)throw this.#s;let a=await this.#E.claim(1n);this.#E.release(a);continue}return s<i&&n.sendCredit.release(i-s),s}}#ee(e,t){if(!le(this.#u)||t===0)return!0;let n=BigInt(t);if(this.#O+n>this.#F)return!1;this.#O+=n;let i=this.#w.get(e);if(i){if(i.recvOffset+n>i.recvMax)return!1;i.recvOffset+=n}return!0}#M(e){!le(this.#u)||e===0||e===0n||(this.#Q+=BigInt(e),this.#ge())}#te(e,t){if(!le(this.#u)||t===0)return;let n=this.#w.get(e);n&&(n.recvConsumed+=BigInt(t),this.#ye(e,n))}#ge(){let e=Va(this.#Q,this.#F,this.#h.initialMaxData);e!==null&&(this.#F=e,this.#y({type:"max_data",max:e}))}#ye(e,t){let n=new Q(v.from(e)),i;n.dir===oe.Bi?i=n.serverInitiated===this.#n?this.#h.initialMaxStreamDataBidiLocal:this.#h.initialMaxStreamDataBidiRemote:i=this.#h.initialMaxStreamDataUni;let s=Va(t.recvConsumed,t.recvMax,i);s!==null&&(t.recvMax=s,this.#y({type:"max_stream_data",id:n,max:s}))}#re(e){if(!le(this.#u))return;let n=(e===oe.Bi?this.#D:this.#C).consume(1n);n!==null&&(e===oe.Bi?this.#y({type:"max_streams_bidi",max:n}):this.#y({type:"max_streams_uni",max:n}))}#L(e){return e===oe.Bi?this.#oe:this.#ae}#be(e){if(!le(this.#u))return 0n;let t=e.id.value.value,n=this.#w.get(t),i=n?.recvOffset??0n,s=e.finalSize>i?e.finalSize:i,a=s-i,o=n?.recvMax??(e.id.dir===oe.Bi?this.#h.initialMaxStreamDataBidiRemote:this.#h.initialMaxStreamDataUni);return s>o||this.#O+a>this.#F?null:(this.#O+=a,n&&(n.recvOffset=s),a)}#k(e){if(!this.#a.has(e)&&!this.#c.has(e)){let t=this.#w.get(e);t&&(t.sendCredit.close(),this.#w.delete(e))}}#ve(e){if(this.#s)return;let t=e.id.value.value;if(!e.id.canRecv(this.#n))throw new Error("Invalid stream ID direction");let n=this.#c.get(t);if(!(le(this.#u)&&e.id.serverInitiated!==this.#n&&!n&&this.#L(e.id.dir).isClosed(e.id.index))){if(n){if(!this.#ee(t,e.data.byteLength)){this.#I(1002,"flow control error"),this.#A(1002,"flow control error");return}}else{if(e.id.serverInitiated===this.#n)return;if(!e.id.canRecv(this.#n))throw new Error("received write-only stream");if(le(this.#u)){if(!(e.id.dir===oe.Bi?this.#D:this.#C).receiveUpTo(e.id.index+1n)){this.#I(1002,"stream limit exceeded"),this.#A(1002,"stream limit exceeded");return}this.#L(e.id.dir).record(e.id.index)}if(le(this.#u)){let h=e.id.dir===oe.Bi?this.#h.initialMaxStreamDataBidiRemote:this.#h.initialMaxStreamDataUni,p=e.id.dir===oe.Bi?this.#S.initialMaxStreamDataBidiLocal:0n;this.#w.set(t,{sendCredit:new Ie(p),sendOffset:0n,recvMax:h,recvOffset:0n,recvConsumed:0n})}if(!this.#ee(t,e.data.byteLength)){this.#I(1002,"flow control error"),this.#A(1002,"flow control error");return}let i=!1,s=!1,a=!1,o=()=>{!i||!s||a||(a=!0,this.#re(e.id.dir))},c=()=>{i=!0,o()},u=()=>{s=!0,o()},d=new ai(h=>{this.#te(t,h),this.#M(h)},(h,p)=>{this.#M(h),this.#y({type:"stop_sending",id:e.id,code:v.from(Hr(p))}),this.#c.delete(t),this.#k(t)},u);this.#c.set(t,d),n=d;let f=d.readable,l=h=>{this.#M(d.error(h))};if(e.id.dir===oe.Bi){let h=new WritableStream({start:p=>{this.#a.set(t,p)},write:async p=>{await this.#X(e.id,p)},abort:p=>{this.#t?.dropStream(t,p instanceof Error?p:new Error("stream aborted")),this.#y({type:"reset_stream",id:e.id,code:v.from(Hr(p)),finalSize:this.#U(t)}),this.#a.delete(t),this.#k(t)},close:async()=>{await this.#Y(e.id),this.#a.delete(t),this.#t?.forget(t),this.#k(t)}});this.#K(h,t,ci),this.#v.push({readable:f,writable:h},c,l)||l(new Error("incoming stream acceptor cancelled"))}else this.#g.push(f,c,l)||l(new Error("incoming stream acceptor cancelled"))}e.data.byteLength>0&&(n.push(e.data)||this.#M(e.data.byteLength)),e.fin&&(n.finish(),this.#c.delete(t),this.#k(t))}}#Ae(e){if(e.reliableSize!==void 0&&!this.#h.resetStreamAt)throw new Error("RESET_STREAM_AT received without advertising reset_stream_at");if(!e.id.canRecv(this.#n))throw new Error("Invalid stream ID direction");let t=e.id.value.value,n=this.#c.get(t),i=e.id.serverInitiated!==this.#n;if(!n){if(le(this.#u)&&i&&this.#L(e.id.dir).isClosed(e.id.index)||!i)return;if(le(this.#u)&&!(e.id.dir===oe.Bi?this.#D:this.#C).receiveUpTo(e.id.index+1n)){this.#I(1002,"stream limit exceeded"),this.#A(1002,"stream limit exceeded");return}}let s=this.#be(e);if(s===null){this.#I(1002,"flow control error"),this.#A(1002,"flow control error");return}if(!n){this.#M(s),le(this.#u)&&this.#L(e.id.dir).record(e.id.index),this.#re(e.id.dir);return}let a=n.reset(new Wr(La(e.code.value),"RESET_STREAM"));this.#M(s+BigInt(a)),this.#c.delete(t),this.#k(t)}#xe(e){let t=e.id.value.value,n=this.#a.get(t);if(!n)return;let i=new Wr(La(e.code.value),"STOP_SENDING");n.error(i),this.#a.delete(t),this.#t?.dropStream(t,i),this.#y({type:"reset_stream",id:e.id,code:e.code,finalSize:this.#U(t)}),this.#k(t)}#U(e){return this.#w.get(e)?.sendOffset??0n}#Se(){this.#y({type:"transport_parameters",params:this.#h})}#Ee(){return Ut(this.#u)?this.#_?this.#S.maxRecordSize:mr:BigInt(oi)}#ne(e,t){let n=pl(this.#u,this.#Ee(),e,t),i=BigInt(hl),s=n<i?n:i;if(s===0n)throw new Error("peer frame limit leaves no room for stream data");return s}#W(e){if(Ut(this.#u)){let t=this.#_?this.#S.maxRecordSize:mr;if(BigInt(e.byteLength)>t)throw new Error(`record exceeds peer max_record_size (${e.byteLength} > ${t})`)}}async#H(e,t){let n=this.#t;if(!n)throw this.#s??new Error("session not open");let i=Ps(t,this.#u);this.#W(i),await n.enqueueStream(e,i)}async#ke(e,t,n){let i=this.#w.get(t);if(!i)throw new Error(`missing flow state for stream ${t}`);for(let s=0;s<n.byteLength;){let a=BigInt(n.byteLength-s),o=this.#ne(e,i.sendOffset),c=Number(o<a?o:a),u=await this.#we(t,BigInt(c)),d=Number(u),f=n.subarray(s,s+d),l=i.sendOffset;try{await this.#H(t,{type:"stream",id:e,offset:l,data:f,fin:!1})}catch(h){if(d>0){let p=this.#w.get(t);p&&p.sendCredit.release(BigInt(d)),this.#E.release(BigInt(d))}throw h}i.sendOffset+=BigInt(d),s+=d}}async#X(e,t){let n=e.value.value;if(le(this.#u))await this.#ke(e,n,t);else{let i=Number(this.#ne(e,0n));for(let s=0;s<t.byteLength;s+=i){let a=Math.min(s+i,t.byteLength),o=t.subarray(s,a);await this.#H(n,{type:"stream",id:e,data:o,fin:!1})}}}async#Y(e){let t=e.value.value,n=le(this.#u)?this.#w.get(t)?.sendOffset:void 0;if(le(this.#u)&&n===void 0)throw new Error(`missing flow state for stream ${t}`);await this.#H(t,{type:"stream",id:e,offset:n,data:new Uint8Array,fin:!0})}#Te(e){if(this.#s)return;let t=Ps({type:"datagram",data:e},this.#u);this.#W(t),this.#t?.enqueueDatagram(t)}#y(e){if(this.#s)return;let t=Ps(e,this.#u);this.#W(t),this.#t?.enqueueControl(t)}#K(e,t,n){this.#t?.setSendOrder(t,n);let i=n;Object.defineProperty(e,"sendOrder",{configurable:!0,enumerable:!0,get:()=>i,set:s=>{i=s,this.#t?.setSendOrder(t,s)}})}async createBidirectionalStream(e){if(await this.ready,this.#s)throw this.#s;let t=e?.sendOrder??ci;await this.#P.claim(1n);let n=Q.create(this.#l++,oe.Bi,this.#n),i=n.value.value;le(this.#u)&&this.#w.set(i,{sendCredit:new Ie(this.#S.initialMaxStreamDataBidiRemote),sendOffset:0n,recvMax:this.#h.initialMaxStreamDataBidiLocal,recvOffset:0n,recvConsumed:0n});let s=new WritableStream({start:o=>{this.#a.set(i,o)},write:async o=>{await this.#X(n,o)},abort:o=>{this.#t?.dropStream(i,o instanceof Error?o:new Error("stream aborted")),this.#y({type:"reset_stream",id:n,code:v.from(Hr(o)),finalSize:this.#U(i)}),this.#a.delete(i),this.#k(i)},close:async()=>{await this.#Y(n),this.#a.delete(i),this.#t?.forget(i),this.#k(i)}});this.#K(s,i,t);let a=new ai(o=>{this.#te(i,o),this.#M(o)},(o,c)=>{this.#M(o),this.#y({type:"stop_sending",id:n,code:v.from(Hr(c))}),this.#c.delete(i),this.#k(i)});return this.#c.set(i,a),{readable:a.readable,writable:s}}async createUnidirectionalStream(e){if(await this.ready,this.#s)throw this.#s;let t=e?.sendOrder??ci;await this.#z.claim(1n);let n=Q.create(this.#d++,oe.Uni,this.#n),i=n.value.value;le(this.#u)&&this.#w.set(i,{sendCredit:new Ie(this.#S.initialMaxStreamDataUni),sendOffset:0n,recvMax:0n,recvOffset:0n,recvConsumed:0n});let s=this,a=new WritableStream({start:o=>{s.#a.set(i,o)},async write(o){await s.#X(n,o)},abort(o){s.#t?.dropStream(i,o instanceof Error?o:new Error("stream aborted")),s.#y({type:"reset_stream",id:n,code:v.from(Hr(o)),finalSize:s.#U(i)}),s.#a.delete(i),s.#k(i)},async close(){await s.#Y(n),s.#a.delete(i),s.#t?.forget(i),s.#k(i)}});return this.#K(a,i,t),a}#ie(){this.#R&&(clearInterval(this.#R),this.#R=void 0),this.#v.close(this.#o),this.#g.close(this.#o),this.datagrams.close(this.#o);for(let t of this.#a.values())try{t.error(this.#s)}catch{}let e=this.#s??this.#o??new Error("Connection closed");for(let t of this.#c.values())try{t.error(e)}catch{}this.#a.clear(),this.#c.clear();for(let t of this.#w.values())t.sendCredit.close(e);this.#w.clear(),this.#E.close(e),this.#P.close(e),this.#z.close(e),this.#D.close(e),this.#C.close(e),this.#t?.close(e)}#se(e,t){this.#s||(this.#s=this.#o??new Error(`Connection closed: ${e} ${t}`),this.#m(this.#s),this.#b({closeCode:e,reason:t}),this.#ie())}#A(e,t,n){this.#s||(n!==void 0&&(this.#o??=n instanceof Error?n:new Error(String(n))),this.#s=this.#o??new Error(`Connection closed: ${e} ${t}`),this.#m(this.#s),this.#x(new si(this.#s.message,{cause:this.#s})),this.#ie())}#B(){try{this.#e?.close()}catch{}}#Me(e,t){this.#y({type:"application_close",code:v.from(e),reason:t}),setTimeout(()=>{this.#B()},100)}#I(e,t){this.#y({type:"connection_close",code:v.from(e),reason:t}),setTimeout(()=>{this.#B()},100)}close(e){if(this.#s)return;let t=e?.closeCode??0,n=e?.reason??"";this.#Me(t,n),this.#se(t,n)}setSendBufferSize(e){this.#r=Math.max(1,Math.floor(e)),this.#e?.setHighWaterMark?.(this.#r)}get congestionControl(){return"default"}};var di=ui;function Os(r){return r instanceof di?"websocket":"webtransport"}async function C(r,e){let t=new Uint8Array,n=new me(new WritableStream({write(i){let s=t.byteLength+i.byteLength;if(s>t.buffer.byteLength){let a=Math.max(s,t.buffer.byteLength*2),o=new ArrayBuffer(a),c=new Uint8Array(o,0,s);c.set(t),c.set(i,t.byteLength),t=c}else t=new Uint8Array(t.buffer,0,s),t.set(i,s-i.byteLength)}}),r.version);try{await e(n)}finally{n.close()}if(await n.closed,t.byteLength>65535)throw new Error(`Message too large: ${t.byteLength} bytes (max 65535)`);await r.u16(t.byteLength),await r.write(t)}async function O(r,e){let t=await r.u16(),n=await r.read(t),i=new ae(void 0,n,r.version),s=await e(i);if(!await i.done())throw new Error("Message decoding consumed too few bytes");return s}var li=class r{static id=16;newSessionUri;timeout;constructor({newSessionUri:e,timeout:t=0n}){this.newSessionUri=e,this.timeout=t}async#e(e,t){await e.string(this.newSessionUri),t!==m.DRAFT_14&&t!==m.DRAFT_15&&t!==m.DRAFT_16&&await e.u62(this.timeout)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=await e.string(),i=t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16?0n:await e.u62();return new r({newSessionUri:n,timeout:i})}};var bl=3,Pw=0x08n,xl=0x10n,zw=0x06n,vl=64;function Al(r){switch(r){case m.DRAFT_14:case m.DRAFT_15:case m.DRAFT_16:case m.DRAFT_17:return!1;default:return!0}}function Sl(r){switch(r){case m.DRAFT_14:case m.DRAFT_15:return!1;default:return!0}}async function Rw(r,e,t,n){let i=Sl(n)?e-t:e;await r.u62(i)}async function Fw(r,e,t,n){let i=Math.round(e.value*t/e.scale);await Rw(r,xl,0n,n),await r.u62(BigInt(i))}async function Dw(r,e,t){if(r===void 0)return new Uint8Array;let n=[],i=new me(new WritableStream({write(c){n.push(new Uint8Array(c))}}),t);await Fw(i,r,e,t),i.close(),await i.closed;let s=n.reduce((c,u)=>c+u.byteLength,0),a=new Uint8Array(s),o=0;for(let c of n)a.set(c,o),o+=c.byteLength;return a}async function Cw(r,e,t){let n,i,s=0n,a=!0;for(;!await r.done();){let o=await r.u62(),c=!Sl(t)||a?o:s+o;if(a=!1,s=c,c%2n===0n){let u=await r.u62();c===xl||c===zw?n=u:c===Pw&&(i=u)}else{let u=await r.u53();await r.read(u)}}if(n!==void 0)return new xe(Number(n),i!==void 0?ne(Number(i)):e)}var Xr=class r{flags;trackAlias;groupId;subGroupId;publisherPriority;constructor({trackAlias:e,groupId:t,subGroupId:n,publisherPriority:i,flags:s}){this.flags=s,this.trackAlias=e,this.groupId=t,this.subGroupId=n,this.publisherPriority=i}async encode(e,t){if(!this.flags.hasSubgroup&&this.subGroupId!==0)throw new Error(`Subgroup ID must be 0 if hasSubgroup is false: ${this.subGroupId}`);let i=this.flags.hasPriority?16:48;this.flags.hasExtensions&&(i|=1),this.flags.hasSubgroupObject&&(i|=2),this.flags.hasSubgroup&&(i|=4),this.flags.hasEnd&&(i|=8),Al(t)&&(i|=vl),await e.u53(i),await e.u62(this.trackAlias),await e.u53(this.groupId),this.flags.hasSubgroup&&await e.u53(this.subGroupId),this.flags.hasPriority&&await e.u8(this.publisherPriority)}static async decode(e,t){let n=await e.u53(),i=Al(t)?n&~vl:n,s,a;if(i>=16&&i<=31)s=!0,a=i;else if(i>=48&&i<=63)s=!1,a=i-32;else throw new Error(`Unsupported group type: ${i}`);let o={hasExtensions:(a&1)!==0,hasSubgroupObject:(a&2)!==0,hasSubgroup:(a&4)!==0,hasEnd:(a&8)!==0,hasPriority:s},c=await e.u62(),u=await e.u53(),d=o.hasSubgroup?await e.u53():0,f=s?await e.u8():128;return new r({trackAlias:c,groupId:u,subGroupId:d,publisherPriority:f,flags:o})}},Yr=class r{payload;timestamp;constructor({payload:e,timestamp:t}={}){this.payload=e,this.timestamp=t}async encode(e,t,n,i=e.version){if(await e.u53(0),t.hasExtensions){let s=await Dw(this.timestamp,n,i);await e.u53(s.byteLength),await e.write(s)}this.payload!==void 0?(await e.u53(this.payload.byteLength),this.payload.byteLength===0?await e.u53(0):await e.write(this.payload)):(await e.u53(0),await e.u53(bl))}static async decode(e,t,n,i=e.version){let s=await e.u53();if(s!==0)throw new Error(`object ID delta is not supported: ${s}`);let a;if(t.hasExtensions){let u=await e.u53(),d=await e.read(u);n!==void 0&&(a=await Cw(new ae(void 0,d,i),n,i))}let o=await e.u53();if(o>0){let u=await e.read(o);return new r({payload:u,timestamp:a})}let c=await e.u53();if(t.hasEnd){if(c===0)return new r({payload:new Uint8Array(0),timestamp:a})}else if(c===0||c===bl)return new r;throw new Error(`Unsupported object status: ${c}`)}};var ja=0x08n,El=0x22n;async function Vs(r,e,t){if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16)return;let n=0n;e.timescale!==void 0&&(await r.u62(ja),await r.u62(BigInt(e.timescale)),n=ja),e.groupOrder!==void 0&&(await r.u62(El-n),await r.u62(BigInt(e.groupOrder)))}async function Kr(r,e){if(e===m.DRAFT_14||e===m.DRAFT_15)return{};let t={},n=0n,i=0;for(;!await r.done();){let s=await r.u62(),a=i===0?s:n+s;if(n=a,i++,a%2n===0n){let o=await r.u62();if(a===ja&&o>0n)t.timescale=ne(Number(o));else if(a===El){if(o<1n||o>2n)throw new Error(`unknown group order: ${o}`);t.groupOrder=Number(o)}}else{let o=await r.u53();await r.read(o)}}return t}var fi=class r{static id=29;requestId;trackNamespace;trackName;trackAlias;groupOrder;contentExists;largest;forward;constructor({requestId:e,trackNamespace:t,trackName:n,trackAlias:i,groupOrder:s,contentExists:a,largest:o,forward:c}){this.requestId=e,this.trackNamespace=t,this.trackName=n,this.trackAlias=i,this.groupOrder=s,this.contentExists=a,this.largest=o,this.forward=c}async#e(e,t){if(await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await be(e,this.trackNamespace),await e.string(this.trackName),await e.u62(this.trackAlias),t===m.DRAFT_14){if(await e.u8(this.groupOrder),await e.bool(this.contentExists),this.contentExists!==!!this.largest)throw new Error("contentExists and largest must both be true or false");this.largest&&(await e.u62(this.largest.groupId),await e.u62(this.largest.objectId)),await e.bool(this.forward),await e.u53(0)}else{if(this.contentExists!==!!this.largest)throw new Error("contentExists and largest must both be true or false");let n=new D;t===m.DRAFT_15&&(n.groupOrder=this.groupOrder),n.forward=this.forward,this.largest&&(n.largest=this.largest),await n.encode(e,t),await Vs(e,{groupOrder:this.groupOrder},t)}}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=await e.u62();t===m.DRAFT_17&&await e.u62();let i=await se(e),s=await e.string(),a=await e.u62();if(t===m.DRAFT_14){let l=await e.u8(),h=await e.bool(),p=h?{groupId:await e.u62(),objectId:await e.u62()}:void 0,_=await e.bool();return await D.decode(e,t),new r({requestId:n,trackNamespace:i,trackName:s,trackAlias:a,groupOrder:l,contentExists:h,largest:p,forward:_})}let o=await D.decode(e,t),u=(await Kr(e,t)).groupOrder??o.groupOrder??2,d=o.forward??!0,f=o.largest;return new r({requestId:n,trackNamespace:i,trackName:s,trackAlias:a,groupOrder:u,contentExists:!!f,largest:f,forward:d})}};var hi=class r{static id=31;requestId;errorCode;reasonPhrase;constructor({requestId:e,errorCode:t,reasonPhrase:n}){this.requestId=e,this.errorCode=t,this.reasonPhrase=n}async#e(e){await e.u62(this.requestId),await e.u62(BigInt(this.errorCode)),await e.string(this.reasonPhrase)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62(),n=Number(await e.u62()),i=await e.string();return new r({requestId:t,errorCode:n,reasonPhrase:i})}},pi=class r{static id=11;requestId;statusCode;reasonPhrase;constructor({requestId:e,statusCode:t,reasonPhrase:n}){this.requestId=e,this.statusCode=t,this.reasonPhrase=n}async#e(e,t){if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16){if(this.requestId===void 0)throw new Error("requestId required for draft14-16");await e.u62(this.requestId)}await e.u62(BigInt(this.statusCode)),await e.u62(BigInt(0)),await e.string(this.reasonPhrase)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16?await e.u62():void 0,i=Number(await e.u62());await e.u62();let s=await e.string();return new r({requestId:n,statusCode:i,reasonPhrase:s})}};var Ye=class r{static id=6;requestId;trackNamespace;cluster;constructor({requestId:e,trackNamespace:t,cluster:n}){this.requestId=e,this.trackNamespace=t,this.cluster=n}async#e(e,t){await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await be(e,this.trackNamespace),await(this.cluster?ni(this.cluster):new D).encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t,n=!1){return O(e,i=>r.#t(i,t,n))}static async#t(e,t,n){let i=await e.u62();t===m.DRAFT_17&&await e.u62();let s=await se(e);if(n){let a=await ii(e,t);return new r({requestId:i,trackNamespace:s,cluster:a})}return await D.decode(e,t),new r({requestId:i,trackNamespace:s})}},_r=class r{static id=7;requestId;constructor({requestId:e}){this.requestId=e}async#e(e){await e.u62(this.requestId)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62();return new r({requestId:t})}},mi=class r{static id=8;requestId;errorCode;reasonPhrase;constructor({requestId:e,errorCode:t,reasonPhrase:n}){this.requestId=e,this.errorCode=t,this.reasonPhrase=n}async#e(e){await e.u62(this.requestId),await e.u62(BigInt(this.errorCode)),await e.string(this.reasonPhrase)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62(),n=Number(await e.u62()),i=await e.string();return new r({requestId:t,errorCode:n,reasonPhrase:i})}};var $t=class r{static id=9;trackNamespace;requestId;constructor({trackNamespace:e="",requestId:t=0n}={}){this.trackNamespace=e,this.requestId=t}async#e(e,t){if(t!==m.DRAFT_14&&t!==m.DRAFT_15&&t!==m.DRAFT_16)throw new Error("PublishNamespaceDone removed in draft-17+");t===m.DRAFT_16?await e.u62(this.requestId):await be(e,this.trackNamespace)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){if(t!==m.DRAFT_14&&t!==m.DRAFT_15&&t!==m.DRAFT_16)throw new Error("PublishNamespaceDone removed in draft-17+");if(t===m.DRAFT_16){let i=await e.u62();return new r({requestId:i})}let n=await se(e);return new r({trackNamespace:n})}};function kl(r){return 255-r}function Tl(r){return 255-r}var Pe=class r{static id=7;requestId;parameters;constructor({requestId:e,parameters:t=new D}){this.requestId=e,this.parameters=t}async#e(e,t){if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16){if(this.requestId===void 0)throw new Error("requestId required for draft14-16");await e.u62(this.requestId)}await this.parameters.encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async#t(e,t){let n=t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16?await e.u62():void 0,i=await D.decode(e,t);return await Kr(e,t),new r({requestId:n,parameters:i})}static async decode(e,t){return O(e,n=>r.#t(n,t))}},ve=class r{static id=5;requestId;errorCode;reasonPhrase;retryInterval;constructor({requestId:e,errorCode:t,reasonPhrase:n,retryInterval:i=0n}){this.requestId=e,this.errorCode=t,this.reasonPhrase=n,this.retryInterval=i}async#e(e,t){if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16){if(this.requestId===void 0)throw new Error("requestId required for draft14-16");await e.u62(this.requestId)}await e.u62(BigInt(this.errorCode)),t!==m.DRAFT_14&&t!==m.DRAFT_15&&await e.u62(this.retryInterval),await e.string(this.reasonPhrase)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async#t(e,t){let n=t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16?await e.u62():void 0,i=Number(await e.u62()),s=t===m.DRAFT_14||t===m.DRAFT_15?0n:await e.u62(),a=await e.string();return new r({requestId:n,errorCode:i,reasonPhrase:a,retryInterval:s})}static async decode(e,t){return O(e,n=>r.#t(n,t))}};var Nt=2,qt=class r{static id=3;requestId;trackNamespace;trackName;subscriberPriority;constructor({requestId:e,trackNamespace:t,trackName:n,subscriberPriority:i}){this.requestId=e,this.trackNamespace=t,this.trackName=n,this.subscriberPriority=i}async#e(e,t){if(await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await be(e,this.trackNamespace),await e.string(this.trackName),t===m.DRAFT_14)await e.u8(this.subscriberPriority),await e.u8(Nt),await e.bool(!0),await e.u53(2),await e.u53(0);else{let n=new D;n.subscriberPriority=this.subscriberPriority,n.groupOrder=Nt,n.forward=!0,n.subscriptionFilter=2,await n.encode(e,t)}}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=await e.u62();t===m.DRAFT_17&&await e.u62();let i=await se(e),s=await e.string();if(t===m.DRAFT_14){let f=await e.u8(),l=await e.u8();if(l>2)throw new Error(`unknown group order: ${l}`);l===0&&(l=Nt);let h=await e.bool();if(!h)throw new Error(`unsupported forward value: ${h}`);let p=await e.u53();if(p!==1&&p!==2)throw new Error(`unsupported filter type: ${p}`);return await D.decode(e,t),new r({requestId:n,trackNamespace:i,trackName:s,subscriberPriority:f})}let a=await D.decode(e,t),o=a.subscriberPriority??128,c=a.groupOrder??Nt;if(c>2)throw new Error(`unknown group order: ${c}`);c===0&&(c=Nt);let u=a.forward??!0;if(!u)throw new Error(`unsupported forward value: ${u}`);let d=a.subscriptionFilter??2;if(d!==1&&d!==2)throw new Error(`unsupported filter type: ${d}`);return new r({requestId:n,trackNamespace:i,trackName:s,subscriberPriority:o})}},Zt=class r{static id=4;requestId;trackAlias;timescale;constructor({requestId:e,trackAlias:t,timescale:n}){this.requestId=e,this.trackAlias=t,this.timescale=n}async#e(e,t){if(t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16){if(this.requestId===void 0)throw new Error("requestId required for draft14-16");await e.u62(this.requestId)}if(await e.u62(this.trackAlias),t===m.DRAFT_14)await e.u62(0n),await e.u8(Nt),await e.bool(!1),await e.u53(0);else{let n=new D;t===m.DRAFT_15&&(n.groupOrder=Nt),await n.encode(e,t),await Vs(e,{timescale:this.timescale,groupOrder:Nt},t)}}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=t===m.DRAFT_14||t===m.DRAFT_15||t===m.DRAFT_16?await e.u62():void 0,i=await e.u62(),s;if(t===m.DRAFT_14){let a=await e.u62();if(a!==BigInt(0))throw new Error(`unsupported expires: ${a}`);await e.u8(),await e.bool()&&(await e.u62(),await e.u62()),await D.decode(e,t)}else await D.decode(e,t),s=(await Kr(e,t)).timescale;return new r({requestId:n,trackAlias:i,timescale:s})}},wr=class r{static id=5;requestId;errorCode;reasonPhrase;constructor({requestId:e,errorCode:t,reasonPhrase:n}){this.requestId=e,this.errorCode=t,this.reasonPhrase=n}async#e(e){await e.u62(this.requestId),await e.u62(BigInt(this.errorCode)),await e.string(this.reasonPhrase)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62(),n=Number(await e.u62()),i=await e.string();return new r({requestId:t,errorCode:n,reasonPhrase:i})}},Ls=class r{static id=2;requestId;constructor({requestId:e}){this.requestId=e}async#e(e,t){t===m.DRAFT_14?(await e.u62(this.requestId),await e.u62(0n),await e.u62(0n),await e.u62(0n),await e.u62(0n),await e.u8(128),await e.bool(!0),await e.u53(0)):t===m.DRAFT_15||t===m.DRAFT_16?(await e.u62(this.requestId),await e.u62(0n),await new D().encode(e,t)):(await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await new D().encode(e,t))}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){if(t===m.DRAFT_14){let n=await e.u62();return await e.u62(),await e.u62(),await e.u62(),await e.u62(),await e.u8(),await e.bool(),await D.decode(e,t),new r({requestId:n})}else if(t===m.DRAFT_15||t===m.DRAFT_16){let n=await e.u62();return await e.u62(),await D.decode(e,t),new r({requestId:n})}else{let n=await e.u62();return t===m.DRAFT_17&&await e.u62(),await D.decode(e,t),new r({requestId:n})}}},_i=class r{static id=10;requestId;constructor({requestId:e}){this.requestId=e}async#e(e){await e.u62(this.requestId)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62();return new r({requestId:t})}};function Us(r){switch(r){case m.DRAFT_14:case m.DRAFT_15:case m.DRAFT_16:case m.DRAFT_17:return!0;default:return!1}}var vt=class r{static id=80;namespace;requestId;constructor({namespace:e,requestId:t}){this.namespace=e,this.requestId=t}async#e(e,t){if(Us(t))throw new Error(`SUBSCRIBE_NAMESPACE (0x50) is draft-18+ only, not ${t}`);await e.u62(this.requestId),await be(e,this.namespace),await new D().encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){if(Us(t))throw new Error(`SUBSCRIBE_NAMESPACE (0x50) is draft-18+ only, not ${t}`);let n=await e.u62(),i=await se(e);return await D.decode(e,t),new r({namespace:i,requestId:n})}},Gt=class r{static id=17;namespace;requestId;subscribeOptions;constructor({namespace:e,requestId:t,subscribeOptions:n=1}){this.namespace=e,this.requestId=t,this.subscribeOptions=n}async#e(e,t){if(!Us(t))throw new Error(`legacy SUBSCRIBE_NAMESPACE (0x11) is draft-14..17 only, not ${t}`);await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await be(e,this.namespace),(t===m.DRAFT_16||t===m.DRAFT_17)&&await e.u53(this.subscribeOptions),await new D().encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){if(!Us(t))throw new Error(`legacy SUBSCRIBE_NAMESPACE (0x11) is draft-14..17 only, not ${t}`);let n=await e.u62();t===m.DRAFT_17&&await e.u62();let i=await se(e),s=1;return(t===m.DRAFT_16||t===m.DRAFT_17)&&(s=await e.u53()),await D.decode(e,t),new r({namespace:i,requestId:n,subscribeOptions:s})}};var gr=class r{static id=18;requestId;constructor({requestId:e}){this.requestId=e}async#e(e){await e.u62(this.requestId)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62();return new r({requestId:t})}};var wi=class r{static id=20;requestId;constructor({requestId:e}){this.requestId=e}async#e(e){await e.u62(this.requestId)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await e.u62();return new r({requestId:t})}},jt=class r{static id=8;suffix;cluster;constructor({suffix:e,cluster:t}){this.suffix=e,this.cluster=t}async#e(e,t){await be(e,this.suffix),this.cluster&&await ni(this.cluster).encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t,n=!1){return O(e,i=>r.#t(i,t,n))}static async#t(e,t,n){let i=await se(e);return n?new r({suffix:i,cluster:await ii(e,t)}):new r({suffix:i})}},Wt=class r{static id=14;suffix;constructor({suffix:e}){this.suffix=e}async#e(e){await be(e,this.suffix)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await se(e);return new r({suffix:t})}},gi=class r{static id=15;suffix;trackName;constructor({suffix:e,trackName:t}){this.suffix=e,this.trackName=t}async#e(e){await be(e,this.suffix),await e.string(this.trackName)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await se(e),n=await e.string();return new r({suffix:t,trackName:n})}};var Ow=2,yi=class r{static id=13;requestId;trackNamespace;trackName;constructor({requestId:e,trackNamespace:t,trackName:n}){this.requestId=e,this.trackNamespace=t,this.trackName=n}async#e(e,t){await e.u62(this.requestId),t===m.DRAFT_17&&await e.u62(0n),await be(e,this.trackNamespace),await e.string(this.trackName),t===m.DRAFT_14?(await e.u8(0),await e.u8(Ow),await e.bool(!1),await e.u53(2),await e.u53(0)):await new D().encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async decode(e,t){return O(e,n=>r.#t(n,t))}static async#t(e,t){let n=await e.u62();t===m.DRAFT_17&&await e.u62();let i=await se(e),s=await e.string();return t===m.DRAFT_14?(await e.u8(),await e.u8(),await e.bool(),await e.u53(),await D.decode(e,t)):await D.decode(e,t),new r({requestId:n,trackNamespace:i,trackName:s})}},Qr=class r{static id=14;trackNamespace;trackName;statusCode;lastGroupId;lastObjectId;constructor({trackNamespace:e,trackName:t,statusCode:n,lastGroupId:i,lastObjectId:s}){this.trackNamespace=e,this.trackName=t,this.statusCode=n,this.lastGroupId=i,this.lastObjectId=s}async#e(e){await be(e,this.trackNamespace),await e.string(this.trackName),await e.u62(BigInt(this.statusCode)),await e.u62(this.lastGroupId),await e.u62(this.lastObjectId)}async encode(e,t){return C(e,this.#e.bind(this))}static async decode(e,t){return O(e,r.#t)}static async#t(e){let t=await se(e),n=await e.string(),i=Number(await e.u62()),s=await e.u62(),a=await e.u62();return new r({trackNamespace:t,trackName:n,statusCode:i,lastGroupId:s,lastObjectId:a})}static STATUS_IN_PROGRESS=0;static STATUS_NOT_FOUND=1;static STATUS_NOT_AUTHORIZED=2;static STATUS_ENDED=3};var Ml=100,Il=5e3,Pl=5e3;function zl(r){return new Promise(e=>setTimeout(e,r*(.5+Math.random()/2)))}var Bs=class{#e;#t;#r;#n;#i=new A(new Map);constructor({quic:e,session:t,requiresSolicitation:n,cluster:i}){this.#e=e,this.#t=t,this.#r=n,this.#n=Ca(i)}publish(e,t){this.#i.mutate(n=>{if(!n)throw new Error("closed");n.set(e,t)}),t.closed.then(()=>{this.#i.mutate(n=>{n?.get(e)===t&&n.delete(e)})})}async runSubscribe(e,t){let n=this.#t.version,i=e.trackNamespace,s=this.#i.peek()?.get(i);if(!s){n===m.DRAFT_14?(await t.writer.u53(wr.id),await new wr({requestId:e.requestId,errorCode:404,reasonPhrase:"Broadcast not found"}).encode(t.writer,n)):(await t.writer.u53(ve.id),await new ve({requestId:n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0,errorCode:404,reasonPhrase:"Broadcast not found"}).encode(t.writer,n)),t.close();return}let a=s.subscribe(e.trackName,{priority:kl(e.subscriberPriority)});try{let o=(await a.info()).timescale;await t.writer.u53(Zt.id),await new Zt({requestId:n===m.DRAFT_14||n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0,trackAlias:e.requestId,timescale:o}).encode(t.writer,n),console.debug(`publish ok: broadcast=${i} track=${a.name}`);let u=!1,d,f=new Promise(h=>{d=h});t.reader.closed.then(()=>{u||d()},()=>d());let l=(async()=>{for(;;){let h=await a.recvGroup();if(!h)return;this.#s({requestId:e.requestId,group:h,timescale:o,unsubscribed:f})}})();if(await Promise.race([l,t.reader.closed]),console.debug(`publish done: broadcast=${i} track=${a.name}`),n===m.DRAFT_14||n===m.DRAFT_15||n===m.DRAFT_16)try{await t.writer.u53(pi.id),await new pi({requestId:e.requestId,statusCode:200,reasonPhrase:"OK"}).encode(t.writer,n)}catch{}u=!0,t.close()}catch(o){let c=L(o);console.warn(`publish error: broadcast=${i} track=${a.name} error=${ee(c)}`),t.abort(c)}finally{a.close()}}async#s(e){let{requestId:t,group:n,timescale:i,unsubscribed:s}=e;try{let a=await me.tryOpen(this.#e,{cancel:s,version:this.#t.version,waitUntilAvailable:!1});if(!a){n.close(new Error("no stream slot"));return}let o=new Xr({trackAlias:t,groupId:n.sequence,subGroupId:0,publisherPriority:0,flags:{hasExtensions:!0,hasSubgroup:!1,hasSubgroupObject:!1,hasEnd:!0,hasPriority:!0}});await o.encode(a,this.#t.version);try{for(;;){let c=await Promise.race([n.readFrame(),a.closed]);if(!c)break;await new Yr({payload:c.payload,timestamp:c.timestamp}).encode(a,o.flags,i,this.#t.version)}a.close()}catch(c){a.reset(L(c))}}finally{n.close()}}async runSubscribeNamespace(e,t){let n=this.#t.version,i=e.namespace,s=n===m.DRAFT_14||n===m.DRAFT_15,a=new Map;try{if(n===m.DRAFT_14?(await t.writer.u53(gr.id),await new gr({requestId:e.requestId}).encode(t.writer,n)):(await t.writer.u53(Pe.id),await new Pe({requestId:n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0}).encode(t.writer,n)),!this.#r){await t.reader.closed,t.close();return}let o=async l=>s?await this.#c(De(i,l),a,f):(await t.writer.u53(jt.id),await new jt({suffix:l,cluster:this.#n}).encode(t.writer,n),!0),c=async l=>{s?await this.#d(De(i,l),a):(await t.writer.u53(Wt.id),await new Wt({suffix:l}).encode(t.writer,n))},u=new Set,d=0,f=new Map;for(;;){let l,h=new Promise(x=>{l=this.#i.changed(x)}),p=this.#i.peek();if(!p){l();break}let _=new Set;for(let x of p.keys()){let P=tt(i,x);P!==null&&_.add(P)}let w=new Set([..._].map(x=>De(i,x)));for(let x of[...f.keys()])w.has(x)||f.delete(x);let y=new Set(u);for(let x of _.difference(u))this.#o(De(i,x),f)&&await o(x)&&y.add(x);for(let x of u.difference(_))await c(x),y.delete(x);u=y,d=[..._.difference(u)].some(x=>this.#a(De(i,x),f))?Math.min(d?d*2:Ml,Il):0;let g=await(d?Promise.race([h,t.reader.closed,zl(d).then(()=>p)]):Promise.race([h,t.reader.closed]));if(l(),!g)break}t.close()}catch(o){let c=L(o);console.debug(`subscribe_namespace stream error: ${ee(c)}`),t.abort(c)}finally{for(let o of[...a.keys()])await this.#d(o,a)}}async runPublishNamespaces(){if(this.#r)return;let e=new Map;try{let t=new Set,n=0,i=new Map;for(;;){let s,a=new Promise(f=>{s=this.#i.changed(f)}),o=this.#i.peek();if(!o){s();break}let c=new Set(o.keys());for(let f of[...i.keys()])c.has(f)||i.delete(f);for(let f of c.difference(t))this.#o(f,i)&&await this.#c(f,e,i);for(let f of t.difference(c))await this.#d(f,e);t=new Set(e.keys()),n=[...c.difference(t)].some(f=>this.#a(f,i))?Math.min(n?n*2:Ml,Il):0;let d=await(n?Promise.race([a,zl(n).then(()=>o)]):a);if(s(),!d)break}}catch(t){console.warn(`publish_namespace loop failed: ${ee(L(t))}`)}finally{for(let t of[...e.keys()])await this.#d(t,e)}}#o(e,t){let n=t.get(e);return n===void 0?!0:n!=="never"&&Date.now()>=n}#a(e,t){return t.get(e)!=="never"}async#c(e,t,n){let i=await this.#t.nextRequestId();if(i===void 0)return!1;let s;try{s=await this.#t.openBi();let a=s;return await Rt((async()=>{await a.writer.u53(Ye.id),await new Ye({requestId:i,trackNamespace:e,cluster:this.#n}).encode(a.writer,this.#t.version);let c=await a.reader.u53();if(c===ve.id){let u=await ve.decode(a.reader,this.#t.version);throw this.#t.version===m.DRAFT_14||this.#t.version===m.DRAFT_15||n.set(e,u.retryInterval===0n?"never":Date.now()+Number(u.retryInterval)),new Error(`PublishNamespace rejected: ${u.errorCode} ${u.reasonPhrase}`)}if(c!==Pe.id)throw new Error(`PublishNamespace rejected: typeId=0x${c.toString(16)}`);this.#t.version===m.DRAFT_14?await _r.decode(a.reader,this.#t.version):await Pe.decode(a.reader,this.#t.version)})(),Pl,`advertisement timed out after ${Pl}ms waiting for the peer's answer`),t.set(e,{path:e,requestId:i,stream:s}),!0}catch(a){let o=L(a);return console.warn(`announce failed: broadcast=${e} error=${ee(o)}`),s?.abort(o),!1}}async#d(e,t){let n=t.get(e);if(!n)return;t.delete(e);let i=this.#t.version;if(i===m.DRAFT_14||i===m.DRAFT_15||i===m.DRAFT_16)try{await n.stream.writer.u53($t.id),await new $t({trackNamespace:n.path,requestId:n.requestId}).encode(n.stream.writer,i)}catch{}n.stream.close()}async runTrackStatusRequest(e,t){let n=this.#t.version;n===m.DRAFT_14?(await t.writer.u53(Qr.id),await new Qr({trackNamespace:e.trackNamespace,trackName:e.trackName,statusCode:Qr.STATUS_NOT_FOUND,lastGroupId:0n,lastObjectId:0n}).encode(t.writer,n)):(await t.writer.u53(Pe.id),await new Pe({requestId:n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0}).encode(t.writer,n)),t.close()}close(){this.#i.update(e=>{for(let t of e?.values()??[])t.close()})}};var Jr=class{#e=new Map;get(e){let t=this.#e.get(e);if(t&&t.closed.peek()===void 0)return t.clone()}insert(e,t){return this.#e.set(e,t),t.closed.then(()=>{this.#e.get(e)===t&&this.#e.delete(e)}),t}evict(e){this.#e.delete(e)}};function Vw(r,e){return r.broadcast===e.broadcast&&r.name===e.name}var bi=class extends Error{constructor(e){super(`track alias retired: ${e}`),this.name="RetiredTrackAlias"}},Ha=class extends Error{constructor(e){super(`track alias shared by another subscription: ${e}`),this.name="SharedTrackAlias"}},vi=class extends Error{constructor(e){super(`duplicate track alias: ${e}`),this.name="DuplicateTrackAlias"}},$s=class{#e=new Map;#t=new Map;#r=[];#n=new Set;async get(e){let t=this.#e.get(e);if(t!==void 0)return t.value;if(this.#n.has(e))throw new bi(e);let{promise:n,resolve:i}=Promise.withResolvers(),s=this.#t.get(e);s||(s=new Set,this.#t.set(e,s)),s.add(i);let a,o=new Promise((c,u)=>{a=setTimeout(()=>u(new Error(`unknown track alias: ${e}`)),1e3)});try{return await Promise.race([n,o])}finally{clearTimeout(a),s.delete(i),this.#t.get(e)===s&&s.size===0&&this.#t.delete(e)}}set(e,t,n){let i=this.#e.get(e);if(i!==void 0){if(i.value===t)return;throw Vw(i.track,n)?new Ha(e):new vi(e)}this.#i(e),this.#e.set(e,{value:t,track:n});let s=this.#t.get(e);this.#t.delete(e);for(let a of s??[])a(t)}retire(e,t){if(this.#e.get(e)?.value!==t)return!1;if(this.#e.delete(e),this.#n.has(e))return!0;for(this.#n.add(e),this.#r.push(e);this.#r.length>64;){let n=this.#r.shift();n!==void 0&&this.#n.delete(n)}return!0}#i(e){if(!this.#n.delete(e))return;let t=this.#r.indexOf(e);t!==-1&&this.#r.splice(t,1)}};var Rl=1e4,Ns=class{#e;#t;#r=new $s;#n=new Map;#i=new Jr;#s=new Set;#o=new Map;#a=new Set;constructor({session:e,cluster:t}){this.#e=e,this.#t=t}#c(e){return e!==void 0&&this.#t!==void 0&&Oa(e,this.#t.self)}announced(e=Me()){let t=new Pt(e);for(let n of this.#o.keys()){let i=tt(e,n);i!==null&&t.append({path:i,active:!0})}return this.#a.add(t),this.#u(t,e).finally(()=>{this.#a.delete(t),t.close()}),t.consume()}#d(e){let t=this.#o.get(e)??0;if(this.#o.set(e,t+1),!(t>0)){console.debug(`announced: broadcast=${e} active=true`);for(let n of this.#a){let i=tt(n.prefix,e);i!==null&&n.append({path:i,active:!0})}}}#l(e){let t=this.#o.get(e);if(t!==void 0){if(t>1){this.#o.set(e,t-1);return}this.#o.delete(e),this.#i.evict(e),console.debug(`announced: broadcast=${e} active=false`);for(let n of this.#a){let i=tt(n.prefix,e);if(i!==null)try{n.append({path:i,active:!1})}catch{}}}}async#u(e,t){let n=this.#e.version,i=new Set,s=!1,a=await this.#e.nextRequestId();if(a!==void 0)try{let o=n===m.DRAFT_16&&this.#e.openNativeBi?await this.#e.openNativeBi():await this.#e.openBi();try{n===m.DRAFT_14||n===m.DRAFT_15||n===m.DRAFT_16||n===m.DRAFT_17?(await o.writer.u53(Gt.id),await new Gt({namespace:t,requestId:a}).encode(o.writer,n)):(await o.writer.u53(vt.id),await new vt({namespace:t,requestId:a}).encode(o.writer,n)),console.debug(`subscribe_namespace written: requestId=${a}`);let c=await o.reader.u53();if(c===Pe.id)await Pe.decode(o.reader,n);else if(c===gr.id){let d=await o.reader.u16();await o.reader.read(d)}else throw new Error(`SubscribeNamespace rejected: typeId=0x${c.toString(16)}`);let u=(async()=>{for(;!await o.reader.done();){let f=await o.reader.u53();if(f===jt.id){let l=await jt.decode(o.reader,n,Gr(this.#t));if(s)break;let h=De(t,l.suffix);if(this.#c(l.cluster)){console.debug(`dropping reflected namespace: broadcast=${h}`),i.delete(h)&&this.#l(h);continue}i.has(h)||(i.add(h),this.#d(h))}else if(f===Wt.id){let l=await Wt.decode(o.reader,n);if(s)break;let h=De(t,l.suffix);i.delete(h)&&this.#l(h)}else if(f===gi.id&&n===m.DRAFT_17){let l=await gi.decode(o.reader,n);console.debug(`publish_blocked: suffix=${l.suffix} track=${l.trackName}`)}else throw new Error(`unexpected message on subscribe_namespace stream: 0x${f.toString(16)}`)}})();if(u.catch(d=>{d instanceof Ne&&this.#e.close()}),await Promise.race([u,e.closed]),n===m.DRAFT_14||n===m.DRAFT_15)try{await o.writer.u53(wi.id),await new wi({requestId:a}).encode(o.writer,n)}catch{}o.close()}catch(c){throw o.abort(L(c)),c}}catch(o){let c=L(o);console.warn(`subscribe_namespace error: ${ee(c)}`),c instanceof Ne&&this.#e.close(),e.close(c)}finally{s=!0;for(let o of i)this.#l(o);i.clear()}}consume(e){return this.#i.get(e)??this.#i.insert(e,this.#f(e))}#f(e){let t=new Xa;return(async()=>{for(;;){let n=await t.requested();if(!n)break;this.#p(e,n)}})(),t}async#p(e,t){let n=await this.#e.nextRequestId();if(n===void 0){t.reject(new Error("session closed"));return}console.debug(`subscribe start: id=${n} broadcast=${e} track=${t.name}`);let i=t.accept({ordered:!1}),s={},a=this.#b(s,e,t,i,n),o=async()=>{for(;;)if(await i.unused(),i.closed.peek()!==void 0||!i.used.peek())return null},c,u;try{let d=await Promise.race([Rt(a,Rl,`subscribe timed out after ${Rl}ms waiting for SUBSCRIBE_OK (browser stream limit reached?)`),o()]);if(d===null)throw new Error("subscribe abandoned before it was accepted");c=d.stream,u=d.alias,console.debug(`subscribe ok: id=${n} broadcast=${e} track=${t.name}`)}catch(d){let f=L(d);i.close(f),console.warn(`subscribe error: id=${n} broadcast=${e} track=${t.name} error=${ee(f)}`);let l=!1,h=async p=>{s.cancelled=!0,s.registeredAlias!==void 0&&this.#r.retire(s.registeredAlias,i)&&this.#n.delete(s.registeredAlias),!(!s.stream||l)&&(!s.sent&&!p||(l=!0,s.sent&&!s.rejected&&await this.#m(s.stream,n),s.stream.abort(f)))};h(!1),a.then(()=>h(!0),()=>h(!0));return}try{let d=Symbol("publisher"),f=Symbol("local"),l=Symbol("idle"),h=Promise.race([c.reader.closed.then(()=>d),i.closed.then(()=>f)]),p=f;for(;;){let _=await Promise.race([h,i.unused().then(()=>l)]);if(!(_===l&&i.closed.peek()===void 0&&i.used.peek())){p=_;break}}p!==d&&await this.#m(c,n),i.close(),c.close(),console.debug(`subscribe close: id=${n} broadcast=${e} track=${t.name}`)}catch(d){let f=L(d);i.close(f),c.abort(f),console.warn(`subscribe error: id=${n} broadcast=${e} track=${t.name} error=${ee(f)}`)}finally{this.#r.retire(u,i)&&this.#n.delete(u)}}async#m(e,t){let n=this.#e.version;if(!(n!==m.DRAFT_14&&n!==m.DRAFT_15&&n!==m.DRAFT_16))try{await e.writer.u53(_i.id),await new _i({requestId:t}).encode(e.writer,n)}catch{}}async#b(e,t,n,i,s){let a=this.#e.version;if(e.stream=await this.#e.openBi(),e.cancelled)throw new Error("subscribe cancelled before it was sent");if(await e.stream.writer.u53(qt.id),await new qt({requestId:s,trackNamespace:t,trackName:n.name,subscriberPriority:Tl(n.priority)}).encode(e.stream.writer,a),e.sent=!0,e.cancelled)throw new Error("subscribe cancelled while it was being sent");console.debug(`subscribe written: id=${s} broadcast=${t} track=${n.name}`);let c=await e.stream.reader.u53();if(c!==Zt.id){let d="unknown error";try{if(c===ve.id){let f=a===m.DRAFT_14?await wr.decode(e.stream.reader,a):await ve.decode(e.stream.reader,a);d=`code=${f.errorCode} reason=${f.reasonPhrase}`}}catch{}throw e.rejected=!0,new Error(`SUBSCRIBE error: ${d}`)}let u=await Zt.decode(e.stream.reader,a);try{this.#r.set(u.trackAlias,i,{broadcast:t,name:n.name}),u.timescale!==void 0&&this.#n.set(u.trackAlias,u.timescale)}catch(d){throw d instanceof vi&&this.#e.close(),d}return e.registeredAlias=u.trackAlias,{stream:e.stream,alias:u.trackAlias}}async runPublishNamespace(e,t){let n=this.#e.version,i=e.trackNamespace;if(this.#c(e.cluster)){console.debug(`dropping reflected publish_namespace: broadcast=${i}`),await t.writer.u53(ve.id),await new ve({requestId:e.requestId,errorCode:400,reasonPhrase:"route loops back"}).encode(t.writer,n),t.close();return}let s=n===m.DRAFT_14||n===m.DRAFT_15;if(s&&(this.#o.has(i)||this.#s.has(i))){console.warn("duplicate PublishNamespace"),n===m.DRAFT_14?(await t.writer.u53(mi.id),await new mi({requestId:e.requestId,errorCode:409,reasonPhrase:"duplicate namespace"}).encode(t.writer,n)):(await t.writer.u53(ve.id),await new ve({requestId:e.requestId,errorCode:409,reasonPhrase:"duplicate namespace"}).encode(t.writer,n)),t.close();return}s&&this.#s.add(i);let a=!1;try{n===m.DRAFT_14?(await t.writer.u53(_r.id),await new _r({requestId:e.requestId}).encode(t.writer,n)):(await t.writer.u53(Pe.id),await new Pe({requestId:n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0}).encode(t.writer,n)),a=!0,this.#d(i);let o=n===m.DRAFT_16||s;for(;!await t.reader.done();){let c=await t.reader.u53();if(o&&c===$t.id){await $t.decode(t.reader,n);break}if(c!==Ye.id)throw new Ne(`unexpected message on publish_namespace stream: 0x${c.toString(16)}`);let u=await Ye.decode(t.reader,n,Gr(this.#t));if(u.requestId!==e.requestId||u.trackNamespace!==i)throw new Ne("publish_namespace update does not match its stream");if(this.#c(u.cluster)){a&&(a=!1,console.debug(`publish_namespace now loops back, detaching: broadcast=${i}`),this.#l(i));continue}a||(a=!0,this.#d(i))}}finally{s&&this.#s.delete(i),a&&this.#l(i)}}async runPublish(e,t){let n=this.#e.version,i=3;n===m.DRAFT_14?(await t.writer.u53(hi.id),await new hi({requestId:e.requestId,errorCode:i,reasonPhrase:"publish not supported"}).encode(t.writer,n)):(await t.writer.u53(ve.id),await new ve({requestId:n===m.DRAFT_15||n===m.DRAFT_16?e.requestId:void 0,errorCode:i,reasonPhrase:"publish not supported"}).encode(t.writer,n)),t.close()}async handleGroup(e,t){let n=new wt(e.groupId);if(e.subGroupId!==0)throw new Error("subgroups are not supported");try{let i=await this.#r.get(e.trackAlias);for(i.writeGroup(n);await Promise.race([t.done(),n.closed,i.closed])===!1;){let a=await Yr.decode(t,e.flags,this.#n.get(e.trackAlias),this.#e.version);if(a.payload===void 0)break;n.writeFrame({payload:a.payload,timestamp:a.timestamp??xe.now()})}n.close()}catch(i){let s=L(i);s instanceof bi&&console.debug(`dropping group for a cancelled subscription: alias=${e.trackAlias}`),n.close(s),t.stop(s)}}},Xa=class r extends Vr{constructor(e){super(e)}clone(){return new r(this.shareState())}fetchGroup(){return Promise.reject(new Error("fetch group is not supported for moq-transport"))}};var At=class{url;version;transport;discovery;probe=new A({});#e;#t;#r;#n;#i;#s;#o=!1;constructor({url:e,quic:t,control:n,maxRequestId:i,version:s,client:a,discovery:o=!0,solicit:c,cluster:u}){if(this.url=e,this.discovery=o,this.version=Gu(s),this.transport=Os(t),this.#e=t,s>=m.DRAFT_17)this.#t=new hs(t,s,a),this.#f(n,s);else{let d=new ps(t,n,s,i,a);this.#t=d,d.run().catch(f=>{this.#o||console.error("adapter error",f),this.close()})}this.#r=new Bs({quic:this.#e,session:this.#t,requiresSolicitation:c??!1,cluster:u}),this.#i=c,this.#s=u,this.#n=new Ns({session:this.#t,cluster:u}),this.#a()}async stats(){return Is(this.#e)}close(){if(!this.#o){this.#o=!0,this.#r.close(),this.#t.close();try{this.#e.close()}catch{}}}async#a(){try{await Promise.all([this.#c(),this.#l(),this.#r.runPublishNamespaces()])}catch(e){this.#o||console.error("fatal error running connection",e)}finally{this.close()}}publish(e,t){this.#r.publish(e,t)}announced(e=Me()){return this.#n.announced(e)}consume(e){return this.#n.consume(e)}announcedBroadcast(e){return new zt({connection:this,path:e})}async#c(){for(;;){let e=await this.#t.acceptBi();if(!e)break;this.#d(e).catch(t=>{console.error("error processing bidi stream",t),e.abort(new Error("bidi stream error")),t instanceof Ne&&this.close()})}}async#d(e){let t=await e.reader.u53();switch(t){case vt.id:{let n=await vt.decode(e.reader,this.#t.version);await this.#r.runSubscribeNamespace(n,e);break}case Gt.id:{let n=await Gt.decode(e.reader,this.#t.version),i=new vt({requestId:n.requestId,namespace:n.namespace});await this.#r.runSubscribeNamespace(i,e);break}case Ls.id:{e.abort(new Error("unexpected REQUEST_UPDATE as initial message"));break}case qt.id:{let n=await qt.decode(e.reader,this.#t.version);await this.#r.runSubscribe(n,e);break}case yi.id:{let n=await yi.decode(e.reader,this.#t.version);await this.#r.runTrackStatusRequest(n,e);break}case Ye.id:{let n=await Ye.decode(e.reader,this.#t.version,Gr(this.#s)),i=this.#t.version===m.DRAFT_14||this.#t.version===m.DRAFT_15;if(this.#i!==void 0&&!i){console.error(`unsolicited publish_namespace from a peer that implements MoQ Solicit: broadcast=${n.trackNamespace}`),this.close();break}await this.#n.runPublishNamespace(n,e);break}case fi.id:{let n=await fi.decode(e.reader,this.#t.version);await this.#n.runPublish(n,e);break}default:console.warn(`unexpected bidi stream type: 0x${t.toString(16)}`),e.abort(new Error("unexpected stream type"))}}async#l(){let e=new Br(this.#e,this.#t.version);for(;;){let t=await e.next();if(!t)break;this.#u(t).then(()=>{t.stop(new Error("cancel"))}).catch(n=>{console.error("error processing object stream",n),t.stop(n)})}}async#u(e){let t=await Xr.decode(e,this.#t.version);await this.#n.handleGroup(t,e)}async#f(e,t){try{if(await e.reader.done())return;let i=await e.reader.u53();if(i===li.id){let s=await li.decode(e.reader,t);console.warn(`received GOAWAY with redirect URI: ${s.newSessionUri}`)}else console.warn(`unexpected message on setup stream: 0x${i.toString(16)}`)}catch(n){this.#o||console.error("error reading setup stream",n)}finally{this.close()}}get closed(){return this.#e.closed.then(()=>{})}};var yr=class r{static id=12032;parameters;constructor({parameters:e=new ue}={}){this.parameters=e}async#e(e,t){await this.parameters.encode(e,t)}async encode(e,t){return C(e,n=>this.#e(n,t))}static async#t(e,t){let n=await ue.decode(e,t);return new r({parameters:n})}static async decode(e,t){return O(e,n=>r.#t(n,t))}},Lw=128,br=class r{static id=32;versions;parameters;constructor({versions:e,parameters:t=new ue}){this.versions=e,this.parameters=t}async#e(e,t){if(t===m.DRAFT_15||t===m.DRAFT_16)await this.parameters.encode(e,t);else if(t===m.DRAFT_14){await e.u53(this.versions.length);for(let n of this.versions)await e.u53(n);await this.parameters.encode(e,t)}else throw new Error("ClientSetup not used for this version")}async encode(e,t){return C(e,n=>this.#e(n,t))}static async#t(e,t){if(t===m.DRAFT_15||t===m.DRAFT_16){let n=await ue.decode(e,t);return new r({versions:[t],parameters:n})}else if(t===m.DRAFT_14){let n=await e.u53();if(n>Lw)throw new Error(`too many versions: ${n}`);let i=[];for(let a=0;a<n;a++){let o=await e.u53();i.push(o)}let s=await ue.decode(e,t);return new r({versions:i,parameters:s})}else throw new Error("ClientSetup not used for this version")}static async decode(e,t){return O(e,n=>r.#t(n,t))}},vr=class r{static id=33;version;parameters;constructor({version:e,parameters:t=new ue}){this.version=e,this.parameters=t}async#e(e,t){if(t===m.DRAFT_15||t===m.DRAFT_16)await this.parameters.encode(e,t);else if(t===m.DRAFT_14)await e.u53(this.version),await this.parameters.encode(e,t);else throw new Error("ServerSetup not used for this version")}async encode(e,t){return C(e,n=>this.#e(n,t))}static async#t(e,t){if(t===m.DRAFT_15||t===m.DRAFT_16){let n=await ue.decode(e,t);return new r({version:t,parameters:n})}else if(t===m.DRAFT_14){let n=await e.u53(),i=await ue.decode(e,t);return new r({version:n,parameters:i})}else throw new Error("ServerSetup not used for this version")}static async decode(e,t){return O(e,n=>r.#t(n,t))}};function Ar(r){let e=r.getVarint(de.Solicit);return e===void 0?void 0:e!==0n}function xr(r){r.setVarint(de.Solicit,1n)}async function Z(r,e){let t=new Uint8Array,n=new me(new WritableStream({write(i){let s=t.byteLength+i.byteLength;if(s>t.buffer.byteLength){let a=Math.max(s,t.buffer.byteLength*2),o=new ArrayBuffer(a),c=new Uint8Array(o,0,s);c.set(t),c.set(i,t.byteLength),t=c}else t=new Uint8Array(t.buffer,0,s),t.set(i,s-i.byteLength)}}));await e(n),n.close(),await n.closed,await r.u53(t.byteLength),t.byteLength>0&&await r.write(t)}async function G(r,e){let t=await r.u53(),n=await r.read(t),i=new ae(void 0,n),s=await e(i);if(!await i.done())throw new Error("Message decoding consumed too few bytes");return s}async function at(r,e){if(!await r.done())return await G(r,e)}var S={DRAFT_01:4279086337,DRAFT_02:4279086338,DRAFT_03:4279086339,DRAFT_04:4279086340,DRAFT_05:4279086341,DRAFT_06:4279086342};function St(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:return!1;default:return!0}}function qs(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:return!1;default:return!0}}function en(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:return!1;default:return!0}}function Ht(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:return!1;default:return!0}}function Et(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:case S.DRAFT_05:return!1;default:return!0}}function Ai(r){switch(r){case S.DRAFT_04:case S.DRAFT_05:return!0;default:return!1}}function Ka(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:case S.DRAFT_05:return!1;default:return!0}}var tn="moql",rn="moq-lite-03",nn="moq-lite-04",sn="moq-lite-05",Zs="moq-lite-06-wip",Uw={[S.DRAFT_01]:"moq-lite-01",[S.DRAFT_02]:"moq-lite-02",[S.DRAFT_03]:"moq-lite-03",[S.DRAFT_04]:"moq-lite-04",[S.DRAFT_05]:"moq-lite-05",[S.DRAFT_06]:"moq-lite-06-wip"};function Fl(r){return Uw[r]??`unknown(0x${r.toString(16)})`}var Ol=0,Vl=1,Bw=2,Ll=0,Ul=1,Bl=2;function $w(r){if(r.length>qe)throw new Error(`hop count ${r.length} exceeds maximum ${qe}`)}async function Gs(r,e,t){switch($w(t),e){case S.DRAFT_01:case S.DRAFT_02:break;case S.DRAFT_03:await r.u53(t.length);break;default:await r.u53(t.length);for(let n of t)await r.u62(n);break}}async function Qa(r,e){switch(e){case S.DRAFT_01:case S.DRAFT_02:return[];case S.DRAFT_03:{let t=await r.u53();if(t>qe)throw new Error(`hop count ${t} exceeds maximum ${qe}`);return new Array(t).fill(ri)}default:{let t=await r.u53();if(t>qe)throw new Error(`hop count ${t} exceeds maximum ${qe}`);let n=[];for(let i=0;i<t;i++)n.push(st.parse(await r.u62()));return n}}}async function Dl(r,e,t){Ka(e)&&await r.u62(t??0n)}async function Cl(r,e){return Ka(e)?await r.u62():0n}async function Nw(r,e,t){switch(e.status){case"active":await r.string(Te(e.suffix)),await Gs(r,t,e.hops),await Dl(r,t,e.cost);break;case"endedId":await r.u62(e.id);break;case"restart":await r.u62(e.id),await Gs(r,t,e.hops),await Dl(r,t,e.cost);break;case"ended":throw new Error("ended-by-path not supported for this version")}}function qw(r){switch(r.status){case"active":return Ll;case"endedId":return Ul;case"restart":return Bl;case"ended":throw new Error("ended-by-path not supported for this version")}}async function Zw(r,e,t){switch(e){case Ll:{let n=$e(await r.string()),i=await Qa(r,t);return{status:"active",suffix:n,hops:i,cost:await Cl(r,t)}}case Ul:return{status:"endedId",id:await r.u62()};case Bl:{let n=await r.u62(),i=await Qa(r,t);return{status:"restart",id:n,hops:i,cost:await Cl(r,t)}}default:throw new Error(`unknown announce message type: ${e}`)}}async function Gw(r,e,t){switch(e.status){case"active":await r.u8(Vl),await r.string(Te(e.suffix)),await Gs(r,t,e.hops);break;case"ended":await r.u8(Ol),await r.string(Te(e.suffix)),await Gs(r,t,[]);break;case"endedId":case"restart":throw new Error("announce ids not supported for this version")}}async function jw(r,e){let t=await r.u8(),n=t===Vl||t===Bw&&Ht(e);if(t!==Ol&&!n)throw new Error("invalid announce status");let i=$e(await r.string()),s=await Qa(r,e);return n?{status:"active",suffix:i,hops:s}:{status:"ended",suffix:i}}async function un(r,e,t){return Et(t)?(await r.u53(qw(e)),Z(r,n=>Nw(n,e,t))):Z(r,n=>Gw(n,e,t))}async function $l(r,e){if(Et(e)){if(await r.done())return;let t=await r.u53();return G(r,n=>Zw(n,t,e))}return at(r,t=>jw(t,e))}var on=class r{prefix;excludeHop;constructor(e,t=0n){this.prefix=e,this.excludeHop=t}async#e(e,t){await e.string(Te(this.prefix)),Ai(t)&&await e.u62(this.excludeHop)}static async#t(e,t){let n=$e(await e.string()),i=Ai(t)?await e.u62():0n;return new r(n,i)}async encode(e,t){return Z(e,n=>this.#e(n,t))}static async decode(e,t){return G(e,n=>r.#t(n,t))}},an=class r{suffixes;constructor(e){this.suffixes=e}static#e(e){switch(e){case S.DRAFT_01:case S.DRAFT_02:break;default:throw new Error("announce init not supported for this version")}}async#t(e){await e.u53(this.suffixes.length);for(let t of this.suffixes)await e.string(Te(t))}static async#r(e){let t=await e.u53(),n=[];for(let i=0;i<t;i++)n.push($e(await e.string()));return new r(n)}async encode(e,t){return r.#e(t),Z(e,this.#t.bind(this))}static async decode(e,t){return r.#e(t),G(e,r.#r)}},cn=class r{origin;active;constructor(e,t){this.origin=e,this.active=t}static#e(e){if(!Ht(e))throw new Error("announce ok not supported for this version")}async#t(e){await e.u62(this.origin),await e.u53(this.active)}static async#r(e){let t=await e.u62();if(t===0n)throw new Error("announce ok origin must be non-zero");let n=st.parse(t),i=await e.u53();return new r(n,i)}async encode(e,t){return r.#e(t),Z(e,this.#t.bind(this))}static async decode(e,t){return r.#e(t),G(e,r.#r)}};function Nl(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:throw new Error("fetch not supported for this version");default:break}}var dn=class r{broadcast;track;priority;group;constructor(e,t,n,i){this.broadcast=e,this.track=t,this.priority=n,this.group=i}async#e(e){await e.string(Te(this.broadcast)),await e.string(this.track),await e.u8(this.priority),await e.u53(this.group)}static async#t(e){let t=$e(await e.string()),n=await e.string(),i=await e.u8(),s=await e.u53();return new r(t,n,i,s)}async encode(e,t){return Nl(t),Z(e,n=>this.#e(n))}static async decode(e,t){return Nl(t),G(e,n=>r.#t(n))}};function ql(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:throw new Error("goaway not supported for this version");default:break}}var js=class r{uri;constructor(e){this.uri=e}async#e(e){await e.string(this.uri)}static async#t(e){return new r(await e.string())}async encode(e,t){return ql(t),Z(e,this.#e.bind(this))}static async decode(e,t){return ql(t),G(e,r.#t)}};var ln=class r{subscribe;sequence;constructor(e,t){this.subscribe=e,this.sequence=t}async#e(e){await e.u62(this.subscribe),await e.u53(this.sequence)}static async#t(e){return new r(await e.u62(),await e.u53())}async encode(e){return Z(e,this.#e.bind(this))}static async decode(e){return G(e,r.#t)}static async decodeMaybe(e){return at(e,r.#t)}};var fn=class r{subscribe;sequence;timestamp;payload;constructor(e,t,n,i){this.subscribe=e,this.sequence=t,this.timestamp=n,this.payload=i}encode(){let e=Xe(new ArrayBuffer(8),this.subscribe),t=Xe(new ArrayBuffer(8),this.sequence),n=Xe(new ArrayBuffer(8),this.timestamp),i=new Uint8Array(e.byteLength+t.byteLength+n.byteLength+this.payload.byteLength),s=0;return i.set(e,s),s+=e.byteLength,i.set(t,s),s+=t.byteLength,i.set(n,s),s+=n.byteLength,i.set(this.payload,s),i}static async decode(e){let t=new ae(void 0,e),n=await t.u62(),i=await t.u53(),s=await t.u53(),a=await t.readAll();return new r(n,i,s,a)}};function Ja(r){return r.datagrams}function xi(r){let e=Ja(r)?.maxDatagramSize;return typeof e=="number"&&e>0?e:0}function Zl(r){let e=Ja(r)?.readable;if(!e){console.warn("datagram receive disabled: WebTransport datagrams.readable is unavailable");return}try{return e.getReader()}catch(t){console.warn("datagram receive disabled: failed to open WebTransport datagram reader",t);return}}function Gl(r){let e=Ja(r);if(!(!e||xi(r)===0))try{let t=typeof e.createWritable=="function"?e.createWritable():e.writable;if(!t){console.warn("datagram send disabled: WebTransport datagram writable stream is unavailable");return}return t.getWriter()}catch(t){console.warn("datagram send disabled: failed to open WebTransport datagram writer",t);return}}function hn({priority:r,position:e=0}){return-((255-Wl(r,255))*17592186044416+Wl(e,17592186044416-1)+1)}function Wl(r,e){return Math.min(Math.max(Math.trunc(r),0),e)}var Ws=class{#e;#t=new Map;#r;#n=!1;constructor(e){this.#e=e,this.#r=e.subscription.subscribe(()=>this.#s())}rank(e){return hn({priority:this.#e.subscription.peek()?.priority??0,position:this.#i(e)})}add(e,t){this.#t.set(e,t),this.#s()}remove(e){this.#t.delete(e)&&(this.#n&&this.#t.size===0?this.#r():this.#s())}close(){this.#n=!0,this.#t.size===0&&this.#r()}#i(e){let t=this.#e.subscription.peek()?.ordered??!1,n=0;for(let i of this.#t.values())(t?i<e:i>e)&&n++;return n}#s(){let e=this.#e.subscription.peek()?.priority??0;for(let[t,n]of this.#t)t.setPriority(hn({priority:e,position:this.#i(n)}))}};function ec(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:throw new Error("probe not supported for this version");default:break}}var pn=class r{bitrate;rtt;constructor({bitrate:e,rtt:t}={}){this.bitrate=e,this.rtt=t}async#e(e,t){await e.u53(this.bitrate!==void 0?Math.max(this.bitrate,1):0),St(t)&&await e.u53(this.rtt!==void 0?Math.max(this.rtt,1):0)}static async#t(e,t){let n=await e.u53(),i=n===0?void 0:n,s;if(St(t)){let a=await e.u53();s=a===0?void 0:a}return new r({bitrate:i,rtt:s})}async encode(e,t){return ec(t),Z(e,n=>this.#e(n,t))}static async decode(e,t){return ec(t),G(e,n=>r.#t(n,t))}static async decodeMaybe(e,t){return ec(t),at(e,n=>r.#t(n,t))}};var Sr=class r{priority;ordered;maxLatency;startGroup;endGroup;constructor(e){this.priority=e.priority,this.ordered=e.ordered??!1,this.maxLatency=e.maxLatency??0,this.startGroup=e.startGroup,this.endGroup=e.endGroup}async#e(e,t){switch(t){case S.DRAFT_01:case S.DRAFT_02:await e.u8(this.priority);break;default:await e.u8(this.priority),await e.bool(this.ordered),await e.u53(this.maxLatency),await e.u53(this.startGroup!==void 0?this.startGroup+1:0),await e.u53(this.endGroup!==void 0?this.endGroup+1:0);break}}static async#t(e,t){switch(t){case S.DRAFT_01:case S.DRAFT_02:return new r({priority:await e.u8()});default:{let n=await e.u8(),i=await e.bool(),s=await e.u53(),a=await e.u53(),o=await e.u53();return new r({priority:n,ordered:i,maxLatency:s,startGroup:a>0?a-1:void 0,endGroup:o>0?o-1:void 0})}}}async encode(e,t){return Z(e,n=>this.#e(n,t))}static async decode(e,t){return G(e,n=>r.#t(n,t))}static async decodeMaybe(e,t){return at(e,n=>r.#t(n,t))}},mn=class r{id;broadcast;track;priority;ordered;maxLatency;startGroup;endGroup;constructor(e){this.id=e.id,this.broadcast=e.broadcast,this.track=e.track,this.priority=e.priority,this.ordered=e.ordered??!1,this.maxLatency=e.maxLatency??0,this.startGroup=e.startGroup,this.endGroup=e.endGroup}async#e(e,t){switch(await e.u62(this.id),await e.string(Te(this.broadcast)),await e.string(this.track),await e.u8(this.priority),t){case S.DRAFT_01:case S.DRAFT_02:break;default:await e.bool(this.ordered),await e.u53(this.maxLatency),await e.u53(this.startGroup!==void 0?this.startGroup+1:0),await e.u53(this.endGroup!==void 0?this.endGroup+1:0);break}}static async#t(e,t){let n=await e.u62(),i=$e(await e.string()),s=await e.string(),a=await e.u8();switch(t){case S.DRAFT_01:case S.DRAFT_02:return new r({id:n,broadcast:i,track:s,priority:a});default:{let o=await e.bool(),c=await e.u53(),u=await e.u53(),d=await e.u53();return new r({id:n,broadcast:i,track:s,priority:a,ordered:o,maxLatency:c,startGroup:u>0?u-1:void 0,endGroup:d>0?d-1:void 0})}}}async encode(e,t){return Z(e,n=>this.#e(n,t))}static async decode(e,t){return G(e,n=>r.#t(n,t))}},_n=class r{priority;ordered;maxLatency;startGroup;endGroup;constructor({priority:e=0,ordered:t=!1,maxLatency:n=0,startGroup:i=void 0,endGroup:s=void 0}){this.priority=e,this.ordered=t,this.maxLatency=n,this.startGroup=i,this.endGroup=s}async#e(e,t){switch(t){case S.DRAFT_02:break;case S.DRAFT_01:await e.u8(this.priority??0);break;default:await e.u8(this.priority),await e.bool(this.ordered),await e.u53(this.maxLatency),await e.u53(this.startGroup!==void 0?this.startGroup+1:0),await e.u53(this.endGroup!==void 0?this.endGroup+1:0);break}}static async#t(e,t){let n,i,s,a,o;switch(e){case S.DRAFT_02:break;case S.DRAFT_01:n=await t.u8();break;default:n=await t.u8(),i=await t.bool(),s=await t.u53(),a=await t.u53(),o=await t.u53();break}return new r({priority:n,ordered:i,maxLatency:s,startGroup:a!==void 0&&a>0?a-1:void 0,endGroup:o!==void 0&&o>0?o-1:void 0})}async encode(e,t){return Z(e,n=>this.#e(n,t))}static async decode(e,t){return G(e,r.#t.bind(r,t))}},Si=class r{group;constructor(e){this.group=e}async encode(e){return Z(e,async t=>{await t.u53(this.group)})}static async decode(e){return G(e,async t=>new r(await t.u53()))}},Ei=class r{group;constructor(e){this.group=e}async encode(e){return Z(e,async t=>{await t.u53(this.group)})}static async decode(e){return G(e,async t=>new r(await t.u53()))}},Hs=class r{start;end;error;constructor(e){this.start=e.start,this.end=e.end,this.error=e.error}async#e(e){await e.u53(this.start),await e.u53(this.end),await e.u53(this.error)}static async#t(e){return new r({start:await e.u53(),end:await e.u53(),error:await e.u53()})}async encode(e){return Z(e,this.#e.bind(this))}static async decode(e){return G(e,r.#t)}};async function Xs(r,e,t){switch(t){case S.DRAFT_01:case S.DRAFT_02:if("ok"in e)await e.ok.encode(r,t);else throw new Error("only SUBSCRIBE_OK is supported for this version");break;case S.DRAFT_03:case S.DRAFT_04:if("ok"in e)await r.u53(0),await e.ok.encode(r,t);else if("drop"in e)await r.u53(1),await e.drop.encode(r);else throw new Error("SUBSCRIBE_START/END not supported for this version");break;default:if("start"in e)await r.u53(0),await e.start.encode(r);else if("end"in e)await r.u53(1),await e.end.encode(r);else if("drop"in e)await r.u53(2),await e.drop.encode(r);else throw new Error("SUBSCRIBE_OK not supported for this version");break}}async function tc(r,e){switch(e){case S.DRAFT_01:case S.DRAFT_02:return{ok:await _n.decode(r,e)};case S.DRAFT_03:case S.DRAFT_04:{let t=await r.u53();switch(t){case 0:return{ok:await _n.decode(r,e)};case 1:return{drop:await Hs.decode(r)};default:throw new Error(`unknown subscribe response type: ${t}`)}}default:{let t=await r.u53();switch(t){case 0:return{start:await Si.decode(r)};case 1:return{end:await Ei.decode(r)};case 2:return{drop:await Hs.decode(r)};default:throw new Error(`unknown subscribe response type: ${t}`)}}}}async function Hl(r,e){if(!await r.done())return tc(r,e)}function Ys(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:throw new Error("track stream not supported for this version");default:break}}var wn=class r{broadcast;track;constructor(e,t){this.broadcast=e,this.track=t}async#e(e){await e.string(Te(this.broadcast)),await e.string(this.track)}static async#t(e){let t=$e(await e.string()),n=await e.string();return new r(t,n)}async encode(e,t){return Ys(t),Z(e,n=>this.#e(n))}static async decode(e,t){return Ys(t),G(e,n=>r.#t(n))}},gn=class r{priority;ordered;latencyMax;timescale;constructor({priority:e=0,ordered:t=!1,latencyMax:n=0,timescale:i=0}){this.priority=e,this.ordered=t,this.latencyMax=n,this.timescale=i}async#e(e){await e.u8(this.priority),await e.bool(this.ordered),await e.u53(this.latencyMax),await e.u53(this.timescale)}static async#t(e){let t=await e.u8(),n=await e.bool(),i=await e.u53(),s=await e.u53();if(s===0)throw new Error("track timescale must be non-zero");return new r({priority:t,ordered:n,latencyMax:i,timescale:s})}async encode(e,t){if(Ys(t),this.timescale===0)throw new Error("track timescale must be non-zero");return Z(e,n=>this.#e(n))}static async decode(e,t){return Ys(t),G(e,n=>r.#t(n))}};var rc=100,Ks=1e4,Ww=.25,Hw=.25;function Xl(r){return r>=0n?r<<1n:(-r<<1n)-1n}function Qs(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:return!1;default:return!0}}var Js=class{version;origin;#e;#t;#r=new A(new Map);#n=new Map;constructor(e,t,n){this.#e=e,this.version=t,this.origin=n,en(t)&&(this.#t=Gl(e))}publish(e,t){this.#r.mutate(n=>{if(!n)throw new Error("closed");n.set(e,t)}),t.closed.then(()=>{this.#r.mutate(n=>{n?.get(e)===t&&n.delete(e)})})}async runAnnounce(e,t){console.debug(`announce: prefix=${e.prefix}`);let n=new Set,i=this.#r.peek();if(!i)return;for(let o of i.keys()){let c=tt(e.prefix,o);c!==null&&(console.debug(`announce: broadcast=${o} active=true`),n.add(c))}let s=0n,a=new Map;switch(this.version){case S.DRAFT_01:case S.DRAFT_02:{await new an([...n]).encode(t.writer,this.version);break}default:{if(!Ht(this.version)){for(let c of n)await un(t.writer,{status:"active",suffix:c,hops:[this.origin]},this.version);break}await new cn(this.origin,n.size).encode(t.writer,this.version);for(let c of n)Et(this.version)&&a.set(c,s++),await un(t.writer,{status:"active",suffix:c,hops:[]},this.version);break}}for(;;){let o,c=new Promise(f=>{o=this.#r.changed(f)}),u=await Promise.race([c,t.reader.closed]);if(o(),!u)break;let d=new Set;for(let f of u.keys()){let l=tt(e.prefix,f);l!==null&&d.add(l)}for(let f of d.difference(n)){console.debug(`announce: broadcast=${f} active=true`);let l=Ht(this.version)?[]:[this.origin];Et(this.version)&&a.set(f,s++),await un(t.writer,{status:"active",suffix:f,hops:l},this.version)}for(let f of n.difference(d))if(console.debug(`announce: broadcast=${f} active=false`),Et(this.version)){let l=a.get(f);if(a.delete(f),l===void 0)continue;await un(t.writer,{status:"endedId",id:l},this.version)}else await un(t.writer,{status:"ended",suffix:f},this.version);n=d}}async runSubscribe(e,t){let n=this.#r.peek()?.get(e.broadcast);if(!n){console.debug(`publish unknown: broadcast=${e.broadcast}`),t.writer.reset(new Error("not found"));return}let i=n.subscribe(e.track,{priority:e.priority,ordered:e.ordered,latencyMax:e.maxLatency,startGroup:e.startGroup,endGroup:e.endGroup}),s=e.startGroup??i.latest();s!==void 0&&i.startAt(s),i.endAt(e.endGroup);let a=Promise.resolve();try{let o=ne.MILLI;if(Qs(this.version))o=(await i.info()).timescale;else{let u=new _n({priority:e.priority,ordered:e.ordered,maxLatency:e.maxLatency,startGroup:e.startGroup,endGroup:e.endGroup});await Xs(t.writer,{ok:u},this.version)}console.debug(`publish ok: broadcast=${e.broadcast} track=${i.name}`);let c=this.#i(e.id,e.broadcast,i,t.writer,o);for(this.#t&&(a=this.#o(e.id,i,o));;){let u=Sr.decodeMaybe(t.reader,this.version),d=await Promise.any([c,u]);if(!d)break;d instanceof Sr&&(console.debug(`subscribe update: broadcast=${e.broadcast} track=${i.name}`),i.update({priority:d.priority,ordered:d.ordered,latencyMax:d.maxLatency,startGroup:d.startGroup,endGroup:d.endGroup}),d.startGroup!==void 0&&i.startAt(d.startGroup),i.endAt(d.endGroup))}console.debug(`publish done: broadcast=${e.broadcast} track=${i.name}`),t.close(),i.close(),await a}catch(o){let c=L(o);console.warn(`publish error: broadcast=${e.broadcast} track=${i.name} error=${ee(c)}`),i.close(c),t.abort(c),await a}}async runFetch(e,t){if(!Qs(this.version)){t.writer.reset(new Error("fetch requires moq-lite-05 or newer"));return}let n=this.#r.peek()?.get(e.broadcast);if(!n){console.debug(`fetch unknown: broadcast=${e.broadcast}`),t.writer.reset(new Error("not found"));return}t.writer.setPriority(hn({priority:e.priority}));let i;try{let s=await this.#s(e.broadcast,e.track);i=await n.track(e.track).fetchGroup(e.group,{priority:e.priority}),await this.#a(i,t.writer,ne(s.timescale)),console.debug(`fetch done: broadcast=${e.broadcast} track=${e.track} group=${e.group}`),t.close(),i.close()}catch(s){let a=L(s);console.warn(`fetch error: broadcast=${e.broadcast} track=${e.track} group=${e.group} error=${ee(a)}`),i?.close(a),t.abort(a)}}async#i(e,t,n,i,s){let a=Qs(this.version),o=!1,c=0,u=new Ws(n),d=!1,f,l=new Promise(h=>{f=h});i.closed.then(()=>{d||f()},()=>f());try{for(;;){let h=n.recvGroup(),p=await Promise.race([h,i.closed]);if(!p){h.then(_=>_?.close()).catch(()=>{});break}a&&!o&&(o=!0,n.startAt(p.sequence),await Xs(i,{start:new Si(p.sequence)},this.version)),c=Math.max(c,p.sequence+1),this.#c({sub:e,group:p,timescale:s,priority:u,unsubscribed:l})}a&&await Xs(i,{end:new Ei(c)},this.version),console.debug(`publish close: broadcast=${t} track=${n.name}`),d=!0,n.close(),i.close()}catch(h){let p=L(h);console.warn(`publish error: broadcast=${t} track=${n.name} error=${ee(p)}`),f(),n.close(p),i.reset(p)}finally{u.close()}}async runTrackInfo(e,t){try{await(await this.#s(e.broadcast,e.track)).encode(t.writer,this.version),console.debug(`track info: broadcast=${e.broadcast} track=${e.track}`),t.close()}catch(n){console.debug(`track unknown: broadcast=${e.broadcast} track=${e.track}`),t.writer.reset(L(n))}}#s(e,t){let n=`${e}\0${t}`,i=this.#n.get(n);if(i)return i;let s=(async()=>{let a=this.#r.peek()?.get(e);if(!a)throw new Error("not found");let o=await a.track(t).info();return new gn({priority:o.priority,ordered:o.ordered,latencyMax:o.latencyMax,timescale:o.timescale})})();return s.catch(()=>this.#n.delete(n)),this.#n.set(n,s),s}async#o(e,t,n){let i=this.#t;if(!i)return;let s=xi(this.#e);try{for(;;){let a=await t.recvDatagram();if(!a)return;let o=Math.round(a.timestamp.as(n)),c=new fn(e,a.sequence,o,a.payload).encode();if(c.byteLength>s){console.debug(`dropping oversize datagram: sub=${e} size=${c.byteLength} max=${s}`);continue}await i.ready,await i.write(c)}}catch(a){console.debug(`datagram send stopped: sub=${e} error=${ee(a)}`)}}async#a(e,t,n){let i=0n;for(;;){let s=await Promise.race([e.readFrame(),t.closed]);if(!s)break;let a=BigInt(Math.round(s.timestamp.as(n)));await t.u62(Xl(a-i)),i=a,await t.u53(s.payload.byteLength),await t.write(s.payload)}}async#c(e){let{sub:t,group:n,timescale:i,priority:s,unsubscribed:a}=e,o=new ln(t,n.sequence);try{let c=await me.tryOpen(this.#e,{sendOrder:s.rank(n.sequence),cancel:a,waitUntilAvailable:!1});if(!c){n.close(new Error("no stream slot"));return}try{s.add(c,n.sequence),await c.u53(0),await o.encode(c);let u=Qs(this.version),d=0n;for(;;){let f=await Promise.race([n.readFrame(),c.closed]);if(!f)break;if(u){let l=BigInt(Math.round(f.timestamp.as(i)));await c.u62(Xl(l-d)),d=l}await c.u53(f.payload.byteLength),await c.write(f.payload)}c.close(),n.close()}catch(u){let d=L(u);c.reset(d),n.close(d)}finally{s.remove(c)}}catch(c){let u=L(c);n.close(u)}}async runProbe(e){let t=this.#e;if(!t.getStats){e.close();return}let n,i,s=(a,o,c=0)=>a===void 0&&o===void 0?!1:a===void 0||o===void 0?!0:a===0?o!==0:Math.abs(o-a)/a>=c;try{for(;;){let a=new Promise(l=>setTimeout(()=>l("timeout"),rc));if(await Promise.race([a,e.reader.closed])!=="timeout")break;let c=await t.getStats(),u=c.smoothedRtt!=null?Math.round(c.smoothedRtt):void 0,d=new pn({bitrate:c.estimatedSendRate??void 0,rtt:St(this.version)?u:void 0});if(d.bitrate===void 0&&d.rtt===void 0&&!(n!==void 0&&(n.bitrate!==void 0||n.rtt!==void 0)))continue;let f;if(n===void 0||i===void 0)f=!0;else{let l=performance.now()-i,h=Math.max(rc,Math.min(Ks,l)),p=Ks-rc,_=Ww*(Ks-h)/p;f=l>=Ks||s(n.bitrate,d.bitrate,_)||s(n.rtt,d.rtt,Hw)}f&&(await d.encode(e.writer,this.version),n=d,i=performance.now())}}catch(a){console.warn("probe stream error",a),e.close()}}close(){this.#r.update(e=>{for(let t of e?.values()??[])t.close()}),this.#t?.releaseLock(),this.#t=void 0}};var eo=class r{bitrate;constructor(e){this.bitrate=e}static#e(e){switch(e){case S.DRAFT_01:case S.DRAFT_02:break;default:throw new Error("session info not supported for this version")}}async#t(e){await e.u53(this.bitrate)}static async#r(e){let t=await e.u53();return new r(t)}async encode(e,t){return r.#e(t),Z(e,this.#t.bind(this))}static async decode(e,t){return r.#e(t),G(e,r.#r)}static async decodeMaybe(e,t){return r.#e(t),at(e,r.#r)}};var Yl=0x1n,Kl=0x2n,Ql=0x3n,Jl=0x5n,ef=64,Ce={None:0,Report:1,Increase:2};function Xw(r){switch(r){case 0n:return Ce.None;case 1n:return Ce.Report;default:return Ce.Increase}}var yn={Both:0,Publisher:1,Subscriber:2};function Yw(r){switch(r){case 1n:return yn.Publisher;case 2n:return yn.Subscriber;default:return yn.Both}}var to=class r{#e=new Map;setBytes(e,t){this.#e.set(e,t)}getBytes(e){return this.#e.get(e)}setVarint(e,t){this.#e.set(e,Ur(Number(t)))}getVarint(e){let t=this.#e.get(e);if(t===void 0)return;let[n,i]=rt(t);if(i.byteLength!==0)throw new Error("trailing bytes after varint parameter");return BigInt(n)}async encode(e){if(this.#e.size>ef)throw new Error("too many parameters");await e.u53(this.#e.size);for(let[t,n]of this.#e)await e.u62(t),await e.u53(n.byteLength),await e.write(n)}static async decode(e){let t=new r,n=await e.u53();if(n>ef)throw new Error("too many parameters");for(let i=0;i<n;i++){let s=await e.u62();if(t.#e.has(s))throw new Error(`duplicate parameter id: ${s.toString()}`);let a=await e.u53(),o=await e.read(a);t.#e.set(s,o)}return t}},ki=class r{probe;path;role;origin;constructor({probe:e,path:t,role:n,origin:i}={}){this.probe=e??Ce.None,this.path=t,this.role=n??yn.Both,this.origin=i}static#e(e){if(!qs(e))throw new Error("setup stream not supported for this version")}async#t(e){let t=new to;this.probe!==Ce.None&&t.setVarint(Yl,this.probe),this.path!==void 0&&t.setBytes(Kl,new TextEncoder().encode(this.path)),this.role!==yn.Both&&t.setVarint(Ql,this.role),this.origin!==void 0&&this.origin!==0n&&t.setVarint(Jl,this.origin),await t.encode(e)}static async#r(e){let t=await to.decode(e),n=t.getVarint(Yl),i=n===void 0?Ce.None:Xw(n),s=t.getBytes(Kl),a=s===void 0?void 0:new TextDecoder().decode(s),o=t.getVarint(Ql),c=o===void 0?yn.Both:Yw(o),u=t.getVarint(Jl),d=u===void 0||u===0n?void 0:st.parse(u);return new r({probe:i,path:a,role:c,origin:d})}async encode(e,t){return r.#e(t),Z(e,this.#t.bind(this))}static async decode(e,t){return r.#e(t),G(e,r.#r)}};var J={Session:0,Announce:1,Subscribe:2,Fetch:3,Probe:4,Goaway:5,Track:6,ClientCompat:32,ServerCompat:33},ro={Group:0,Setup:1};var tf=1e4;function rf(r){return r>>1n^-(r&1n)}function no(r){switch(r){case S.DRAFT_01:case S.DRAFT_02:case S.DRAFT_03:case S.DRAFT_04:return!1;default:return!0}}var io=class{#e;version;origin;#t=new Map;#r=0n;#n=new Jr;#i=new Map;#s;#o;#a=new AbortController;constructor(e,t,n,i,s){this.#e=e,this.version=t,this.origin=n,this.#s=i,this.#o=s}announced(e=Me(),t={}){let n=new Pt(e);return this.#c(n,e,t),n.consume()}async#c(e,t,n){console.debug(`announced: prefix=${t}`);let i=new on(t,this.origin),s=n.ignoreSelf||!Ai(this.version);try{let a=await H.open(this.#e);await a.writer.u53(J.Announce),await i.encode(a.writer,this.version);let o;switch(Ht(this.version)&&(o=(await cn.decode(a.reader,this.version)).origin),this.version){case S.DRAFT_01:case S.DRAFT_02:{let f=await an.decode(a.reader,this.version);for(let l of f.suffixes){let h=De(t,l);console.debug(`announced: broadcast=${h} active=true`),e.append({path:l,active:!0})}break}default:break}let c=0n,u=new Map,d=new Map;for(;;){let f=await Promise.race([$l(a.reader,this.version),e.closed]);if(!f)break;if(f instanceof Error)throw f;let l,h,p;switch(f.status){case"active":l=f.suffix,h=!0,p=f.hops,Et(this.version)&&u.set(c++,f.suffix);break;case"ended":l=f.suffix,h=!1;break;case"endedId":{let y=u.get(f.id);if(y===void 0)throw new Error(`unknown announce id: ${f.id}`);u.delete(f.id),l=y,h=!1;break}case"restart":{let y=u.get(f.id);if(y===void 0)throw new Error(`unknown announce id: ${f.id}`);l=y,h=!0,p=f.hops;break}}let _=De(t,l),w=()=>{d.delete(l),this.#n.evict(_),console.debug(`announced: broadcast=${_} active=false`),e.append({path:l,active:!1})};if(p!==void 0&&s&&(o!==void 0?[...p,o]:p).includes(this.origin)){d.has(l)&&w();continue}if(h){let y=p?.[0]??o;if(d.has(l)){if(d.get(l)===y){console.debug(`announced: broadcast=${_} rerouted`);continue}w()}d.set(l,y)}else{w();continue}console.debug(`announced: broadcast=${_} active=true`),e.append({path:l,active:!0})}e.close()}catch(a){e.close(L(a))}}consume(e){return this.#n.get(e)??this.#n.insert(e,this.#d(e))}#d(e){let t=new nc(this,e);return(async()=>{for(;;){let n=await t.requested();if(!n)break;this.#l(e,n)}})(),t}async#l(e,t){let n=this.#r++,i=t.subscription,s=new A(void 0);console.debug(`subscribe start: id=${n} broadcast=${e} track=${t.name}`);let a=new mn({id:n,broadcast:e,track:t.name,priority:i.priority??0,ordered:i.ordered,maxLatency:i.latencyMax,startGroup:i.startGroup,endGroup:i.endGroup}),o={},c=this.#u(o,a,t,n,s),u;try{u=await Rt(c,tf,`subscribe timed out after ${tf}ms waiting for the first response (browser stream limit reached?)`),console.debug(`subscribe ok: id=${n} broadcast=${e} track=${t.name}`)}catch(l){let h=L(l);t.reject(h),this.#t.delete(n),console.warn(`subscribe error: id=${n} broadcast=${e} track=${t.name} error=${ee(h)}`),c.then(()=>o.stream?.abort(h),()=>o.stream?.abort(h));return}let{stream:d,producer:f}=u;try{let l=no(this.version)?this.#x(d):d.reader.closed,h=this.version===S.DRAFT_01||this.version===S.DRAFT_02?void 0:this.#v(n,e,f,a,d),p=[l,f.closed];h!==void 0&&p.push(h);let _=Promise.race(p),w=Symbol("idle");for(;await Promise.race([_,f.unused().then(()=>w)])===w&&f.closed.peek()===void 0&&f.used.peek(););f.close(),d.close(),console.debug(`subscribe close: id=${n} broadcast=${e} track=${t.name}`)}catch(l){let h=L(l);f.close(h),console.warn(`subscribe error: id=${n} broadcast=${e} track=${t.name} error=${ee(h)}`),d.abort(h)}finally{this.#t.delete(n)}}async#u(e,t,n,i,s){let a,o=!1;if(no(this.version)){let c=await this.#f(t.broadcast,t.track);a=n.accept(this.#p(c)),s.set(c.timescale)}else a=n.accept(),s.set(0),o=!0;if(this.#t.set(i,{track:a,timescale:s}),e.stream=await H.open(this.#e),await e.stream.writer.u53(J.Subscribe),await t.encode(e.stream.writer,this.version),o&&!("ok"in await tc(e.stream.reader,this.version)))throw new Error("first subscribe response must be SUBSCRIBE_OK");return{stream:e.stream,producer:a}}async#f(e,t){let n=await H.open(this.#e);try{await n.writer.u53(J.Track),await new wn(e,t).encode(n.writer,this.version);let i=await gn.decode(n.reader,this.version);return n.close(),i}catch(i){throw n.abort(L(i)),i}}#p(e){return{timescale:ne(e.timescale),latencyMax:e.latencyMax,priority:e.priority,ordered:e.ordered}}async resolveTrackInfo(e,t){if(!no(this.version))throw new Error("track info requires moq-lite-05 or newer");return this.#p(await this.#f(e,t))}fetchGroup(e,t,n,i={}){let s=JSON.stringify([e,t,n]),a=this.#i.get(s);if(a&&!a.isClosed)return Promise.resolve(a.mirror());let o=new wt(n);return this.#i.set(s,o),o.closed.then(()=>{this.#i.get(s)===o&&this.#i.delete(s)}),this.#m(e,t,n,i,o)}async#m(e,t,n,i,s){try{if(!no(this.version))throw new Error("fetch group requires moq-lite-05 or newer");let a=await this.#f(e,t),o=i.priority??0,c=await H.open(this.#e,{sendOrder:hn({priority:o})});try{await c.writer.u53(J.Fetch),await new dn(e,t,o,n).encode(c.writer,this.version)}catch(d){throw c.abort(L(d)),d}let u=s.mirror();return this.#b(c,s,ne(a.timescale)),u}catch(a){throw s.close(L(a)),a}}async#b(e,t,n){try{let i=0n,s=Symbol("idle"),a=Promise.resolve(t.closed),o=t.unused().then(()=>s);for(;;){let c=await Promise.race([e.reader.done(),a,o]);if(c===s){if(!t.isClosed&&t.used.peek()){o=t.unused().then(()=>s);continue}break}if(c!==!1)break;i+=rf(await e.reader.u62());let u=new xe(Number(i),n),d=await e.reader.u53(),f=await e.reader.read(d);if(!f)break;t.writeFrame({payload:f,timestamp:u})}t.close(),e.close()}catch(i){let s=L(i);t.close(s),e.abort(s)}}async#x(e){try{for(;;)if(!await Hl(e.reader,this.version))return}catch{}}async#v(e,t,n,i,s){let a=Promise.race([n.closed,s.reader.closed]).then(()=>null),o={priority:i.priority,ordered:i.ordered,latencyMax:i.maxLatency,startGroup:i.startGroup,endGroup:i.endGroup};for(;;){let c=n.subscription.peek();if(c===void 0||this.#g(c,o)){if(await Promise.race([n.subscription.changed(),a])===null)return;continue}await new Sr({priority:c.priority??0,ordered:c.ordered,maxLatency:c.latencyMax,startGroup:c.startGroup,endGroup:c.endGroup}).encode(s.writer,this.version),o={...c},console.debug(`subscribe update: id=${e} broadcast=${t} track=${n.name}`)}}#g(e,t){return(e.priority??0)===(t.priority??0)&&(e.ordered??!1)===(t.ordered??!1)&&(e.latencyMax??0)===(t.latencyMax??0)&&e.startGroup===t.startGroup&&e.endGroup===t.endGroup}async runGroup(e,t){let n=this.#t.get(e.subscribe);if(!n){if(e.subscribe>=this.#r)throw new Error(`unknown subscription: id=${e.subscribe}`);return}let{track:i,timescale:s}=n,a=new wt(e.sequence);i.writeGroup(a);try{let o=s.peek();for(;o===void 0;){if(i.closed.peek()!==void 0){a.close(),t.stop(new Error("cancel"));return}await A.race(s,i.closed),o=s.peek()}let c=0n;for(;await Promise.race([t.done(),i.closed,a.closed])===!1;){let d;o!==0?(c+=rf(await t.u62()),d=new xe(Number(c),ne(o))):d=xe.now();let f=await t.u53(),l=await t.read(f);if(!l)break;a.writeFrame({payload:l,timestamp:d})}a.close(),t.stop(new Error("cancel"))}catch(o){let c=L(o);a.close(c),t.stop(c)}}async runDatagrams(){if(!en(this.version)||xi(this.#e)===0)return;let e=Zl(this.#e);if(e)try{try{for(;;){let{value:t,done:n}=await e.read();if(n)break;if(t)try{await this.#T(t)}catch(i){console.debug(`dropping datagram: ${ee(i)}`)}}}finally{e.releaseLock()}}catch(t){let n=L(t);n.message==="The session is closed."?console.debug(`datagram receive stopped: ${n.message}`):console.warn("datagram stream error",t)}}async#T(e){let t=await fn.decode(e),n=this.#t.get(t.subscribe);if(!n)return;let i=n.timescale.peek();if(!i)return;let s=new xe(t.timestamp,ne(i));n.track.writeDatagram({sequence:t.sequence,timestamp:s,payload:t.payload})}async#h(e){let t=e.peek();for(;t===void 0;)t=await e.changed();return t.probe}async runProbe(){if(this.#s&&!(this.version===S.DRAFT_01||this.version===S.DRAFT_02)&&!(this.#o&&await this.#h(this.#o)<Ce.Report))try{let e=await H.open(this.#e);for(await e.writer.u53(J.Probe);;){let t=await pn.decodeMaybe(e.reader,this.version);if(!t)break;let n=this.#s.peek(),i=t.rtt!==void 0?Nn(t.rtt):void 0;this.#s.set({estimatedRecvRate:t.bitrate,rtt:St(this.version)?i:i??n.rtt})}}catch(e){this.#a.signal.aborted||console.warn("probe stream error",e)}finally{this.#s.set({})}}close(){this.#a.abort();for(let{track:e}of this.#t.values())e.close();this.#t.clear()}},nc=class r extends Vr{#e;#t;constructor(e,t,n){super(n),this.#e=e,this.#t=t}clone(){return new r(this.#e,this.#t,this.shareState())}resolveTrackInfo(e){return this.#e.resolveTrackInfo(this.#t,e)}fetchGroup(e,t,n){return this.#e.fetchGroup(this.#t,e,t,n)}};var ze=class{url;version;transport;discovery;#e;#t;#r;#n;#i;probe;origin;#s=new A(void 0);#o=new A(void 0);#a=new A({});get peerRole(){return this.#o}constructor({url:e,quic:t,version:n,session:i,discovery:s=!0}){this.url=e,this.#t=t,this.#r=i,this.version=Fl(n),this.#e=n,this.transport=Os(t),this.discovery=s,this.probe=this.#a,this.origin=Ts(),this.#n=new Js(this.#t,this.#e,this.origin),this.#i=new io(this.#t,this.#e,this.origin,this.#a,this.#s),this.#c()}close(){this.#n.close(),this.#i.close();try{this.#t.close()}catch{}}async#c(){let e=[this.#d(),this.#u(),this.#p()];qs(this.#e)&&e.push(this.#l()),e.push(this.#i.runProbe()),en(this.#e)&&e.push(this.#i.runDatagrams());try{await Promise.all(e)}catch(t){console.error("fatal error running connection",t)}finally{this.close()}}publish(e,t){this.#n.publish(e,t)}announced(e=Me()){return this.#i.announced(e)}consume(e){return this.#i.consume(e)}announcedBroadcast(e){return new zt({connection:this,path:e})}async#d(){if(this.#r)try{for(;await eo.decodeMaybe(this.#r.reader,this.#e););}finally{console.debug("session stream closed")}}async#l(){let e=await me.open(this.#t);try{await e.u53(ro.Setup);let t=await Kw(this.#t,this.#e);await new ki({probe:t,origin:this.origin}).encode(e,this.#e),e.close()}catch(t){throw e.reset(t),t}}async#u(){for(;;){let e=await H.accept(this.#t);if(!e)break;this.#f(e).catch(t=>{e.writer.reset(t)}).finally(()=>{e.writer.close()})}}async#f(e){let t=await e.reader.u53();if(t===J.Session)throw new Error("duplicate session stream");if(t===J.Announce){let n=await on.decode(e.reader,this.#e);await this.#n.runAnnounce(n,e)}else if(t===J.Subscribe){let n=await mn.decode(e.reader,this.#e);await this.#n.runSubscribe(n,e)}else if(t===J.Fetch){let n=await dn.decode(e.reader,this.#e);await this.#n.runFetch(n,e)}else if(t===J.Track){let n=await wn.decode(e.reader,this.#e);await this.#n.runTrackInfo(n,e)}else if(t===J.Probe)await this.#n.runProbe(e);else if(t===J.Goaway){let n=await js.decode(e.reader,this.#e);console.info("received goaway:",n.uri)}else throw new Error(`unknown stream type: ${t.toString()}`)}async#p(){let e=new Br(this.#t);for(;;){let t=await e.next();if(!t)break;this.#m(t).then(()=>{t.stop(new Error("cancel"))}).catch(n=>{t.stop(n)})}}async#m(e){let t=await e.u53();if(t===ro.Group){let n=await ln.decode(e);await this.#i.runGroup(n,e)}else if(t===ro.Setup){let n=await ki.decode(e,this.#e);this.#s.set(n),this.#o.set(n.role)}else throw new Error(`unknown stream type: ${t.toString()}`)}async stats(){return Is(this.#t)}get closed(){return this.#t.closed.then(()=>{})}};async function Kw(r,e){let t=r.getStats;if(typeof t!="function")return Ce.None;let n;try{n=await t.call(r)}catch{return Ce.None}let i=St(e)?n.smoothedRtt:void 0;return n.estimatedSendRate!=null||i!=null?Ce.Report:Ce.None}async function so(r,e,t){let n=new TextEncoder,i=new ue;i.setBytes(de.Implementation,n.encode(t)),xr(i);let s=Ts();ot.intoSetup(i,s,e);let a=new yr({parameters:i}),[o,c]=await Promise.all([Qw(r,e,a),Jw(r,e)]);return{control:new H({writer:o,reader:c.reader}),solicit:c.solicit,cluster:{self:s,peer:c.cluster}}}async function Qw(r,e,t){let n=await me.open(r,{version:e});return await n.u53(yr.id),await t.encode(n,e),n}async function Jw(r,e){let t=r.incomingUnidirectionalStreams.getReader(),n=await t.read();if(t.releaseLock(),n.done)throw new Error("no incoming uni stream for SETUP");let i=new ae(n.value,void 0,e),s=await i.u53();if(s!==yr.id)throw new Error(`unexpected stream type on setup uni: 0x${s.toString(16)}`);let a=await yr.decode(i,e);return{reader:i,solicit:Ar(a.parameters),cluster:ot.fromSetup(a.parameters,e)}}async function tg(r,e,t){let n=r.protocol,i=t?.discovery??!0;if(n===te.DRAFT_19)return ic(r,e,m.DRAFT_19,i);if(n===te.DRAFT_18)return ic(r,e,m.DRAFT_18,i);if(n===te.DRAFT_17)return ic(r,e,m.DRAFT_17,i);if(n===te.DRAFT_16)return nf(r,e,m.DRAFT_16,i);if(n===te.DRAFT_15)return nf(r,e,m.DRAFT_15,i);if(n===Zs)return new ze({url:e,quic:r,version:S.DRAFT_06,discovery:i});if(n===sn)return new ze({url:e,quic:r,version:S.DRAFT_05,discovery:i});if(n===nn)return new ze({url:e,quic:r,version:S.DRAFT_04,discovery:i});if(n===rn)return new ze({url:e,quic:r,version:S.DRAFT_03,discovery:i});if(n===tn||n===""||n===void 0)return rg(r,e,t);throw new Error(`unsupported WebTransport protocol: ${n}`)}async function ic(r,e,t,n){let{control:i,solicit:s,cluster:a}=await so(r,t,"moq-lite-js");return new At({discovery:n,client:!1,url:e,quic:r,control:i,solicit:s,cluster:a,maxRequestId:0n,version:t})}async function nf(r,e,t,n){let i=await H.accept(r);if(!i)throw new Error("no incoming bidi stream for SETUP");let s=await i.reader.u53();if(s!==J.ClientCompat)throw new Error(`unexpected client message type: 0x${s.toString(16)}`);let a=await br.decode(i.reader,t);await i.writer.u53(J.ServerCompat);let o=new TextEncoder,c=new ue;c.setVarint(de.MaxRequestId,42069n),c.setBytes(de.Implementation,o.encode("moq-lite-js")),xr(c),await new vr({version:t,parameters:c}).encode(i.writer,t);let d=42069n;return new At({discovery:n,client:!1,url:e,quic:r,control:i,maxRequestId:d,version:t,solicit:Ar(a.parameters)})}async function rg(r,e,t){let n=t?.discovery??!0,i=m.DRAFT_14,s=await H.accept(r);if(!s)throw new Error("no incoming bidi stream for SETUP");let a=await s.reader.u53();if(a!==J.ClientCompat)throw new Error(`unexpected client message type: 0x${a.toString(16)}`);let o=await br.decode(s.reader,i),c=[...Object.values(S),...Object.values(m)],u;if(t?.version!==void 0)u=t.version;else{let h=o.versions.find(p=>c.includes(p));if(h===void 0)throw new Error(`no common version found; client offered: ${o.versions.map(p=>p.toString(16)).join(", ")}`);u=h}await s.writer.u53(J.ServerCompat);let d=new TextEncoder,f=new ue;if(f.setVarint(de.MaxRequestId,42069n),f.setBytes(de.Implementation,d.encode("moq-lite-js")),xr(f),await new vr({version:u,parameters:f}).encode(s.writer,i),Object.values(S).includes(u))return new ze({url:e,quic:r,version:u,session:s,discovery:n});if(Object.values(m).includes(u)){let h=o.parameters.getVarint(de.MaxRequestId)??0n;return new At({discovery:n,client:!1,url:e,quic:r,control:s,maxRequestId:h,version:u,solicit:Ar(o.parameters)})}else throw new Error(`unsupported version: ${u.toString(16)}`)}var of=Bm(sf(),1);function ng(r){let t=of.default.getParser(r).satisfies({firefox:">=153.0",safari:"<0"});return t===void 0?!0:t}function oo(){return typeof globalThis.WebTransport>"u"?!1:typeof navigator>"u"?!0:ng(navigator.userAgent)}function oc(r){if(r=r.startsWith("0x")?r.slice(2):r,r.length%2)throw new Error("invalid hex string length");let e=r.match(/.{2}/g);if(!e)throw new Error("invalid hex string format");return new Uint8Array(e.map(t=>parseInt(t,16)))}var sg=500,og=["mediaoverquic.com"];function ag(r){return!og.some(e=>r.hostname.endsWith(e))}var af=new Set,cg=new AbortController().signal;async function ac(r,e){let t=e?.signal??cg;t.throwIfAborted();let{promise:n,resolve:i}=Promise.withResolvers(),s=()=>i();t.addEventListener("abort",s,{once:!0});let a=ug(r,e,n);try{let o=await Promise.race([a,n.then(()=>{})]);if(o&&!t.aborted)return o;throw a.then(c=>c.close()).catch(()=>{}),t.reason}finally{t.removeEventListener("abort",s)}}async function ug(r,e,t){let n=e?.discovery??ag(r);if(e?.transport){let f=e.transport;return t.then(()=>f.close()),cf(r,f,n)}let{promise:i,resolve:s}=Promise.withResolvers(),a=Promise.race([i,t]),o=oo()?hg(r,a,e?.webtransport):void 0,c=!o||af.has(r.toString())?0:e?.websocket?.delay??sg,u=e?.websocket?.enabled!==!1?pg(e?.websocket?.url??r,c,a):void 0;if(!u&&!o)throw new Error("no transport available; WebTransport not supported and WebSocket is disabled");let d=await Promise.any(o!==void 0?u!==void 0?[u,o]:[o]:[u]);if(s(),!d)throw new Error("no transport available");return t.then(()=>d.close()),d instanceof di?(console.warn(r.toString(),"connected via WebSocket"),af.add(r.toString())):console.debug(r.toString(),"connected via WebTransport"),await cf(r,d,n)}async function cf(r,e,t){let n=e.protocol||void 0;console.debug(r.toString(),"negotiated ALPN:",n??"(none)");let i,s=n===te.DRAFT_19?m.DRAFT_19:n===te.DRAFT_18?m.DRAFT_18:n===te.DRAFT_17?m.DRAFT_17:void 0;if(s!==void 0)return await dg(r,e,s,t);if(n===te.DRAFT_16)i=m.DRAFT_16;else if(n===te.DRAFT_15)i=m.DRAFT_15;else{if(n===Zs)return new ze({url:r,quic:e,version:S.DRAFT_06,discovery:t});if(n===sn)return new ze({url:r,quic:e,version:S.DRAFT_05,discovery:t});if(n===nn)return new ze({url:r,quic:e,version:S.DRAFT_04,discovery:t});if(n===rn)return new ze({url:r,quic:e,version:S.DRAFT_03,discovery:t});if(n===tn||n===""||n===void 0)i=m.DRAFT_14;else throw new Error(`unsupported WebTransport protocol: ${n}`)}let a=await H.open(e);await a.writer.u53(J.ClientCompat);let o=new TextEncoder,c=new ue;c.setVarint(de.MaxRequestId,42069n),c.setBytes(de.Implementation,o.encode("moq-lite-js")),xr(c),await new br({versions:i===m.DRAFT_16?[m.DRAFT_16]:i===m.DRAFT_15?[m.DRAFT_15]:[S.DRAFT_02,S.DRAFT_01,m.DRAFT_14],parameters:c}).encode(a.writer,i);let d=await a.reader.u53();if(d!==J.ServerCompat)throw new Error(`unsupported server message type: ${d.toString()}`);let f=await vr.decode(a.reader,i);if(Object.values(S).includes(f.version))return new ze({url:r,quic:e,version:f.version,session:a,discovery:t});if(Object.values(m).includes(f.version)){let l=f.parameters.getVarint(de.MaxRequestId)??0n;return new At({discovery:t,client:!0,url:r,quic:e,control:a,maxRequestId:l,version:f.version,solicit:Ar(f.parameters)})}else throw new Error(`unsupported server version: ${f.version.toString()}`)}async function dg(r,e,t,n){let{control:i,solicit:s,cluster:a}=await so(e,t,"moq-lite-js");return new At({discovery:n,client:!0,url:r,quic:e,control:i,solicit:s,cluster:a,maxRequestId:0n,version:t})}function lg(r){let e=r.match(/-----BEGIN CERTIFICATE-----([\s\S]+?)-----END CERTIFICATE-----/);if(!e)throw new Error("invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor");let t=atob(e[1].replace(/\s+/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}async function uf(r){let e=typeof r=="string"?lg(r):r,t=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(t)}async function fg(r){let e=[];for(let t of r?.serverCertificateHashes??[]){let n=typeof t.value=="string"?oc(t.value):t.value;e.push({algorithm:t.algorithm??"sha-256",value:n})}return r?.serverCertificate!==void 0&&e.push({algorithm:"sha-256",value:await uf(r.serverCertificate)}),e.length>0?e:void 0}async function hg(r,e,t){let n=r,{serverCertificate:i,serverCertificateHashes:s,...a}=t??{},o={allowPooling:!1,congestionControl:"low-latency",protocols:[sn,nn,rn,tn,te.DRAFT_19,te.DRAFT_18,te.DRAFT_17,te.DRAFT_16,te.DRAFT_15],...a},c=await fg(t)??[];if(r.protocol==="http:"){let f=new URL(r);f.pathname="/certificate.sha256",f.search="",console.debug(f.toString(),"performing an insecure fingerprint fetch; use https:// in production");let l=await Promise.race([fetch(f),e]);if(!l)return;let h=await Promise.race([l.text(),e]);if(h===void 0)return;c.push({algorithm:"sha-256",value:oc(h)}),n=new URL(r),n.protocol="https:"}c.length>0&&(o.serverCertificateHashes=c);let u=new WebTransport(n,o);if(u.closed.catch(()=>{}),!await Promise.race([u.ready.then(()=>!0),e])){u.close();return}return u}async function pg(r,e,t){let n=new Promise(c=>setTimeout(c,e));if(!await Promise.race([t,n.then(()=>!0)]))return;let s={[sn]:null,[nn]:null,[rn]:null,[tn]:null,[te.DRAFT_18]:"qmux-01",[te.DRAFT_17]:null,[te.DRAFT_16]:null,[te.DRAFT_15]:null},a=new di(r,{protocols:Object.keys(s),versions:s});if(!await Promise.race([a.ready.then(()=>!0),t])){a.close();return}return a}var mg=1e4,cc=class{url;enabled;status=new A("disconnected");established=new A(void 0);probe;webtransport;websocket;discovery;delay;#e=new j;closed;#t;#r;#n;#i;#s=new A(0);#o=new A(!1);#a;constructor(e){this.url=A.from(e?.url),this.enabled=A.from(e?.enabled??!1),this.delay=e?.delay??{initial:1e3,multiplier:2,max:5e3},this.webtransport=e?.webtransport,this.websocket=e?.websocket,this.discovery=e?.discovery,this.closed=new Promise((t,n)=>{this.#t=t,this.#r=n}),this.closed.catch(()=>{}),typeof window<"u"&&typeof document<"u"&&(this.#e.event(window,"pagehide",()=>this.#o.set(!0)),this.#e.event(window,"pageshow",()=>this.#o.set(!1)),this.#e.event(window,"unload",()=>this.#o.set(!0)),this.#e.event(document,"visibilitychange",()=>{document.hidden||this.#o.set(!1)})),this.probe=this.#e.computed(t=>{let n=t.get(this.established);return n&&t.get(n.probe)}),this.#a=this.#e.computed(t=>t.get(this.url)?.href),this.#e.run(this.#c.bind(this))}#c(e){e.get(this.#s);let t=e.get(this.#o);if(!e.get(this.enabled)||t)return;let i=e.get(this.#a);if(!i)return;let s=new URL(i);e.set(this.status,"connecting","disconnected");let a=e.abort;e.spawn(async()=>{let o;try{let c=await ac(s,{websocket:this.websocket,webtransport:this.webtransport,discovery:this.discovery,signal:a});if(e.cleanup(()=>c.close()),a.aborted||(e.set(this.established,c),e.set(this.status,"connected","disconnected"),o=performance.now(),!await Promise.race([e.cancel,c.closed.then(()=>!0)])))return;console.warn("connection closed, reconnecting"),this.#d(e,o)}catch(c){if(a.aborted)return;console.warn("connection error:",c),this.#d(e,o,c)}})}#d(e,t,n){this.established.set(void 0),this.status.set("disconnected"),t!==void 0&&performance.now()-t>=this.delay.initial&&(this.#n=void 0,this.#i=void 0);let i=performance.now(),s=this.delay.timeout??mg;if(this.#n??=this.delay.initial,this.#i??=s>0?i+s:Number.POSITIVE_INFINITY,i>=this.#i){console.warn("reconnect timed out"),this.#r(n===void 0?new Error("reconnect timed out"):L(n));return}let a=Math.min(this.#n*(.5+Math.random()/2),this.#i-i);this.#n=Math.min(this.#n*this.delay.multiplier,this.delay.max);let o=this.#s.peek()+1;e.timer(()=>this.#s.update(c=>Math.max(c,o)),a)}announced(e=Me()){let t=new Pt(e),n=t.consume(),i=!1;n.closed.then(()=>{i=!0});let s=new j;return s.run(a=>{let o=a.get(this.established);if(!o||!o.discovery)return;let c=o.announced(e);a.cleanup(()=>c.close());let u=new Set;a.spawn(async()=>{try{for(;;){let d=await Promise.race([a.cancel,c.next()]);if(!d)break;d.active?u.add(d.path):u.delete(d.path),t.append(d)}}catch{}finally{if(!i)for(let d of u)t.append({path:d,active:!1})}})}),this.#e.cleanup(()=>s.close()),n.closed.then(()=>s.close()),n}announcedBroadcast(e){return new zt({connection:this.established,path:e})}async stats(){return this.established.peek()?.stats()}close(){this.#e.close(),this.#t()}};function Ke(r){return r==="real-time"||typeof r=="number"?{min:r,max:r}:{min:r.min??"real-time",max:r.max??"real-time"}}function uc(r,e){return r===e?r:{min:r,max:e}}var wg=E.Milli(20),df=E.Milli(100),lf=class ff{in;#e={reference:new A(void 0),buffer:new A(E.Milli.zero),jitter:new A(df),timestamp:new A(void 0),buffered:new A(!1),maxBuffer:new A(E.Milli.zero)};out=this.#e;#t;#r=new Map;#n;#i=new j;constructor(e){this.in={latency:N(e?.latency??"real-time"),connection:N(e?.connection),audio:N(e?.audio),video:N(e?.video)},this.#t=Promise.withResolvers(),this.#i.run(this.#a.bind(this)),this.#i.run(this.#c.bind(this)),this.#i.run(this.#s.bind(this))}#s(e){let{max:t}=Ke(e.get(this.in.latency)),n=e.get(this.#e.buffer);t==="real-time"?(this.#e.buffered.set(!1),this.#e.maxBuffer.set(n)):(this.#e.buffered.set(t>n),this.#e.maxBuffer.set(E.Milli.max(t,n)))}#o(){let{max:e}=Ke(this.in.latency.peek()),t=this.#e.buffer.peek();return e==="real-time"?t:E.Milli.max(e,t)}#a(e){let{min:t}=Ke(e.get(this.in.latency));if(typeof t=="number"){this.#n=void 0,this.#e.jitter.set(t);return}let n=e.get(this.in.connection),i=n&&e.get(n.probe).rtt;if(i!==void 0){this.#n=this.#n===void 0?i:Math.min(this.#n,i);let s=E.Milli(Math.max(wg,this.#n*1.25));this.#e.jitter.set(s);return}this.#n=void 0,this.#e.jitter.set(df)}#c(e){let t=e.get(this.#e.jitter),n=e.get(this.in.video)??E.Milli.zero,i=e.get(this.in.audio)??E.Milli.zero,s=E.Milli.add(E.Milli.max(n,i),t);this.#e.buffer.set(s),this.#t.resolve(),this.#t=Promise.withResolvers()}received(e,t=""){this.#e.timestamp.update(u=>u===void 0||e>u?e:u);let n=E.Milli.now(),i=E.Milli.sub(n,e),s=this.#e.reference.peek();if(s===void 0){this.#d(i);return}let a=this.#e.buffer.peek(),o=E.Milli.add(E.Milli.sub(s,i),a);if(o<0){let u=this.#r.get(t);u?(u.count++,u.maxMs=Math.max(u.maxMs,-o)):this.#r.set(t,{count:1,maxMs:-o})}else{let u=this.#r.get(t);if(u){let d=t?`sync[${t}]`:"sync",f=ff.#l(u.maxMs);console.debug(`${d}: ${u.count} late frame(s), max ${f} behind`),this.#r.delete(t)}}if(i>=s)return;let c=this.#o();o<=c||this.#d(E.Milli.add(i,E.Milli.sub(c,a)))}#d(e){this.#e.reference.set(e),this.#t.resolve(),this.#t=Promise.withResolvers()}reset(){this.#e.reference.set(void 0),this.#r.clear(),this.#t.resolve(),this.#t=Promise.withResolvers()}now(){let e=this.#e.reference.peek();if(e!==void 0)return E.Milli.sub(E.Milli.sub(E.Milli.now(),e),this.#e.buffer.peek())}async wait(e){if(this.#e.reference.peek()===void 0)throw Error("reference not set; call received() first");for(;;){let t=E.Milli.now(),n=E.Milli.sub(t,e),i=this.#e.reference.peek();if(i===void 0)return;let s=E.Milli.add(E.Milli.sub(i,n),this.#e.buffer.peek());if(s<=0||s<5)return;let a=new Promise(o=>setTimeout(o,s)).then(()=>!0);if(await Promise.race([this.#t.promise,a]))return}}static#l(e){if(e=Math.round(e),e<1e3)return`${e}ms`;let t=e/1e3;if(t<60)return`${Math.round(t*10)/10}s`;let n=t/60;return`${Math.round(n*10)/10}m`}close(){this.#i.close()}};var gg=["legacy","cmaf","loc"],yg=Vt(xs({kind:q().check(ks(r=>!gg.includes(r),{message:"recognized container kind must match its own schema"}))}),Ot(r=>({kind:"unknown",raw:r}))),uo=Es(it([sl("kind",[K({kind:Zr("legacy")}),K({kind:Zr("cmaf"),init:tl()}),K({kind:Zr("loc")})]),yg]),{kind:"legacy"});function dc(r){return r.kind!=="unknown"}var lo=q().check(va(/^([0-9a-fA-F]{2})*$/,"expected hex"));var rP=we().check(Aa(),As(),ti(255)).brand("u8"),fe=we().check(Aa(),As(),ti(Number.MAX_SAFE_INTEGER)).brand("u53");function Qe(r){return fe.parse(r)}var fo=Vt(q(),Ot(W.normalizeRelative));var ho=K({track:q(),timescale:Es(fe,Qe(1e3)),wall:F(fe)});var bg=K({name:q()}),hf=K({broadcast:F(fo),codec:q(),container:uo,description:F(lo),sampleRate:fe,numberOfChannels:fe,bitrate:F(fe),jitter:F(fe),timeline:F(ho)}),pf=it([K({renditions:Ss(q(),hf)}),Vt(K({track:bg,config:hf}),Ot(r=>({renditions:{[r.track.name]:r.config}})))]);var mf="catalog.json",_f="catalog.json.z",lc=["hang","msf"],wf="hang";function gf(r){for(let e of lc)if(r.endsWith(`.${e}`))return e}var po={catalog:100,audio:80,video:60};var vg=K({name:q()}),yf=K({broadcast:F(fo),codec:q(),container:uo,description:F(lo),codedWidth:F(fe),codedHeight:F(fe),displayAspectWidth:F(fe),displayAspectHeight:F(fe),framerate:F(we()),bitrate:F(fe),stalled:F(pr()),optimizeForLatency:F(pr()),jitter:F(fe),timeline:F(ho)}),bf=it([K({renditions:Ss(q(),yf),display:F(K({width:fe,height:fe})),rotation:F(we()),flip:F(pr())}),Vt(qr(K({track:vg,config:yf})),Ot(r=>{let e=r[0]?.config;return{renditions:Object.fromEntries(r.map(t=>[t.track.name,t.config])),display:e?.displayAspectWidth!==void 0&&e?.displayAspectHeight!==void 0?{width:e.displayAspectWidth,height:e.displayAspectHeight}:void 0,rotation:void 0,flip:void 0}}))]);var vf=xs({video:F(bf),audio:F(pf)});var Mi={};ke(Mi,{Format:()=>fc,Producer:()=>hc});var Ag=8,xf=16,xg=6,Af=1e6,fc=class{decode(e){let[t,n]=ie.decode(e);if(n.byteLength<t)throw new Error("loc: properties_length exceeds frame size");let i=n.subarray(0,t),s=n.subarray(t),a,o,c=0,u=!0,d=i;for(;d.byteLength>0;){let[h,p]=ie.decode(d),_=u?h:c+h;if(u=!1,c=_,d=p,_%2===0){let[w,y]=ie.decode(d);if(d=y,_===xf||_===xg)a=w;else if(_===Ag){if(w===0)throw new Error("loc: timescale property must be non-zero");o=w}}else{let[w,y]=ie.decode(d);if(y.byteLength<w)throw new Error("loc: property length exceeds remaining bytes");d=y.subarray(w)}}if(a===void 0)throw new Error("loc: frame missing required timestamp property");let f=o??Af,l=Math.round(a*Af/f);return[{payload:s,timestamp:l,keyframe:!1}]}},hc=class{#e;#t;constructor(e){this.#e=e}encode(e,t,n){if(n)this.#t?.close(),this.#t=this.#e.appendGroup();else if(!this.#t)throw new Error("must start with a keyframe");this.#t?.writeFrame({payload:this.#r(e,t),timestamp:E.Timestamp.fromMicros(t)})}#r(e,t){let n=ie.encode(xf),i=ie.encode(t),s=n.byteLength+i.byteLength,a=ie.encode(s),o=e.byteLength,c=a.byteLength+s+o,u=new Uint8Array(c),d=0;u.set(a,d),d+=a.byteLength,u.set(n,d),d+=n.byteLength,u.set(i,d),d+=i.byteLength;let f=u.subarray(d);return e instanceof Uint8Array?f.set(e):e.copyTo(f),u}close(e){this.#t?.close(),this.#e.close(e)}};var kt={};ke(kt,{Format:()=>wo,createAudioInitSegment:()=>Qg,createVideoInitSegment:()=>Kg,decodeDataSegment:()=>vc,decodeInitSegment:()=>Lg,decodeTimestamp:()=>Bg,encodeDataSegment:()=>i0});function mc(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}var Sg="utf-16",pc="utf-16be",Sf="utf-16le",bn="utf-8";function _c(r,e={}){let t;mc(r)?t=new DataView(r):t=new DataView(r.buffer,r.byteOffset,r.byteLength);let n=0,{encoding:i}=e;if(!i){let u=t.getUint8(0),d=t.getUint8(1);u==239&&d==187&&t.getUint8(2)==191?(i=bn,n=3):u==254&&d==255?(i=pc,n=2):u==255&&d==254?(i=Sf,n=2):i=bn}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(t);let{byteLength:s}=t,a=i!==pc,o="",c;for(;n<s;){switch(i){case bn:if(c=t.getUint8(n),c<128)n++;else if(c>=194&&c<=223)if(n+1<s){let u=t.getUint8(n+1);u>=128&&u<=191?(c=(c&31)<<6|u&63,n+=2):n++}else n++;else if(c>=224&&c<=239)if(n+2<=s-1){let u=t.getUint8(n+1),d=t.getUint8(n+2);u>=128&&u<=191&&d>=128&&d<=191?(c=(c&15)<<12|(u&63)<<6|d&63,n+=3):n++}else n++;else if(c>=240&&c<=244)if(n+3<=s-1){let u=t.getUint8(n+1),d=t.getUint8(n+2),f=t.getUint8(n+3);u>=128&&u<=191&&d>=128&&d<=191&&f>=128&&f<=191?(c=(c&7)<<18|(u&63)<<12|(d&63)<<6|f&63,n+=4):n++}else n++;else n++;break;case pc:case Sg:case Sf:c=t.getUint16(n,a),n+=2;break}o+=String.fromCodePoint(c)}return o}function Ef(r){return new TextEncoder().encode(r)}function Eg(r){return{writers:r?.writers??{}}}var kg=["dinf","edts","grpl","mdia","meco","mfra","minf","moof","moov","mvex","schi","sinf","stbl","strk","traf","trak","tref","udta","vttc"];function zf(r){return"boxes"in r||kg.includes(r.type)}var kf="utf8",Re="uint",vn="template",Tf="string",Mf="int",If="data";var he=class{constructor(r,e){this.writeUint=(t,n)=>{let{dataView:i,cursor:s}=this;switch(n){case 1:i.setUint8(s,t);break;case 2:i.setUint16(s,t);break;case 3:{let a=(t&16776960)>>8,o=t&255;i.setUint16(s,a),i.setUint8(s+2,o);break}case 4:i.setUint32(s,t);break;case 8:{let a=Math.floor(t/Math.pow(2,32)),o=t-a*Math.pow(2,32);i.setUint32(s,a),i.setUint32(s+4,o);break}}this.cursor+=n},this.writeInt=(t,n)=>{let{dataView:i,cursor:s}=this;switch(n){case 1:i.setInt8(s,t);break;case 2:i.setInt16(s,t);break;case 4:i.setInt32(s,t);break;case 8:let a=Math.floor(t/Math.pow(2,32)),o=t-a*Math.pow(2,32);i.setUint32(s,a),i.setUint32(s+4,o);break}this.cursor+=n},this.writeString=t=>{for(let n=0,i=t.length;n<i;n++)this.writeUint(t.charCodeAt(n),1)},this.writeTerminatedString=t=>{for(let n=0,i=t.length;n<i;n++)this.writeUint(t.charCodeAt(n),1);this.writeUint(0,1)},this.writeUtf8TerminatedString=t=>{let n=Ef(t);new Uint8Array(this.dataView.buffer).set(n,this.cursor),this.cursor+=n.length,this.writeUint(0,1)},this.writeBytes=t=>{Array.isArray(t)||(t=[t]);for(let n of t)new Uint8Array(this.dataView.buffer).set(n,this.cursor),this.cursor+=n.length},this.writeArray=(t,n,i,s)=>{let a=n===Re?this.writeUint:n===vn?this.writeTemplate:this.writeInt;for(let o=0;o<s;o++)a(t[o]??0,i)},this.writeTemplate=(t,n)=>{let s=Math.round(t*Math.pow(2,n===4?16:8));this.writeUint(s,n)},this.writeBoxHeader=(t,n)=>{n>4294967295?(this.writeUint(1,4),this.writeString(t),this.writeUint(n,8)):(this.writeUint(n,4),this.writeString(t))},this.dataView=new DataView(new ArrayBuffer(e)),this.cursor=0,this.writeBoxHeader(r,e)}get buffer(){return this.dataView.buffer}get byteLength(){return this.dataView.byteLength}get byteOffset(){return this.dataView.byteOffset}writeFullBox(r,e){this.writeUint(r,1),this.writeUint(e,3)}};function Rf(r,e){return Array.from(r,t=>Mg(t,e))}function wc(r,e){let t=Rf(r,e);return{bytes:t,size:t.reduce((n,i)=>n+i.byteLength,0)}}function Tg(r,e){let{bytes:n,size:i}=wc(r.boxes,e),s=8+i,a=new he(r.type,s);return a.writeBytes(n),a}function Mg(r,e){let t=null;if("type"in r){let{type:n}=r,i=e.writers?.[n];if(i?t=i(r,e):zf(r)?t=Tg(r,e):"view"in r&&(t=r.view),!t)throw new Error(`No writer found for box type: ${n}`)}if("buffer"in r&&(t=r),!t)throw new Error("Invalid box");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Ig(r,e,t){let n=t>0?t:r.byteLength-(e-r.byteOffset);return new Uint8Array(r.buffer,e,Math.max(n,0))}function Pg(r,e,t){let n=NaN,i=e-r.byteOffset;switch(t){case 1:n=r.getInt8(i);break;case 2:n=r.getInt16(i);break;case 4:n=r.getInt32(i);break;case 8:let s=r.getInt32(i),a=r.getInt32(i+4);n=s*Math.pow(2,32)+a;break}return n}function Er(r,e,t){let n=e-r.byteOffset,i=NaN,s,a;switch(t){case 1:i=r.getUint8(n);break;case 2:i=r.getUint16(n);break;case 3:s=r.getUint16(n),a=r.getUint8(n+2),i=(s<<8)+a;break;case 4:i=r.getUint32(n);break;case 8:s=r.getUint32(n),a=r.getUint32(n+4),i=s*Math.pow(2,32)+a;break}return i}function Pf(r,e,t){let n="";for(let i=0;i<t;i++){let s=Er(r,e+i,1);n+=String.fromCharCode(s)}return n}function zg(r,e,t){let n=t/2;return Er(r,e,n)+Er(r,e+n,n)/Math.pow(2,n)}function Rg(r,e){let t="",n=e;for(;n-r.byteOffset<r.byteLength;){let i=Er(r,n,1);if(i===0)break;t+=String.fromCharCode(i),n++}return t}function Fg(r,e){let t=r.byteLength-(e-r.byteOffset);return t>0?_c(new DataView(r.buffer,e,t),{encoding:bn}):""}function Dg(r,e){let t=r.byteLength-(e-r.byteOffset),n="";if(t>0){let i=new DataView(r.buffer,e,t),s=0;for(;s<t&&i.getUint8(s)!==0;s++);n=_c(new DataView(r.buffer,e,s),{encoding:bn})}return n}var Cg=class Ff{constructor(e,t){this.truncated=!1,this.slice=(n,i)=>{let s=new Ff(new DataView(this.dataView.buffer,n,i),this.config),a=this.offset-n,o=i-a;return this.offset+=o,s.jump(a),s},this.read=(n,i=0)=>{let{dataView:s,offset:a}=this,o,c=i;switch(n){case Re:o=Er(s,a,i);break;case Mf:o=Pg(s,a,i);break;case vn:o=zg(s,a,i);break;case Tf:i===-1?(o=Rg(s,a),c=o.length+1):o=Pf(s,a,i);break;case If:o=Ig(s,a,i),c=o.length;break;case kf:i===-1?(o=Dg(s,a),c=o.length+1):o=Fg(s,a);break;default:o=-1}return this.offset+=c,o},this.readUint=n=>this.read(Re,n),this.readInt=n=>this.read(Mf,n),this.readString=n=>this.read(Tf,n),this.readTemplate=n=>this.read(vn,n),this.readData=n=>this.read(If,n),this.readUtf8=n=>this.read(kf,n),this.readFullBox=()=>({version:this.readUint(1),flags:this.readUint(3)}),this.readArray=(n,i,s)=>{let a=[];for(let o=0;o<s;o++)a.push(this.read(n,i));return a},this.jump=n=>{this.offset+=n},this.readBox=()=>{let{dataView:n,offset:i}=this,s=0,a=Er(n,i,4),o=Pf(n,i+4,4),c={size:a,type:o};s+=8,c.size===1&&(c.largesize=Er(n,i+s,8),s+=8);let u=c.size===0?this.bytesRemaining:c.largesize??c.size;if(this.cursor+u>n.byteLength)throw this.truncated=!0,new Error("Truncated box");return this.jump(s),o==="uuid"&&(c.usertype=this.readArray("uint",1,16)),c.view=this.slice(i,u),c},this.readBoxes=(n=-1)=>{let i=[];for(let s of this)if(i.push(s),n>0&&i.length>=n)break;return i},this.readEntries=(n,i)=>{let s=[];for(let a=0;a<n;a++)s.push(i());return s},this.dataView=mc(e)?new DataView(e):e instanceof DataView?e:new DataView(e.buffer,e.byteOffset,e.byteLength),this.offset=this.dataView.byteOffset,this.config=t||{}}get buffer(){return this.dataView.buffer}get byteOffset(){return this.dataView.byteOffset}get byteLength(){return this.dataView.byteLength}get cursor(){return this.offset-this.dataView.byteOffset}get done(){return this.cursor>=this.dataView.byteLength||this.truncated}get bytesRemaining(){return this.dataView.byteLength-this.cursor}*[Symbol.iterator](){let{readers:e={}}=this.config;for(;!this.done;)try{let t=this.readBox(),{type:n,view:i}=t,s=e[n]||e[n.trim()];if(s&&Object.assign(t,s(i,n)),zf(t)&&!t.boxes){let a=[];for(let o of i)a.push(o);t.boxes=a}yield t}catch(t){if(t instanceof Error&&t.message==="Truncated box")break;throw t}}};function mo(r,e){let t=[];for(let n of new Cg(r,e))t.push(n);return t}function Df(r,e){return Rf(r,Eg(e))}function Og(r,e){let{readArray:t,readUint:n,readTemplate:i,readBoxes:s}=e;return{type:r,reserved1:t(Re,1,6),dataReferenceIndex:n(2),reserved2:t(Re,4,2),channelcount:n(2),samplesize:n(2),preDefined:n(2),reserved3:n(2),samplerate:i(4),boxes:s()}}function gc(r,e){let{readArray:t,readUint:n,readInt:i,readTemplate:s,readBoxes:a}=e;return{type:r,reserved1:t(Re,1,6),dataReferenceIndex:n(2),preDefined1:n(2),reserved2:n(2),preDefined2:t(Re,4,3),width:n(2),height:n(2),horizresolution:s(4),vertresolution:s(4),reserved3:n(4),frameCount:n(2),compressorName:t(Re,1,32),depth:n(2),preDefined3:i(2),boxes:a()}}function yc(r){return gc("avc1",r)}function Cf(r){return gc("hev1",r)}function Of(r){return gc("hvc1",r)}function Vf(r){return{type:"mdat",data:r.readData(-1)}}function Lf(r){let{version:e,flags:t}=r.readFullBox(),n=r.readUint(e==1?8:4),i=r.readUint(e==1?8:4),s=r.readUint(4),a=r.readUint(e==1?8:4),o=r.readUint(2);return{type:"mdhd",version:e,flags:t,creationTime:n,modificationTime:i,timescale:s,duration:a,language:String.fromCharCode((o>>10&31)+96,(o>>5&31)+96,(o&31)+96),preDefined:r.readUint(2)}}function Uf(r){return{type:"mfhd",...r.readFullBox(),sequenceNumber:r.readUint(4)}}function Bf(r){return Og("mp4a",r)}function $f(r){let{version:e,flags:t}=r.readFullBox(),n=r.readUint(4);return{type:"stsd",version:e,flags:t,entryCount:n,entries:r.readBoxes(n)}}function Nf(r){let{version:e,flags:t}=r.readFullBox();return{type:"tfdt",version:e,flags:t,baseMediaDecodeTime:r.readUint(e==1?8:4)}}function qf(r){let{version:e,flags:t}=r.readFullBox();return{type:"tfhd",version:e,flags:t,trackId:r.readUint(4),baseDataOffset:t&1?r.readUint(8):void 0,sampleDescriptionIndex:t&2?r.readUint(4):void 0,defaultSampleDuration:t&8?r.readUint(4):void 0,defaultSampleSize:t&16?r.readUint(4):void 0,defaultSampleFlags:t&32?r.readUint(4):void 0}}function Zf(r){let{version:e,flags:t}=r.readFullBox(),n=e===1?8:4;return{type:"tkhd",version:e,flags:t,creationTime:r.readUint(n),modificationTime:r.readUint(n),trackId:r.readUint(4),reserved1:r.readUint(4),duration:r.readUint(n),reserved2:r.readArray(Re,4,2),layer:r.readUint(2),alternateGroup:r.readUint(2),volume:r.readTemplate(2),reserved3:r.readUint(2),matrix:r.readArray(vn,4,9),width:r.readTemplate(4),height:r.readTemplate(4)}}function Gf(r){return{type:"trex",...r.readFullBox(),trackId:r.readUint(4),defaultSampleDescriptionIndex:r.readUint(4),defaultSampleDuration:r.readUint(4),defaultSampleSize:r.readUint(4),defaultSampleFlags:r.readUint(4)}}function jf(r){let{version:e,flags:t}=r.readFullBox(),n=r.readUint(4),i,s;t&1&&(i=r.readInt(4)),t&4&&(s=r.readUint(4));let a=r.readEntries(n,()=>{let o={};return t&256&&(o.sampleDuration=r.readUint(4)),t&512&&(o.sampleSize=r.readUint(4)),t&1024&&(o.sampleFlags=r.readUint(4)),t&2048&&(o.sampleCompositionTimeOffset=e===1?r.readInt(4):r.readUint(4)),o});return{type:"trun",version:e,flags:t,sampleCount:n,dataOffset:i,firstSampleFlags:s,samples:a}}function Wf(r,e){let s=r.entries.length,{bytes:a,size:o}=wc(r.entries,e),c=new he("dref",16+o);return c.writeFullBox(r.version,r.flags),c.writeUint(s,4),c.writeBytes(a),c}function Hf(r){let i=r.compatibleBrands.length*4,s=new he("ftyp",16+i);s.writeString(r.majorBrand),s.writeUint(r.minorVersion,4);for(let a of r.compatibleBrands)s.writeString(a);return s}function Xf(r){let a=r.name.length+1,o=new he("hdlr",32+a);return o.writeFullBox(r.version,r.flags),o.writeUint(r.preDefined,4),o.writeString(r.handlerType),o.writeArray(r.reserved,Re,4,3),o.writeTerminatedString(r.name),o}function Yf(r){let e=new he("mdat",8+r.data.length);return e.writeBytes(r.data),e}function Kf(r){let e=r.version===1?8:4,t=8,n=4,i=e*3,s=new he("mdhd",t+n+i+4+2+2);s.writeFullBox(r.version,r.flags),s.writeUint(r.creationTime,e),s.writeUint(r.modificationTime,e),s.writeUint(r.timescale,4),s.writeUint(r.duration,e);let a=r.language.length>=3?(r.language.charCodeAt(0)-96&31)<<10|(r.language.charCodeAt(1)-96&31)<<5|r.language.charCodeAt(2)-96&31:0;return s.writeUint(a,2),s.writeUint(r.preDefined,2),s}function Qf(r){let e=new he("mfhd",16);return e.writeFullBox(r.version,r.flags),e.writeUint(r.sequenceNumber,4),e}function Jf(r){let e=r.version===1?8:4,t=8,n=4,i=e*3,s=new he("mvhd",t+n+i+4+4+2+2+8+36+24+4);return s.writeFullBox(r.version,r.flags),s.writeUint(r.creationTime,e),s.writeUint(r.modificationTime,e),s.writeUint(r.timescale,4),s.writeUint(r.duration,e),s.writeTemplate(r.rate,4),s.writeTemplate(r.volume,2),s.writeUint(r.reserved1,2),s.writeArray(r.reserved2,Re,4,2),s.writeArray(r.matrix,vn,4,9),s.writeArray(r.preDefined,Re,4,6),s.writeUint(r.nextTrackId,4),s}function eh(r){let e=new he("smhd",16);return e.writeFullBox(r.version,r.flags),e.writeUint(r.balance,2),e.writeUint(r.reserved,2),e}function th(r,e){let s=r.entries.length,{bytes:a,size:o}=wc(r.entries,e),c=new he("stsd",16+o);return c.writeFullBox(r.version,r.flags),c.writeUint(s,4),c.writeBytes(a),c}function rh(r){let i=r.entryCount*8,s=new he("stts",16+i);s.writeFullBox(r.version,r.flags),s.writeUint(r.entryCount,4);for(let a of r.entries)s.writeUint(a.sampleCount,4),s.writeUint(a.sampleDelta,4);return s}function nh(r){let e=r.version===1?8:4,t=8,n=4,i=e,s=new he("tfdt",t+n+i);return s.writeFullBox(r.version,r.flags),s.writeUint(r.baseMediaDecodeTime,e),s}function ih(r){let i=r.flags&1?8:0,s=r.flags&2?4:0,a=r.flags&8?4:0,o=r.flags&16?4:0,c=r.flags&32?4:0,u=new he("tfhd",16+i+s+a+o+c);return u.writeFullBox(r.version,r.flags),u.writeUint(r.trackId,4),r.flags&1&&u.writeUint(r.baseDataOffset??0,8),r.flags&2&&u.writeUint(r.sampleDescriptionIndex??0,4),r.flags&8&&u.writeUint(r.defaultSampleDuration??0,4),r.flags&16&&u.writeUint(r.defaultSampleSize??0,4),r.flags&32&&u.writeUint(r.defaultSampleFlags??0,4),u}function sh(r){let e=r.version===1?8:4,t=8,n=4,i=e*3,s=new he("tkhd",t+n+i+4+4+8+2+2+2+2+36+4+4);return s.writeFullBox(r.version,r.flags),s.writeUint(r.creationTime,e),s.writeUint(r.modificationTime,e),s.writeUint(r.trackId,4),s.writeUint(r.reserved1,4),s.writeUint(r.duration,e),s.writeArray(r.reserved2,Re,4,2),s.writeUint(r.layer,2),s.writeUint(r.alternateGroup,2),s.writeTemplate(r.volume,2),s.writeUint(r.reserved3,2),s.writeArray(r.matrix,vn,4,9),s.writeTemplate(r.width,4),s.writeTemplate(r.height,4),s}function oh(r){let e=new he("trex",32);return e.writeFullBox(r.version,r.flags),e.writeUint(r.trackId,4),e.writeUint(r.defaultSampleDescriptionIndex,4),e.writeUint(r.defaultSampleDuration,4),e.writeUint(r.defaultSampleSize,4),e.writeUint(r.defaultSampleFlags,4),e}function ah(r){let i=r.flags&1?4:0,s=r.flags&4?4:0,a=0;r.flags&256&&(a+=4),r.flags&512&&(a+=4),r.flags&1024&&(a+=4),r.flags&2048&&(a+=4);let o=a*r.sampleCount,c=new he("trun",16+i+s+o);c.writeFullBox(r.version,r.flags),c.writeUint(r.sampleCount,4),r.flags&1&&c.writeUint(r.dataOffset??0,4),r.flags&4&&c.writeUint(r.firstSampleFlags??0,4);for(let u of r.samples)r.flags&256&&c.writeUint(u.sampleDuration??0,4),r.flags&512&&c.writeUint(u.sampleSize??0,4),r.flags&1024&&c.writeUint(u.sampleFlags??0,4),r.flags&2048&&c.writeUint(u.sampleCompositionTimeOffset??0,4);return c}function ch(r){let n=r.location.length+1,i=new he("url ",12+n);return i.writeFullBox(r.version,r.flags),i.writeTerminatedString(r.location),i}function uh(r){let e=new he("vmhd",20);return e.writeFullBox(r.version,r.flags),e.writeUint(r.graphicsmode,2),e.writeArray(r.opcolor,Re,2,3),e}var Vg={avc1:yc,avc3:yc,hvc1:Of,hev1:Cf,mp4a:Bf,stsd:$f,mdhd:Lf,tkhd:Zf,trex:Gf},lh={mfhd:Uf,tfhd:qf,tfdt:Nf,trun:jf,mdat:Vf};function ct(r,e){for(let t of r){if(e(t))return t;let n=t.boxes;if(n&&Array.isArray(n)){let i=ct(n,e);if(i)return i}}}function bc(r){let e=new ArrayBuffer(r.byteLength);return new Uint8Array(e).set(r),e}function Xt(r){return e=>e.type===r}function Lg(r){let e=mo(bc(r),{readers:Vg}),t=ct(e,Xt("mdhd"));if(!t)throw new Error("No mdhd box found in init segment");let i=ct(e,Xt("tkhd"))?.trackId??1,s=ct(e,Xt("stsd"));if(!s?.entries||s.entries.length===0)throw new Error("No stsd box found in init segment");let a=s.entries[0],o=Ug(a),c=ct(e,u=>u.type==="trex"&&u.trackId===i);return{description:o,timescale:t.timescale,trackId:i,defaultSampleDuration:c?.defaultSampleDuration??0,defaultSampleSize:c?.defaultSampleSize??0,defaultSampleFlags:c?.defaultSampleFlags??0}}function Ug(r){if(!(!r.boxes||!Array.isArray(r.boxes)))for(let e of r.boxes){if(e instanceof Uint8Array){if(e.length>8){let n=String.fromCharCode(e[4],e[5],e[6],e[7]);if(n==="avcC"||n==="hvcC"||n==="dOps")return new Uint8Array(e.slice(8));if(n==="esds")return dh(new Uint8Array(e.slice(8)))}continue}let t=e.type;if(t==="avcC"||t==="hvcC"||t==="dOps"){if(e.view){let n=e.view,i=8,s=n.byteOffset+i,a=e.size-i;return new Uint8Array(n.buffer,s,a)}if(e.data instanceof Uint8Array)return new Uint8Array(e.data);if(e.raw instanceof Uint8Array)return new Uint8Array(e.raw.slice(8))}if(t==="esds"){let n;if(e.view){let i=e.view,s=8;n=new Uint8Array(i.buffer,i.byteOffset+s,e.size-s)}else e.data instanceof Uint8Array?n=new Uint8Array(e.data):e.raw instanceof Uint8Array&&(n=new Uint8Array(e.raw.slice(8)));if(n)return dh(n)}}}function dh(r){let e=4;for(;e<r.length;){let t=r[e++],n=0;for(let i=0;i<4&&e<r.length;i++){let s=r[e++];if(n=n<<7|s&127,(s&128)===0)break}if(t===5)return e+n<=r.length?new Uint8Array(r.buffer,r.byteOffset+e,n):void 0;t===3?e+=3:t===4?e+=13:e+=n}}function Bg(r,e){let t=mo(bc(r),{readers:lh});return(ct(t,Xt("tfdt"))?.baseMediaDecodeTime??0)*1e6/e.timescale}function vc(r,e){let t=mo(bc(r),{readers:lh}),i=ct(t,Xt("tfdt"))?.baseMediaDecodeTime??0,s=ct(t,Xt("tfhd")),a=s?.defaultSampleDuration??e.defaultSampleDuration,o=s?.defaultSampleSize??e.defaultSampleSize,c=s?.defaultSampleFlags??e.defaultSampleFlags,u=ct(t,Xt("trun"));if(!u)throw new Error("No trun box found in data segment");let d=ct(t,Xt("mdat"));if(!d)throw new Error("No mdat box found in data segment");let f=d.data;if(!f)throw new Error("No data in mdat box");let l=[],h=0,p=i;for(let _=0;_<u.sampleCount;_++){let w=u.samples[_]??{},y=w.sampleSize??o,b=w.sampleDuration??a;if(y<=0)throw new Error(`Invalid sample size ${y} for sample ${_} in trun`);if(b<0)throw new Error(`Invalid sample duration ${b} for sample ${_} in trun`);if(h+y>f.length)throw new Error(`Sample ${_} would overflow mdat: offset=${h}, size=${y}, mdatLength=${f.length}`);let g=_===0&&u.firstSampleFlags!==void 0?u.firstSampleFlags:w.sampleFlags??c,x=w.sampleCompositionTimeOffset??0,P=new Uint8Array(f.slice(h,h+y));h+=y;let I=p+x,M=Math.round(I*1e6/e.timescale),k=Math.round(b*1e6/e.timescale),T=g===0||(g&65536)===0;l.push({data:P,timestamp:M,keyframe:T,duration:k}),p+=b}return l}var hh={96e3:0,88200:1,64e3:2,48e3:3,44100:4,32e3:5,24e3:6,22050:7,16e3:8,12e3:9,11025:10,8e3:11,7350:12},RP=Object.freeze(Object.keys(hh).map(Number).sort((r,e)=>r-e));var fh=2;function $g(r){return r>=1&&r<=6?r:r===8?7:2}function ph(r,e){let t=$g(e),n=hh[r];if(n!==void 0){let a=fh<<3|n>>1,o=(n&1)<<7|t<<3;return new Uint8Array([a,o])}let i=0n;i|=BigInt(fh)<<35n,i|=0xfn<<31n,i|=BigInt(r)<<7n,i|=BigInt(t)<<3n;let s=new Uint8Array(5);for(let a=0;a<s.length;a++)s[a]=Number(i>>BigInt((s.length-1-a)*8)&0xffn);return s}var Ze={};ke(Ze,{fromBytes:()=>Zg,toBytes:()=>Ii});var qg=/^[0-9a-fA-F]*$/;function Ii(r){if(r=r.startsWith("0x")?r.slice(2):r,r.length%2)throw new Error("invalid hex string length");if(!qg.test(r)){let t=r.search(/[^0-9a-fA-F]/);throw new Error(`invalid hex character '${r[t]}' at position ${t}`)}let e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=Number.parseInt(r.slice(t*2,t*2+2),16);return e}function Zg(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}var kr={};ke(kr,{DEFAULT_SAMPLE_RATE:()=>Gg,SAMPLE_RATES:()=>xc,pickRate:()=>Wg,preSkip:()=>Hg,supportsRate:()=>jg,toDOps:()=>Sc});var Gg=48e3,xc=Object.freeze([8e3,12e3,16e3,24e3,48e3]);function jg(r){return xc.includes(r)}function Wg(r){return xc.find(e=>e>=r)??48e3}var Ac=new TextEncoder().encode("OpusHead");function mh(r){let e=0,t=!1;if(r.length>=Ac.length&&Ac.every((n,i)=>r[i]===n))e=Ac.length,t=!0;else if(r[0]===1)t=!0;else if(r[0]!==0)throw new Error("invalid Opus decoder description");if(r.length-e<11)throw new Error("Opus decoder description must contain at least 11 bytes");return{offset:e,littleEndian:t}}function Hg(r){let{offset:e,littleEndian:t}=mh(r);return new DataView(r.buffer,r.byteOffset+e,11).getUint16(2,t)}function Sc(r){let{offset:e,littleEndian:t}=mh(r);if(!t)return r.slice(e);let n=new DataView(r.buffer,r.byteOffset+e,11),i=r.slice(e),s=new DataView(i.buffer);return i[0]=0,i[1]=n.getUint8(1),s.setUint16(2,n.getUint16(2,!0),!1),s.setUint32(4,n.getUint32(4,!0),!1),s.setInt16(8,n.getInt16(8,!0),!1),i[10]=n.getUint8(10),i}var _o=[65536,0,0,0,65536,0,0,0,1073741824],Xg={ftyp:Hf,mvhd:Jf,tkhd:sh,mdhd:Kf,hdlr:Xf,vmhd:uh,smhd:eh,"url ":ch,dref:Wf,stsd:th,stts:rh,trex:oh,mfhd:Qf,tfhd:ih,tfdt:nh,trun:ah,mdat:Yf};function Pi(r){return Df(r,{writers:Xg})}function Ec(r,e,t,n){let i=12+n.length,s=new Uint8Array(i),a=new DataView(s.buffer);return a.setUint32(0,i,!1),s[4]=r.charCodeAt(0),s[5]=r.charCodeAt(1),s[6]=r.charCodeAt(2),s[7]=r.charCodeAt(3),a.setUint32(8,e<<24|t,!1),s.set(n,12),s}function _h(){let r=new Uint8Array(4);return Ec("stsc",0,0,r)}function wh(){let r=new Uint8Array(8);return Ec("stsz",0,0,r)}function gh(){let r=new Uint8Array(4);return Ec("stco",0,0,r)}function Yg(r,e,t){let n=8+t.length,s=8+(78+n),a=new Uint8Array(s),o=new DataView(a.buffer),c=0;return o.setUint32(c,s,!1),c+=4,a[c++]=97,a[c++]=118,a[c++]=99,a[c++]=49,c+=6,o.setUint16(c,1,!1),c+=2,o.setUint16(c,0,!1),c+=2,o.setUint16(c,0,!1),c+=2,c+=12,o.setUint16(c,r,!1),c+=2,o.setUint16(c,e,!1),c+=2,o.setUint32(c,4718592,!1),c+=4,o.setUint32(c,4718592,!1),c+=4,o.setUint32(c,0,!1),c+=4,o.setUint16(c,1,!1),c+=2,c+=32,o.setUint16(c,24,!1),c+=2,o.setUint16(c,65535,!1),c+=2,o.setUint32(c,n,!1),c+=4,a[c++]=97,a[c++]=118,a[c++]=99,a[c++]=67,a.set(t,c),a}function Kg(r){let{codedWidth:e,codedHeight:t,description:n}=r;if(!e||!t||!n)throw new Error("Missing required fields to create video init segment");let i=1e6,s=1,a={type:"ftyp",majorBrand:"isom",minorVersion:512,compatibleBrands:["isom","iso6","mp41"]},o={type:"mvhd",version:0,flags:0,creationTime:0,modificationTime:0,timescale:i,duration:0,rate:65536,volume:256,reserved1:0,reserved2:[0,0],matrix:_o,preDefined:[0,0,0,0,0,0],nextTrackId:s+1},c={type:"tkhd",version:0,flags:3,creationTime:0,modificationTime:0,trackId:s,reserved1:0,duration:0,reserved2:[0,0],layer:0,alternateGroup:0,volume:0,reserved3:0,matrix:_o,width:e*65536,height:t*65536},u={type:"mdhd",version:0,flags:0,creationTime:0,modificationTime:0,timescale:i,duration:0,language:"und",preDefined:0},d={type:"hdlr",version:0,flags:0,preDefined:0,handlerType:"vide",reserved:[0,0,0],name:"VideoHandler"},f={type:"vmhd",version:0,flags:1,graphicsmode:0,opcolor:[0,0,0]},p={type:"dinf",boxes:[{type:"dref",version:0,flags:0,entryCount:1,entries:[{type:"url ",version:0,flags:1,location:""}]}]},w={type:"stsd",version:0,flags:0,entryCount:1,entries:[Yg(e,t,Ii(n))]},y={type:"stts",version:0,flags:0,entryCount:0,entries:[]},b=_h(),g=wh(),x=gh(),Ae=Pi([a,{type:"moov",boxes:[o,{type:"trak",boxes:[c,{type:"mdia",boxes:[u,d,{type:"minf",boxes:[f,p,{type:"stbl",boxes:[w,y,b,g,x]}]}]}]},{type:"mvex",boxes:[{type:"trex",version:0,flags:0,trackId:s,defaultSampleDescriptionIndex:1,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}]}]),ur=Ae.reduce((_t,It)=>_t+It.byteLength,0),mt=new Uint8Array(ur),Je=0;for(let _t of Ae)mt.set(new Uint8Array(_t.buffer,_t.byteOffset,_t.byteLength),Je),Je+=_t.byteLength;return mt}function Qg(r){let{sampleRate:e,numberOfChannels:t,description:n,codec:i}=r,s=1e6,a=1,o={type:"ftyp",majorBrand:"isom",minorVersion:512,compatibleBrands:["isom","iso6","mp41"]},c={type:"mvhd",version:0,flags:0,creationTime:0,modificationTime:0,timescale:s,duration:0,rate:65536,volume:256,reserved1:0,reserved2:[0,0],matrix:_o,preDefined:[0,0,0,0,0,0],nextTrackId:a+1},u={type:"tkhd",version:0,flags:3,creationTime:0,modificationTime:0,trackId:a,reserved1:0,duration:0,reserved2:[0,0],layer:0,alternateGroup:0,volume:256,reserved3:0,matrix:_o,width:0,height:0},d={type:"mdhd",version:0,flags:0,creationTime:0,modificationTime:0,timescale:s,duration:0,language:"und",preDefined:0},f={type:"hdlr",version:0,flags:0,preDefined:0,handlerType:"soun",reserved:[0,0,0],name:"SoundHandler"},l={type:"smhd",version:0,flags:0,balance:0,reserved:0},_={type:"dinf",boxes:[{type:"dref",version:0,flags:0,entryCount:1,entries:[{type:"url ",version:0,flags:1,location:""}]}]},y={type:"stsd",version:0,flags:0,entryCount:1,entries:[Jg(i,e,t,n)]},b={type:"stts",version:0,flags:0,entryCount:0,entries:[]},g=_h(),x=wh(),P=gh(),ur=Pi([o,{type:"moov",boxes:[c,{type:"trak",boxes:[u,{type:"mdia",boxes:[d,f,{type:"minf",boxes:[l,_,{type:"stbl",boxes:[y,b,g,x,P]}]}]}]},{type:"mvex",boxes:[{type:"trex",version:0,flags:0,trackId:a,defaultSampleDescriptionIndex:1,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}]}]),mt=ur.reduce((It,Rm)=>It+Rm.byteLength,0),Je=new Uint8Array(mt),_t=0;for(let It of ur)Je.set(new Uint8Array(It.buffer,It.byteOffset,It.byteLength),_t),_t+=It.byteLength;return Je}function Jg(r,e,t,n){if(r.startsWith("mp4a"))return e0(e,t,n);if(r==="opus")return t0(e,t,n);throw new Error(`Unsupported audio codec: ${r}`)}function e0(r,e,t){let n=r0(r,e,t),s=8+(28+n.length),a=new Uint8Array(s),o=new DataView(a.buffer),c=0;return o.setUint32(c,s,!1),c+=4,a[c++]=109,a[c++]=112,a[c++]=52,a[c++]=97,c+=6,o.setUint16(c,1,!1),c+=2,c+=8,o.setUint16(c,e,!1),c+=2,o.setUint16(c,16,!1),c+=2,o.setUint16(c,0,!1),c+=2,o.setUint16(c,0,!1),c+=2,o.setUint32(c,r*65536,!1),c+=4,a.set(n,c),a}function t0(r,e,t){let n=n0(e,r,t),s=8+(28+n.length),a=new Uint8Array(s),o=new DataView(a.buffer),c=0;return o.setUint32(c,s,!1),c+=4,a[c++]=79,a[c++]=112,a[c++]=117,a[c++]=115,c+=6,o.setUint16(c,1,!1),c+=2,c+=8,o.setUint16(c,e,!1),c+=2,o.setUint16(c,16,!1),c+=2,o.setUint16(c,0,!1),c+=2,o.setUint16(c,0,!1),c+=2,o.setUint32(c,r*65536,!1),c+=4,a.set(n,c),a}function r0(r,e,t){let n=t?Ii(t):ph(r,e),i=n.length,s=15+i,a=5+s+3,o=14+a,c=new Uint8Array(o),u=new DataView(c.buffer),d=0;return u.setUint32(d,o,!1),d+=4,c[d++]=101,c[d++]=115,c[d++]=100,c[d++]=115,u.setUint32(d,0,!1),d+=4,c[d++]=3,c[d++]=a,u.setUint16(d,0,!1),d+=2,c[d++]=0,c[d++]=4,c[d++]=s,c[d++]=64,c[d++]=21,c[d++]=0,c[d++]=0,c[d++]=0,u.setUint32(d,0,!1),d+=4,u.setUint32(d,0,!1),d+=4,c[d++]=5,c[d++]=i,c.set(n,d),d+=i,c[d++]=6,c[d++]=1,c[d++]=2,c}function n0(r,e,t){if(t){let o=Sc(Ii(t)),c=8+o.length,u=new Uint8Array(c);return new DataView(u.buffer).setUint32(0,c,!1),u[4]=100,u[5]=79,u[6]=112,u[7]=115,u.set(o,8),u}let n=19,i=new Uint8Array(n),s=new DataView(i.buffer),a=0;return s.setUint32(a,n,!1),a+=4,i[a++]=100,i[a++]=79,i[a++]=112,i[a++]=115,i[a++]=0,i[a++]=r,s.setUint16(a,312,!1),a+=2,s.setUint32(a,e,!1),a+=4,s.setInt16(a,0,!1),a+=2,i[a++]=0,i}function i0(r){let{data:e,timestamp:t,duration:n,keyframe:i,sequence:s,trackId:a=1}=r,o=i?33554432:16842752,c={type:"mfhd",version:0,flags:0,sequenceNumber:s},u={type:"tfhd",version:0,flags:131072,trackId:a},d={type:"tfdt",version:1,flags:0,baseMediaDecodeTime:t},f={type:"trun",version:0,flags:1793,sampleCount:1,dataOffset:0,samples:[{sampleDuration:n,sampleSize:e.byteLength,sampleFlags:o}]},h={type:"moof",boxes:[c,{type:"traf",boxes:[u,d,f]}]},p=Pi([h]),_=0;for(let k of p)_+=k.byteLength;f.dataOffset=_+8;let w=Pi([h]);_=0;for(let k of w)_+=k.byteLength;let y=new ArrayBuffer(e.byteLength),b=new Uint8Array(y);b.set(e);let x=Pi([{type:"mdat",data:b}]),P=0;for(let k of x)P+=k.byteLength;let I=new Uint8Array(_+P),M=0;for(let k of w)I.set(new Uint8Array(k.buffer,k.byteOffset,k.byteLength),M),M+=k.byteLength;for(let k of x)I.set(new Uint8Array(k.buffer,k.byteOffset,k.byteLength),M),M+=k.byteLength;return I}var wo=class{#e;constructor(e){this.#e=e}decode(e){return vc(e,this.#e).map(t=>({payload:t.data,timestamp:t.timestamp,keyframe:t.keyframe,duration:t.duration}))}};var kc=class{prevMax;group;timestamp;constructor(e,t,n){this.prevMax=e,this.group=t,this.timestamp=n}bySequence(e){if(e<=this.prevMax)return!0;if(e>=this.group)return!1}isStale(e,t){return this.bySequence(e)??t>=this.timestamp}},Tc=class{liveEdge;boundary;discontinuity=0},s0=E.Micro.fromMilli(1);function yh(r,e){return r!==void 0&&e!==void 0&&e<=E.Micro.add(r,s0)}function o0(r,e){return e===void 0?!1:e.consumer.sequence===r.consumer.sequence+1||yh(r.end,e.frames.at(0)?.timestamp)}var Yt=class{#e;#t;#r;#n=[];#i;#s;#o;#a=!1;#c=new Tc;#d;#l=new A([]);buffered=this.#l;#u=new j;constructor(e,t){this.#e=e,this.#t=t.format,this.#r=N(t.latency??E.Milli.zero),this.#u.spawn(this.#f.bind(this)),this.#u.cleanup(()=>{this.#e.close();for(let n of this.#n)n.consumer.close();this.#n.length=0})}async#f(){for(;;){let e=await this.#e.recvGroup();if(!e)break;this.#i===void 0&&(this.#i=e.sequence);let t;if(this.#c.boundary){let i=this.#c.boundary.bySequence(e.sequence);i===void 0?t=!1:i?t=!0:t=e.sequence<this.#i}else t=e.sequence<this.#i;if(t){console.warn(`skipping old group: track=${this.#e.name} ${e.sequence}`),e.close();continue}let n={consumer:e,frames:[],empty:!0};this.#n.push(n),this.#n.sort((i,s)=>i.consumer.sequence-s.consumer.sequence),this.#u.spawn(this.#p.bind(this,n))}}async#p(e){try{let t=0;for(;;){let n=await e.consumer.readFrame();if(!n)break;e.empty=!1;let i=this.#t.decode(n.payload);for(let s of i){let a=this.#t.end?.(s)!==void 0,o={payload:s.payload,timestamp:s.timestamp,keyframe:!a&&t===0?!0:s.keyframe,duration:s.duration};a||t++,e.frames.push(o),(e.latest===void 0||o.timestamp>e.latest)&&(e.latest=o.timestamp);let c=o.timestamp+(o.duration??0);(e.end===void 0||c>e.end)&&(e.end=c),this.#_();let u=!1;if(e.consumer.sequence!==this.#i){if(this.#T(e))return;this.#g(e),this.#x(),u=this.#v()}(u||e.consumer.sequence===this.#i||e===this.#n[0])&&(this.#d?.(),this.#d=void 0)}}}catch{this.#a=!0}finally{if(e.done=!0,e.consumer.sequence===this.#i){this.#m(e);let t=this.#n[this.#n.indexOf(e)+1];this.#i=o0(e,t)?t.consumer.sequence:e.consumer.sequence+1}this.#_(),this.#d?.(),this.#d=void 0,e.consumer.close()}}#m(e){e.end!==void 0&&(this.#s=e.end)}#b(e){return this.#o===void 0?!1:e===this.#o||!this.#a}#x(){if(this.#i===void 0)return;let e=!1;for(;this.#n.length>=2;){let t=E.Micro.fromMilli(this.#r.peek()),n=this.#n[0];if(n.empty&&!n.consumer.done)break;let i,s;for(let o of this.#n){if(o.latest===void 0)continue;let c=o.frames.at(0)?.timestamp??o.latest;(i===void 0||c<i)&&(i=c),(s===void 0||o.latest>s)&&(s=o.latest)}if(i===void 0||s===void 0||s-i<=t)break;this.#n.shift(),this.#i=this.#n[0]?.consumer.sequence,console.warn(`skipping slow group: track=${this.#e.name} ${n.consumer.sequence} -> ${this.#i}`),n.empty&&this.#S(),n.consumer.close(),n.frames.length=0,e=!0,this.#a=!0}e&&(this.#_(),this.#d?.(),this.#d=void 0)}#v(){if(this.#i===void 0)return!1;let e=this.#n[0];if(!e||e.consumer.sequence!==this.#i||e.done||e.frames.length>0||e.end===void 0)return!1;let t=this.#n[1],n=t?.frames.at(0)?.timestamp;return!t||n===void 0||e.end<n?!1:(this.#n.shift(),console.warn(`skipping covered group: ${e.consumer.sequence} -> ${t.consumer.sequence}`),this.#m(e),this.#i=t.consumer.sequence,e.consumer.close(),e.frames.length=0,this.#_(),!0)}#g(e){if(this.#i===void 0)return;let t=this.#c.liveEdge;if(t===void 0||e.consumer.sequence<=this.#i)return;let n=e.frames.at(0)?.timestamp;if(n===void 0||n>=t.timestamp)return;let i=new kc(t.group,e.consumer.sequence,n);this.#c.boundary=i,this.#c.discontinuity++,this.#a=!0,this.#n=this.#n.filter(s=>{let a=i.bySequence(s.consumer.sequence),o=s.frames.at(0),c=a??(o!==void 0&&i.isStale(s.consumer.sequence,o.timestamp));return c&&(s.consumer.close(),s.frames.length=0),!c}),console.warn(`buffer reset: track=${this.#e.name} group timestamps rewound (prevMax ${i.prevMax}, group ${i.group})`),this.#i=this.#n[0]?.consumer.sequence??i.group,this.#s=void 0,this.#o=void 0,this.#c.liveEdge={group:i.group,timestamp:n},this.#_(),this.#d?.(),this.#d=void 0}#T(e){let t=this.#c.boundary;if(!t)return!1;let n=e.frames.at(0);return n===void 0||!t.isStale(e.consumer.sequence,n.timestamp)?!1:(this.#n=this.#n.filter(i=>i!==e),e.consumer.close(),e.frames.length=0,this.#a=!0,this.#_(),!0)}#h(){if(!(this.#i===void 0||this.#c.liveEdge===void 0))for(let e of[...this.#n].reverse()){if(e.consumer.sequence<=this.#i)break;this.#g(e)}}async next(){for(;;){if(this.#h(),this.#i!==void 0&&this.#n.length>0){let n=this.#n[0];n.consumer.sequence>this.#i&&(n.empty&&n.consumer.done||yh(this.#s,n.frames.at(0)?.timestamp))&&(this.#i=n.consumer.sequence)}if(this.#n.length>0&&this.#i!==void 0&&this.#n[0].consumer.sequence<=this.#i){let n=this.#n[0].frames.shift();if(n){let i=this.#n[0].consumer.sequence,s=this.#b(i),a=this.#t.end?.(n);if(a!==void 0)return this.#_(),{frame:void 0,group:i,discontinuity:this.#c.discontinuity,continuous:s,end:a};i!==this.#o&&(this.#a=!1),this.#o=i;let o=this.#c.liveEdge;return(o===void 0||n.timestamp>o.timestamp)&&(this.#c.liveEdge={group:i,timestamp:n.timestamp}),this.#_(),{frame:n,group:i,discontinuity:this.#c.discontinuity,continuous:s}}if(this.#i>this.#n[0].consumer.sequence||this.#n[0].done){this.#n[0].consumer.sequence===this.#i&&(this.#m(this.#n[0]),this.#i+=1);let i=this.#n.shift();if(i){let s=i.consumer.sequence;return i.empty&&this.#S(),this.#_(),{frame:void 0,group:s,discontinuity:this.#c.discontinuity,continuous:this.#b(s)}}}if(this.#v())continue}if(this.#d)throw new Error("multiple calls to next not supported");let e=this.#u.abort;if(e.aborted)return;let t=await new Promise(n=>{let i=()=>n(!0);e.addEventListener("abort",i,{once:!0}),this.#d=()=>{e.removeEventListener("abort",i),n(!1)}});if(this.#d=void 0,t)return}}#S(){this.#c.discontinuity++,this.#c.liveEdge=void 0,this.#c.boundary=void 0,this.#s=void 0,this.#o=void 0,this.#a=!0}#_(){let e=[],t;for(let n of this.#n){let i=n.frames.at(0);if(!i||n.latest===void 0)continue;let s=E.Milli.fromMicro(i.timestamp),a=E.Milli.fromMicro(n.latest),o=e.at(-1),c=t?.done&&t.consumer.sequence+1===n.consumer.sequence;o&&(o.end>=s||c)?o.end=E.Milli.max(o.end,a):e.push({start:s,end:a}),t=n}this.#l.set(e)}get discontinuity(){return this.#c.discontinuity}close(){this.#u.close()}};var zi={};ke(zi,{Format:()=>Mc,Producer:()=>Ic,encodeFrame:()=>bh});var Mc=class{end(e){return e.payload.byteLength===0?e.timestamp:void 0}decode(e){let[t,n]=ie.decode(e);return[{payload:n,timestamp:t,keyframe:!1}]}};function bh(r,e){let t=ie.encode(e),n=new Uint8Array(t.byteLength+r.byteLength);return n.set(t,0),r instanceof Uint8Array?n.set(r,t.byteLength):r.copyTo(n.subarray(t.byteLength)),n}var Ic=class{#e;#t;#r;constructor(e,t={}){this.#e=e,this.#r=t.timeline}encode(e,t,n){if(n)this.#t?.close(),this.#t=this.#e.appendGroup(),this.#r?.record(this.#t.sequence,t);else if(!this.#t)throw new Error("must start with a keyframe");this.#t?.writeFrame({payload:bh(e,t),timestamp:E.Timestamp.fromMicros(t)})}close(e){this.#e.close(e),this.#t?.close()}};function Kt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function vh(r,e){if(Kt(r)&&Kt(e)){let t={},n={value:!1};return Ah(r,e,t,n),{patch:t,forcedSnapshot:n.value}}return{patch:e,forcedSnapshot:!0}}function Ah(r,e,t,n){for(let i of Object.keys(r))i in e||(t[i]=null);for(let i of Object.keys(e)){let s=e[i],a=r[i];if(!(i in r&&Ri(a,s))){if(Kt(a)&&Kt(s)){let c={};Ah(a,s,c,n),Object.keys(c).length>0&&(t[i]=c);continue}s===null&&(n.value=!0),t[i]=s}}}function Pc(r,e){if(!Kt(e))return e;let t=Kt(r)?{...r}:{};for(let[n,i]of Object.entries(e))i===null?delete t[n]:t[n]=Pc(t[n],i);return t}function Ri(r,e){if(r===e)return!0;if(Array.isArray(r)&&Array.isArray(e))return r.length===e.length&&r.every((t,n)=>Ri(t,e[n]));if(Kt(r)&&Kt(e)){let t=Object.keys(r);return t.length!==Object.keys(e).length?!1:t.every(n=>n in e&&Ri(r[n],e[n]))}return!1}var Ro={};ke(Ro,{Consumer:()=>Po,Decoder:()=>Pn,Encoder:()=>zn,Producer:()=>zo});var a0=4,xh=0,Sh=1,c0=2;function kn(r){let e=r.length;for(;--e>=0;)r[e]=0}var u0=0,cp=1,d0=2,up=29,Kc=256,dp=286,xn=30,Qc=19,lp=573,Oi=15,zc=16,l0=7,Jc=256,fp=16,hp=17,pp=18,qc=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Ao=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),f0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),mp=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),h0=512,Mt=new Array(288*2);kn(Mt);var Vi=new Array(xn*2);kn(Vi);var Ui=new Array(h0);kn(Ui);var Bi=new Array(256);kn(Bi);var eu=new Array(up);kn(eu);var xo=new Array(xn);kn(xo);var Rc=class{constructor(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}},_p,wp,gp,Fc=class{constructor(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}},yp=r=>r<256?Ui[r]:Ui[256+(r>>>7)],$i=(r,e)=>{r.pending_buf[r.pending++]=e&255,r.pending_buf[r.pending++]=e>>>8&255},Fe=(r,e,t)=>{r.bi_valid>zc-t?(r.bi_buf|=e<<r.bi_valid&65535,$i(r,r.bi_buf),r.bi_buf=e>>zc-r.bi_valid,r.bi_valid+=t-zc):(r.bi_buf|=e<<r.bi_valid&65535,r.bi_valid+=t)},dt=(r,e,t)=>{Fe(r,t[e*2],t[e*2+1])},bp=(r,e)=>{let t=0;do t|=r&1,r>>>=1,t<<=1;while(--e>0);return t>>>1},p0=r=>{r.bi_valid===16?($i(r,r.bi_buf),r.bi_buf=0,r.bi_valid=0):r.bi_valid>=8&&(r.pending_buf[r.pending++]=r.bi_buf&255,r.bi_buf>>=8,r.bi_valid-=8)},m0=(r,e)=>{let t=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,c=e.stat_desc.max_length,u,d,f,l,h,p,_=0;for(l=0;l<=Oi;l++)r.bl_count[l]=0;for(t[r.heap[r.heap_max]*2+1]=0,u=r.heap_max+1;u<lp;u++)d=r.heap[u],l=t[t[d*2+1]*2+1]+1,l>c&&(l=c,_++),t[d*2+1]=l,!(d>n)&&(r.bl_count[l]++,h=0,d>=o&&(h=a[d-o]),p=t[d*2],r.opt_len+=p*(l+h),s&&(r.static_len+=p*(i[d*2+1]+h)));if(_!==0){do{for(l=c-1;r.bl_count[l]===0;)l--;r.bl_count[l]--,r.bl_count[l+1]+=2,r.bl_count[c]--,_-=2}while(_>0);for(l=c;l!==0;l--)for(d=r.bl_count[l];d!==0;)f=r.heap[--u],!(f>n)&&(t[f*2+1]!==l&&(r.opt_len+=(l-t[f*2+1])*t[f*2],t[f*2+1]=l),d--)}},vp=(r,e,t)=>{let n=new Array(16),i=0,s,a;for(s=1;s<=Oi;s++)i=i+t[s-1]<<1,n[s]=i;for(a=0;a<=e;a++){let o=r[a*2+1];o!==0&&(r[a*2]=bp(n[o]++,o))}},_0=()=>{let r,e,t,n,i,s=new Array(16);for(t=0,n=0;n<up-1;n++)for(eu[n]=t,r=0;r<1<<qc[n];r++)Bi[t++]=n;for(Bi[t-1]=n,i=0,n=0;n<16;n++)for(xo[n]=i,r=0;r<1<<Ao[n];r++)Ui[i++]=n;for(i>>=7;n<xn;n++)for(xo[n]=i<<7,r=0;r<1<<Ao[n]-7;r++)Ui[256+i++]=n;for(e=0;e<=Oi;e++)s[e]=0;for(r=0;r<=143;)Mt[r*2+1]=8,r++,s[8]++;for(;r<=255;)Mt[r*2+1]=9,r++,s[9]++;for(;r<=279;)Mt[r*2+1]=7,r++,s[7]++;for(;r<=287;)Mt[r*2+1]=8,r++,s[8]++;for(vp(Mt,287,s),r=0;r<xn;r++)Vi[r*2+1]=5,Vi[r*2]=bp(r,5);_p=new Rc(Mt,qc,257,dp,Oi),wp=new Rc(Vi,Ao,0,xn,Oi),gp=new Rc(new Array(0),f0,0,Qc,l0)},Ap=r=>{let e;for(e=0;e<dp;e++)r.dyn_ltree[e*2]=0;for(e=0;e<xn;e++)r.dyn_dtree[e*2]=0;for(e=0;e<Qc;e++)r.bl_tree[e*2]=0;r.dyn_ltree[Jc*2]=1,r.opt_len=r.static_len=0,r.sym_next=r.matches=0},xp=r=>{r.bi_valid>8?$i(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},Eh=(r,e,t,n)=>{let i=e*2,s=t*2;return r[i]<r[s]||r[i]===r[s]&&n[e]<=n[t]},Dc=(r,e,t)=>{let n=r.heap[t],i=t<<1;for(;i<=r.heap_len&&(i<r.heap_len&&Eh(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!Eh(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},kh=(r,e,t)=>{let n,i,s=0,a,o;if(r.sym_next!==0)do n=r.pending_buf[r.sym_buf+s++]&255,n+=(r.pending_buf[r.sym_buf+s++]&255)<<8,i=r.pending_buf[r.sym_buf+s++],n===0?dt(r,i,e):(a=Bi[i],dt(r,a+Kc+1,e),o=qc[a],o!==0&&(i-=eu[a],Fe(r,i,o)),n--,a=yp(n),dt(r,a,t),o=Ao[a],o!==0&&(n-=xo[a],Fe(r,n,o)));while(s<r.sym_next);dt(r,Jc,e)},Zc=(r,e)=>{let t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems,a,o,c=-1,u;for(r.heap_len=0,r.heap_max=lp,a=0;a<s;a++)t[a*2]!==0?(r.heap[++r.heap_len]=c=a,r.depth[a]=0):t[a*2+1]=0;for(;r.heap_len<2;)u=r.heap[++r.heap_len]=c<2?++c:0,t[u*2]=1,r.depth[u]=0,r.opt_len--,i&&(r.static_len-=n[u*2+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Dc(r,t,a);u=s;do a=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Dc(r,t,1),o=r.heap[1],r.heap[--r.heap_max]=a,r.heap[--r.heap_max]=o,t[u*2]=t[a*2]+t[o*2],r.depth[u]=(r.depth[a]>=r.depth[o]?r.depth[a]:r.depth[o])+1,t[a*2+1]=t[o*2+1]=u,r.heap[1]=u++,Dc(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],m0(r,e),vp(t,c,r.bl_count)},Th=(r,e,t)=>{let n,i=-1,s,a=e[1],o=0,c=7,u=4;for(a===0&&(c=138,u=3),e[(t+1)*2+1]=65535,n=0;n<=t;n++)s=a,a=e[(n+1)*2+1],!(++o<c&&s===a)&&(o<u?r.bl_tree[s*2]+=o:s!==0?(s!==i&&r.bl_tree[s*2]++,r.bl_tree[fp*2]++):o<=10?r.bl_tree[hp*2]++:r.bl_tree[pp*2]++,o=0,i=s,a===0?(c=138,u=3):s===a?(c=6,u=3):(c=7,u=4))},Mh=(r,e,t)=>{let n,i=-1,s,a=e[1],o=0,c=7,u=4;for(a===0&&(c=138,u=3),n=0;n<=t;n++)if(s=a,a=e[(n+1)*2+1],!(++o<c&&s===a)){if(o<u)do dt(r,s,r.bl_tree);while(--o!==0);else s!==0?(s!==i&&(dt(r,s,r.bl_tree),o--),dt(r,fp,r.bl_tree),Fe(r,o-3,2)):o<=10?(dt(r,hp,r.bl_tree),Fe(r,o-3,3)):(dt(r,pp,r.bl_tree),Fe(r,o-11,7));o=0,i=s,a===0?(c=138,u=3):s===a?(c=6,u=3):(c=7,u=4)}},w0=r=>{let e;for(Th(r,r.dyn_ltree,r.l_desc.max_code),Th(r,r.dyn_dtree,r.d_desc.max_code),Zc(r,r.bl_desc),e=Qc-1;e>=3&&r.bl_tree[mp[e]*2+1]===0;e--);return r.opt_len+=3*(e+1)+5+5+4,e},g0=(r,e,t,n)=>{let i;for(Fe(r,e-257,5),Fe(r,t-1,5),Fe(r,n-4,4),i=0;i<n;i++)Fe(r,r.bl_tree[mp[i]*2+1],3);Mh(r,r.dyn_ltree,e-1),Mh(r,r.dyn_dtree,t-1)},y0=r=>{let e=4093624447,t;for(t=0;t<=31;t++,e>>>=1)if(e&1&&r.dyn_ltree[t*2]!==0)return xh;if(r.dyn_ltree[18]!==0||r.dyn_ltree[20]!==0||r.dyn_ltree[26]!==0)return Sh;for(t=32;t<Kc;t++)if(r.dyn_ltree[t*2]!==0)return Sh;return xh},Ih=!1,b0=r=>{Ih||(_0(),Ih=!0),r.l_desc=new Fc(r.dyn_ltree,_p),r.d_desc=new Fc(r.dyn_dtree,wp),r.bl_desc=new Fc(r.bl_tree,gp),r.bi_buf=0,r.bi_valid=0,Ap(r)},So=(r,e,t,n)=>{Fe(r,(u0<<1)+(n?1:0),3),xp(r),$i(r,t),$i(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},v0=r=>{Fe(r,cp<<1,3),dt(r,Jc,Mt),p0(r)},A0=(r,e,t,n)=>{let i,s,a=0;r.level>0?(r.strm.data_type===c0&&(r.strm.data_type=y0(r)),Zc(r,r.l_desc),Zc(r,r.d_desc),a=w0(r),i=r.opt_len+3+7>>>3,s=r.static_len+3+7>>>3,s<=i&&(i=s)):i=s=t+5,t+4<=i&&e!==-1?So(r,e,t,n):r.strategy===a0||s===i?(Fe(r,(cp<<1)+(n?1:0),3),kh(r,Mt,Vi)):(Fe(r,(d0<<1)+(n?1:0),3),g0(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),kh(r,r.dyn_ltree,r.dyn_dtree)),Ap(r),n&&xp(r)},Jt=(r,e,t)=>(r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[t*2]++:(r.matches++,e--,r.dyn_ltree[(Bi[t]+Kc+1)*2]++,r.dyn_dtree[yp(e)*2]++),r.sym_next===r.sym_end),Ni=(r,e,t,n)=>{let i=r&65535|0,s=r>>>16&65535|0,a=0;for(;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[n++]|0,s=s+i|0;while(--a);i%=65521,s%=65521}return i|s<<16|0},x0=()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r}return e},S0=new Uint32Array(x0()),pe=(r,e,t,n)=>{let i=S0,s=n+t;r^=-1;for(let a=n;a<s;a++)r=r>>>8^i[(r^e[a])&255];return r^-1},Pr={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var tu=2;var E0=9;var k0=573,$=3,Tr=258,lt=262,T0=32,Sn=42,ru=57,Gc=69,jc=73,Wc=91,Hc=103,Mr=113,Di=666,Ee=1,Tn=2,zr=3,Mn=4,M0=3,Ir=(r,e)=>(r.msg=Pr[e],e),Ph=r=>r*2-(r>4?9:0),Qt=r=>{let e=r.length;for(;--e>=0;)r[e]=0},I0=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)},nu=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask,Rr=(r,e)=>{let t;if(r.legacy_hash)t=r.ins_h=nu(r,r.ins_h,r.window[e+$-1]);else{let i=r.window,s=i[e]|i[e+1]<<8|i[e+2]<<16|i[e+3]<<24;t=r.ins_h=Math.imul(s,66521)+66521>>>16&r.hash_mask}let n=r.prev[e&r.w_mask]=r.head[t];return r.head[t]=e,n},Oe=r=>{let e=r.state,t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},Ve=(r,e)=>{A0(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Oe(r.strm)},B=(r,e)=>{r.pending_buf[r.pending++]=e},Fi=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=e&255},Xc=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=Ni(r.adler,e,i,t):r.state.wrap===2&&(r.adler=pe(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},Sp=(r,e)=>{let t=r.max_chain_length,n=r.strstart,i,s,a=r.prev_length,o=r.nice_match,c=r.strstart>r.w_size-lt?r.strstart-(r.w_size-lt):0,u=r.window,d=r.w_mask,f=r.prev,l=r.strstart+Tr,h=u[n+a-1],p=u[n+a];r.prev_length>=r.good_match&&(t>>=2),o>r.lookahead&&(o=r.lookahead);do if(i=e,!(u[i+a]!==p||u[i+a-1]!==h||u[i]!==u[n]||u[++i]!==u[n+1])){n+=2,i++;do;while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&n<l);if(s=Tr-(l-n),n=l-Tr,s>a){if(r.match_start=e,a=s,s>=o)break;h=u[n+a-1],p=u[n+a]}}while((e=f[e&d])>c&&--t!==0);return a<=r.lookahead?a:r.lookahead},En=r=>{let e=r.w_size,t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-lt)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),I0(r),n+=e),r.strm.avail_in===0)break;if(t=Xc(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.legacy_hash){if(r.lookahead+r.insert>=$)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=nu(r,r.ins_h,r.window[i+1]);r.insert&&(Rr(r,i),i++,r.insert--,!(r.lookahead+r.insert<$)););}else if(r.lookahead+r.insert>$)for(i=r.strstart-r.insert;r.insert&&(Rr(r,i),i++,r.insert--,!(r.lookahead+r.insert<=$)););}while(r.lookahead<lt&&r.strm.avail_in!==0)},Ep=(r,e)=>{let t=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,n,i,s,a=0,o=r.strm.avail_in;do{if(n=65535,s=r.bi_valid+42>>3,r.strm.avail_out<s||(s=r.strm.avail_out-s,i=r.strstart-r.block_start,n>i+r.strm.avail_in&&(n=i+r.strm.avail_in),n>s&&(n=s),n<t&&(n===0&&e!==4||e===0||n!==i+r.strm.avail_in)))break;a=e===4&&n===i+r.strm.avail_in?1:0,So(r,0,0,a),r.pending_buf[r.pending-4]=n,r.pending_buf[r.pending-3]=n>>8,r.pending_buf[r.pending-2]=~n,r.pending_buf[r.pending-1]=~n>>8,Oe(r.strm),i&&(i>n&&(i=n),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,n-=i),n&&(Xc(r.strm,r.strm.output,r.strm.next_out,n),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n)}while(a===0);return o-=r.strm.avail_in,o&&(o>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=o&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-o,r.strm.next_in),r.strstart),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.block_start=r.strstart),r.high_water<r.strstart&&(r.high_water=r.strstart),a?Mn:e!==0&&e!==4&&r.strm.avail_in===0&&r.strstart===r.block_start?Tn:(s=r.window_size-r.strstart,r.strm.avail_in>s&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,s+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),s>r.strm.avail_in&&(s=r.strm.avail_in),s&&(Xc(r.strm,r.window,r.strstart,s),r.strstart+=s,r.insert+=s>r.w_size-r.insert?r.w_size-r.insert:s),r.high_water<r.strstart&&(r.high_water=r.strstart),s=r.bi_valid+42>>3,s=r.pending_buf_size-s>65535?65535:r.pending_buf_size-s,t=s>r.w_size?r.w_size:s,i=r.strstart-r.block_start,(i>=t||(i||e===4)&&e!==0&&r.strm.avail_in===0&&i<=s)&&(n=i>s?s:i,a=e===4&&r.strm.avail_in===0&&n===i?1:0,So(r,r.block_start,n,a),r.block_start+=n,Oe(r.strm)),a?zr:Ee)},Cc=(r,e)=>{let t,n;for(;;){if(r.lookahead<lt){if(En(r),r.lookahead<lt&&e===0)return Ee;if(r.lookahead===0)break}if(t=0,r.lookahead>=$&&(t=Rr(r,r.strstart)),t!==0&&r.strstart-t<=r.w_size-lt&&(r.match_length=Sp(r,t)),r.match_length>=$)if(n=Jt(r,r.strstart-r.match_start,r.match_length-$),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=$){r.match_length--;do r.strstart++,t=Rr(r,r.strstart);while(--r.match_length!==0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.legacy_hash&&(r.ins_h=r.window[r.strstart],r.ins_h=nu(r,r.ins_h,r.window[r.strstart+1]));else n=Jt(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(Ve(r,!1),r.strm.avail_out===0))return Ee}return r.insert=r.strstart<$-1?r.strstart:$-1,e===4?(Ve(r,!0),r.strm.avail_out===0?zr:Mn):r.sym_next&&(Ve(r,!1),r.strm.avail_out===0)?Ee:Tn},An=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<lt){if(En(r),r.lookahead<lt&&e===0)return Ee;if(r.lookahead===0)break}if(t=0,r.lookahead>=$&&(t=Rr(r,r.strstart)),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=$-1,t!==0&&r.prev_length<r.max_lazy_match&&r.strstart-t<=r.w_size-lt&&(r.match_length=Sp(r,t),r.match_length<=5&&(r.strategy===1||r.match_length===$&&r.strstart-r.match_start>4096)&&(r.match_length=$-1)),r.prev_length>=$&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-$,n=Jt(r,r.strstart-1-r.prev_match,r.prev_length-$),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(t=Rr(r,r.strstart));while(--r.prev_length!==0);if(r.match_available=0,r.match_length=$-1,r.strstart++,n&&(Ve(r,!1),r.strm.avail_out===0))return Ee}else if(r.match_available){if(n=Jt(r,0,r.window[r.strstart-1]),n&&Ve(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return Ee}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(n=Jt(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<$-1?r.strstart:$-1,e===4?(Ve(r,!0),r.strm.avail_out===0?zr:Mn):r.sym_next&&(Ve(r,!1),r.strm.avail_out===0)?Ee:Tn},P0=(r,e)=>{let t,n,i,s,a=r.window;for(;;){if(r.lookahead<=Tr){if(En(r),r.lookahead<=Tr&&e===0)return Ee;if(r.lookahead===0)break}if(r.match_length=0,r.lookahead>=$&&r.strstart>0&&(i=r.strstart-1,n=a[i],n===a[++i]&&n===a[++i]&&n===a[++i])){s=r.strstart+Tr;do;while(n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&i<s);r.match_length=Tr-(s-i),r.match_length>r.lookahead&&(r.match_length=r.lookahead)}if(r.match_length>=$?(t=Jt(r,1,r.match_length-$),r.lookahead-=r.match_length,r.strstart+=r.match_length,r.match_length=0):(t=Jt(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++),t&&(Ve(r,!1),r.strm.avail_out===0))return Ee}return r.insert=0,e===4?(Ve(r,!0),r.strm.avail_out===0?zr:Mn):r.sym_next&&(Ve(r,!1),r.strm.avail_out===0)?Ee:Tn},z0=(r,e)=>{let t;for(;;){if(r.lookahead===0&&(En(r),r.lookahead===0)){if(e===0)return Ee;break}if(r.match_length=0,t=Jt(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++,t&&(Ve(r,!1),r.strm.avail_out===0))return Ee}return r.insert=0,e===4?(Ve(r,!0),r.strm.avail_out===0?zr:Mn):r.sym_next&&(Ve(r,!1),r.strm.avail_out===0)?Ee:Tn},ut=class{constructor(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}},Ci=[new ut(0,0,0,0,Ep),new ut(4,4,8,4,Cc),new ut(4,5,16,8,Cc),new ut(4,6,32,32,Cc),new ut(4,4,16,16,An),new ut(8,16,32,32,An),new ut(8,16,128,128,An),new ut(8,32,128,256,An),new ut(32,128,258,1024,An),new ut(32,258,258,4096,An)],R0=r=>{r.window_size=2*r.w_size,Qt(r.head),r.max_lazy_match=Ci[r.level].max_lazy,r.good_match=Ci[r.level].good_length,r.nice_match=Ci[r.level].nice_length,r.max_chain_length=Ci[r.level].max_chain,r.strstart=0,r.block_start=0,r.lookahead=0,r.insert=0,r.match_length=r.prev_length=$-1,r.match_available=0,r.ins_h=0},F0=class{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.legacy_hash=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(k0*2),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Qt(this.dyn_ltree),Qt(this.dyn_dtree),Qt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Qt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Qt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}},ko=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.status!==Sn&&e.status!==ru&&e.status!==Gc&&e.status!==jc&&e.status!==Wc&&e.status!==Hc&&e.status!==Mr&&e.status!==Di?1:0},D0=r=>{if(ko(r))return Ir(r,-2);r.total_in=r.total_out=0,r.data_type=2;let e=r.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?ru:e.wrap?Sn:Mr,r.adler=e.wrap===2?0:1,e.last_flush=-2,b0(e),0},C0=r=>{let e=D0(r);return e===0&&R0(r.state),e};var O0=(r,e,t,n,i,s,a)=>{if(!r)return-2;let o=1;if(e===-1&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),i<1||i>E0||t!==8||n<8||n>15||e<0||e>9||s<0||s>4||n===8&&o!==1)return Ir(r,-2);n===8&&(n=9);let c=new F0;return r.state=c,c.strm=r,c.status=Sn,c.wrap=o,c.gzhead=null,c.w_bits=n,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.legacy_hash=a?1:0,c.hash_bits=i+7,!c.legacy_hash&&c.hash_bits<15&&(c.hash_bits=15),c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+$-1)/$),c.window=new Uint8Array(c.w_size*2),c.head=new Uint16Array(c.hash_size),c.prev=new Uint16Array(c.w_size),c.lit_bufsize=1<<i+6,c.pending_buf_size=c.lit_bufsize*4,c.pending_buf=new Uint8Array(c.pending_buf_size),c.sym_buf=c.lit_bufsize,c.sym_end=(c.lit_bufsize-1)*3,c.level=e,c.strategy=s,c.method=t,C0(r)};var V0=(r,e)=>{if(ko(r)||e>5||e<0)return r?Ir(r,-2):-2;let t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===Di&&e!==4)return Ir(r,r.avail_out===0?-5:-2);let n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Oe(r),r.avail_out===0)return t.last_flush=-1,0}else if(r.avail_in===0&&Ph(e)<=Ph(n)&&e!==4)return Ir(r,-5);if(t.status===Di&&r.avail_in!==0)return Ir(r,-5);if(t.status===Sn&&t.wrap===0&&(t.status=Mr),t.status===Sn){let i=8+(t.w_bits-8<<4)<<8,s=-1;if(t.strategy>=2||t.level<2?s=0:t.level<6?s=1:t.level===6?s=2:s=3,i|=s<<6,t.strstart!==0&&(i|=T0),i+=31-i%31,Fi(t,i),t.strstart!==0&&(Fi(t,r.adler>>>16),Fi(t,r.adler&65535)),r.adler=1,t.status=Mr,Oe(r),t.pending!==0)return t.last_flush=-1,0}if(t.status===ru){if(r.adler=0,B(t,31),B(t,139),B(t,8),t.gzhead)B(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),B(t,t.gzhead.time&255),B(t,t.gzhead.time>>8&255),B(t,t.gzhead.time>>16&255),B(t,t.gzhead.time>>24&255),B(t,t.level===9?2:t.strategy>=2||t.level<2?4:0),B(t,t.gzhead.os&255),t.gzhead.extra&&t.gzhead.extra.length&&(B(t,t.gzhead.extra.length&255),B(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=pe(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=Gc;else if(B(t,0),B(t,0),B(t,0),B(t,0),B(t,0),B(t,t.level===9?2:t.strategy>=2||t.level<2?4:0),B(t,M0),t.status=Mr,Oe(r),t.pending!==0)return t.last_flush=-1,0}if(t.status===Gc){if(t.gzhead.extra){let i=t.pending,s=(t.gzhead.extra.length&65535)-t.gzindex;for(;t.pending+s>t.pending_buf_size;){let o=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=o,Oe(r),t.pending!==0)return t.last_flush=-1,0;i=0,s-=o}let a=new Uint8Array(t.gzhead.extra);t.pending_buf.set(a.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending+=s,t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=jc}if(t.status===jc){if(t.gzhead.name){let i=t.pending,s;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i)),Oe(r),t.pending!==0)return t.last_flush=-1,0;i=0}t.gzindex<t.gzhead.name.length?s=t.gzhead.name.charCodeAt(t.gzindex++)&255:s=0,B(t,s)}while(s!==0);t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=Wc}if(t.status===Wc){if(t.gzhead.comment){let i=t.pending,s;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i)),Oe(r),t.pending!==0)return t.last_flush=-1,0;i=0}t.gzindex<t.gzhead.comment.length?s=t.gzhead.comment.charCodeAt(t.gzindex++)&255:s=0,B(t,s)}while(s!==0);t.gzhead.hcrc&&t.pending>i&&(r.adler=pe(r.adler,t.pending_buf,t.pending-i,i))}t.status=Hc}if(t.status===Hc){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(Oe(r),t.pending!==0))return t.last_flush=-1,0;B(t,r.adler&255),B(t,r.adler>>8&255),r.adler=0}if(t.status=Mr,Oe(r),t.pending!==0)return t.last_flush=-1,0}if(r.avail_in!==0||t.lookahead!==0||e!==0&&t.status!==Di){let i=t.level===0?Ep(t,e):t.strategy===2?z0(t,e):t.strategy===3?P0(t,e):Ci[t.level].func(t,e);if((i===zr||i===Mn)&&(t.status=Di),i===Ee||i===zr)return r.avail_out===0&&(t.last_flush=-1),0;if(i===Tn&&(e===1?v0(t):e!==5&&(So(t,0,0,!1),e===3&&(Qt(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Oe(r),r.avail_out===0))return t.last_flush=-1,0}return e!==4?0:t.wrap<=0?1:(t.wrap===2?(B(t,r.adler&255),B(t,r.adler>>8&255),B(t,r.adler>>16&255),B(t,r.adler>>24&255),B(t,r.total_in&255),B(t,r.total_in>>8&255),B(t,r.total_in>>16&255),B(t,r.total_in>>24&255)):(Fi(t,r.adler>>>16),Fi(t,r.adler&65535)),Oe(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?0:1)},L0=r=>{if(ko(r))return-2;let e=r.state.status;return r.state=null,e===Mr?Ir(r,-3):0},U0=(r,e)=>{let t=e.length;if(ko(r))return-2;let n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==Sn||n.lookahead)return-2;if(i===1&&(r.adler=Ni(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(Qt(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(t-n.w_size,t),0),e=c,t=n.w_size}let s=r.avail_in,a=r.next_in,o=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,En(n);n.lookahead>=$;){let c=n.strstart,u=n.lookahead-($-1);do Rr(n,c),c++;while(--u);n.strstart=c,n.lookahead=$-1,En(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=$-1,n.match_available=0,r.next_in=a,r.input=o,r.avail_in=s,n.wrap=i,0},go=16209,B0=16191;function $0(r,e){let t,n,i,s,a,o,c,u,d,f,l,h,p,_,w,y,b,g,x,P,I,M,k,T,R=r.state;t=r.next_in,k=r.input,n=t+(r.avail_in-5),i=r.next_out,T=r.output,s=i-(e-r.avail_out),a=i+(r.avail_out-257),o=R.dmax,c=R.wsize,u=R.whave,d=R.wnext,f=R.window,l=R.hold,h=R.bits,p=R.lencode,_=R.distcode,w=(1<<R.lenbits)-1,y=(1<<R.distbits)-1;e:do{h<15&&(l+=k[t++]<<h,h+=8,l+=k[t++]<<h,h+=8),b=p[l&w];t:for(;;){if(g=b>>>24,l>>>=g,h-=g,g=b>>>16&255,g===0)T[i++]=b&65535;else if(g&16){x=b&65535,g&=15,g&&(h<g&&(l+=k[t++]<<h,h+=8),x+=l&(1<<g)-1,l>>>=g,h-=g),h<15&&(l+=k[t++]<<h,h+=8,l+=k[t++]<<h,h+=8),b=_[l&y];r:for(;;){if(g=b>>>24,l>>>=g,h-=g,g=b>>>16&255,g&16){if(P=b&65535,g&=15,h<g&&(l+=k[t++]<<h,h+=8,h<g&&(l+=k[t++]<<h,h+=8)),P+=l&(1<<g)-1,P>o){r.msg="invalid distance too far back",R.mode=go;break e}if(l>>>=g,h-=g,g=i-s,P>g){if(g=P-g,g>u&&R.sane){r.msg="invalid distance too far back",R.mode=go;break e}if(I=0,M=f,d===0){if(I+=c-g,g<x){x-=g;do T[i++]=f[I++];while(--g);I=i-P,M=T}}else if(d<g){if(I+=c+d-g,g-=d,g<x){x-=g;do T[i++]=f[I++];while(--g);if(I=0,d<x){g=d,x-=g;do T[i++]=f[I++];while(--g);I=i-P,M=T}}}else if(I+=d-g,g<x){x-=g;do T[i++]=f[I++];while(--g);I=i-P,M=T}for(;x>2;)T[i++]=M[I++],T[i++]=M[I++],T[i++]=M[I++],x-=3;x&&(T[i++]=M[I++],x>1&&(T[i++]=M[I++]))}else{I=i-P;do T[i++]=T[I++],T[i++]=T[I++],T[i++]=T[I++],x-=3;while(x>2);x&&(T[i++]=T[I++],x>1&&(T[i++]=T[I++]))}}else if((g&64)===0){b=_[(b&65535)+(l&(1<<g)-1)];continue r}else{r.msg="invalid distance code",R.mode=go;break e}break}}else if((g&64)===0){b=p[(b&65535)+(l&(1<<g)-1)];continue t}else if(g&32){R.mode=B0;break e}else{r.msg="invalid literal/length code",R.mode=go;break e}break}}while(t<n&&i<a);x=h>>3,t-=x,h-=x<<3,l&=(1<<h)-1,r.next_in=t,r.next_out=i,r.avail_in=t<n?5+(n-t):5-(t-n),r.avail_out=i<a?257+(a-i):257-(i-a),R.hold=l,R.bits=h}var yo=15,zh=852,Rh=592,Fh=0,Oc=1,Dh=2,N0=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),q0=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,199,75]),Z0=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),G0=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),Li=(r,e,t,n,i,s,a,o)=>{let c=o.bits,u=0,d=0,f=0,l=0,h=0,p=0,_=0,w=0,y=0,b=0,g,x,P,I,M,k=null,T,R=new Uint16Array(16),Y=new Uint16Array(16),Ae=null,ur,mt,Je;for(u=0;u<=yo;u++)R[u]=0;for(d=0;d<n;d++)R[e[t+d]]++;for(h=c,l=yo;l>=1&&R[l]===0;l--);if(h>l&&(h=l),l===0)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(f=1;f<l&&R[f]===0;f++);for(h<f&&(h=f),w=1,u=1;u<=yo;u++)if(w<<=1,w-=R[u],w<0)return-1;if(w>0&&(r===Fh||l!==1))return-1;for(Y[1]=0,u=1;u<yo;u++)Y[u+1]=Y[u]+R[u];for(d=0;d<n;d++)e[t+d]!==0&&(a[Y[e[t+d]]++]=d);if(r===Fh?(k=Ae=a,T=20):r===Oc?(k=N0,Ae=q0,T=257):(k=Z0,Ae=G0,T=0),b=0,d=0,u=f,M=s,p=h,_=0,P=-1,y=1<<h,I=y-1,r===Oc&&y>zh||r===Dh&&y>Rh)return 1;for(;;){ur=u-_,a[d]+1<T?(mt=0,Je=a[d]):a[d]>=T?(mt=Ae[a[d]-T],Je=k[a[d]-T]):(mt=96,Je=0),g=1<<u-_,x=1<<p,f=x;do x-=g,i[M+(b>>_)+x]=ur<<24|mt<<16|Je|0;while(x!==0);for(g=1<<u-1;b&g;)g>>=1;if(g!==0?(b&=g-1,b+=g):b=0,d++,--R[u]===0){if(u===l)break;u=e[t+a[d]]}if(u>h&&(b&I)!==P){for(_===0&&(_=h),M+=f,p=u-_,w=1<<p;p+_<l&&(w-=R[p+_],!(w<=0));)p++,w<<=1;if(y+=1<<p,r===Oc&&y>zh||r===Dh&&y>Rh)return 1;P=b&I,i[P]=h<<24|p<<16|M-s|0}}return b!==0&&(i[M+b]=u-_<<24|4194304),o.bits=h,0},j0=0,kp=1,Tp=2,To=16180,Ch=16181,Oh=16182,Vh=16183,Lh=16184,Uh=16185,Bh=16186,$h=16187,Nh=16188,qh=16189,Eo=16190,Tt=16191,Vc=16192,Zh=16193,Lc=16194,Gh=16195,jh=16196,Wh=16197,Hh=16198,bo=16199,vo=16200,Xh=16201,Yh=16202,Kh=16203,Qh=16204,Jh=16205,Uc=16206,ep=16207,tp=16208,X=16209,Yc=16210,Mp=16211,W0=852,H0=592;var rp=r=>(r>>>24&255)+(r>>>8&65280)+((r&65280)<<8)+((r&255)<<24),X0=class{constructor(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}},In=r=>{if(!r)return 1;let e=r.state;return!e||e.strm!==r||e.mode<To||e.mode>Mp?1:0},Y0=r=>{if(In(r))return-2;let e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.adler=e.wrap&1),e.mode=To,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(W0),e.distcode=e.distdyn=new Int32Array(H0),e.sane=1,e.back=-1,0},Ip=r=>{if(In(r))return-2;let e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Y0(r)},K0=(r,e)=>{let t;if(In(r))return-2;let n=r.state;return e<0?(t=0,e=-e):(t=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?-2:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,Ip(r))},Q0=(r,e)=>{if(!r)return-2;let t=new X0;r.state=t,t.strm=r,t.window=null,t.mode=To;let n=K0(r,e);return n!==0&&(r.state=null),n};var np=!0,Bc,$c,J0=r=>{if(np){Bc=new Int32Array(512),$c=new Int32Array(32);let e=0;for(;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(Li(kp,r.lens,0,288,Bc,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;Li(Tp,r.lens,0,32,$c,0,r.work,{bits:5}),np=!1}r.lencode=Bc,r.lenbits=9,r.distcode=$c,r.distbits=5},Pp=(r,e,t,n)=>{let i,s=r.state;return s.window===null&&(s.window=new Uint8Array(1<<s.wbits)),s.wsize===0&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0),n>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>n&&(i=n),s.window.set(e.subarray(t-n,t-n+i),s.wnext),n-=i,n?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0},Nc=(r,e)=>{let t,n,i,s,a,o,c,u,d,f,l,h,p,_,w=0,y,b,g,x,P,I,M,k,T=new Uint8Array(4),R,Y,Ae=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(In(r)||!r.output||!r.input&&r.avail_in!==0)return-2;t=r.state,t.mode===Tt&&(t.mode=Vc),a=r.next_out,i=r.output,c=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,u=t.hold,d=t.bits,f=o,l=c,k=0;e:for(;;)switch(t.mode){case To:if(t.wrap===0){t.mode=Vc;break}for(;d<16;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(t.wrap&2&&u===35615){t.wbits===0&&(t.wbits=15),t.check=0,T[0]=u&255,T[1]=u>>>8&255,t.check=pe(t.check,T,2,0),u=0,d=0,t.mode=Ch;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((u&255)<<8)+(u>>8))%31){r.msg="incorrect header check",t.mode=X;break}if((u&15)!==8){r.msg="unknown compression method",t.mode=X;break}if(u>>>=4,d-=4,M=(u&15)+8,t.wbits===0&&(t.wbits=M),M>15||M>t.wbits){r.msg="invalid window size",t.mode=X;break}t.dmax=1<<t.wbits,t.flags=0,r.adler=t.check=1,t.mode=u&512?qh:Tt,u=0,d=0;break;case Ch:for(;d<16;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(t.flags=u,(t.flags&255)!==8){r.msg="unknown compression method",t.mode=X;break}if(t.flags&57344){r.msg="unknown header flags set",t.mode=X;break}t.head&&(t.head.text=u>>8&1),t.flags&512&&t.wrap&4&&(T[0]=u&255,T[1]=u>>>8&255,t.check=pe(t.check,T,2,0)),u=0,d=0,t.mode=Oh;case Oh:for(;d<32;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.head&&(t.head.time=u),t.flags&512&&t.wrap&4&&(T[0]=u&255,T[1]=u>>>8&255,T[2]=u>>>16&255,T[3]=u>>>24&255,t.check=pe(t.check,T,4,0)),u=0,d=0,t.mode=Vh;case Vh:for(;d<16;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.head&&(t.head.xflags=u&255,t.head.os=u>>8),t.flags&512&&t.wrap&4&&(T[0]=u&255,T[1]=u>>>8&255,t.check=pe(t.check,T,2,0)),u=0,d=0,t.mode=Lh;case Lh:if(t.flags&1024){for(;d<16;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.length=u,t.head&&(t.head.extra_len=u),t.flags&512&&t.wrap&4&&(T[0]=u&255,T[1]=u>>>8&255,t.check=pe(t.check,T,2,0)),u=0,d=0}else t.head&&(t.head.extra=null);t.mode=Uh;case Uh:if(t.flags&1024&&(h=t.length,h>o&&(h=o),h&&(t.head&&(M=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+h),M)),t.flags&512&&t.wrap&4&&(t.check=pe(t.check,n,h,s)),o-=h,s+=h,t.length-=h),t.length))break e;t.length=0,t.mode=Bh;case Bh:if(t.flags&2048){if(o===0)break e;h=0;do M=n[s+h++],t.head&&M&&t.length<65536&&(t.head.name+=String.fromCharCode(M));while(M&&h<o);if(t.flags&512&&t.wrap&4&&(t.check=pe(t.check,n,h,s)),o-=h,s+=h,M)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=$h;case $h:if(t.flags&4096){if(o===0)break e;h=0;do M=n[s+h++],t.head&&M&&t.length<65536&&(t.head.comment+=String.fromCharCode(M));while(M&&h<o);if(t.flags&512&&t.wrap&4&&(t.check=pe(t.check,n,h,s)),o-=h,s+=h,M)break e}else t.head&&(t.head.comment=null);t.mode=Nh;case Nh:if(t.flags&512){for(;d<16;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(t.wrap&4&&u!==(t.check&65535)){r.msg="header crc mismatch",t.mode=X;break}u=0,d=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),r.adler=t.check=0,t.mode=Tt;break;case qh:for(;d<32;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}r.adler=t.check=rp(u),u=0,d=0,t.mode=Eo;case Eo:if(t.havedict===0)return r.next_out=a,r.avail_out=c,r.next_in=s,r.avail_in=o,t.hold=u,t.bits=d,2;r.adler=t.check=1,t.mode=Tt;case Tt:if(e===5||e===6)break e;case Vc:if(t.last){u>>>=d&7,d-=d&7,t.mode=Uc;break}for(;d<3;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}switch(t.last=u&1,u>>>=1,d-=1,u&3){case 0:t.mode=Zh;break;case 1:if(J0(t),t.mode=bo,e===6){u>>>=2,d-=2;break e}break;case 2:t.mode=jh;break;case 3:r.msg="invalid block type",t.mode=X}u>>>=2,d-=2;break;case Zh:for(u>>>=d&7,d-=d&7;d<32;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if((u&65535)!==(u>>>16^65535)){r.msg="invalid stored block lengths",t.mode=X;break}if(t.length=u&65535,u=0,d=0,t.mode=Lc,e===6)break e;case Lc:t.mode=Gh;case Gh:if(h=t.length,h){if(h>o&&(h=o),h>c&&(h=c),h===0)break e;i.set(n.subarray(s,s+h),a),o-=h,s+=h,c-=h,a+=h,t.length-=h;break}t.mode=Tt;break;case jh:for(;d<14;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(t.nlen=(u&31)+257,u>>>=5,d-=5,t.ndist=(u&31)+1,u>>>=5,d-=5,t.ncode=(u&15)+4,u>>>=4,d-=4,t.nlen>286||t.ndist>30){r.msg="too many length or distance symbols",t.mode=X;break}t.have=0,t.mode=Wh;case Wh:for(;t.have<t.ncode;){for(;d<3;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.lens[Ae[t.have++]]=u&7,u>>>=3,d-=3}for(;t.have<19;)t.lens[Ae[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,R={bits:t.lenbits},k=Li(j0,t.lens,0,19,t.lencode,0,t.work,R),t.lenbits=R.bits,k){r.msg="invalid code lengths set",t.mode=X;break}t.have=0,t.mode=Hh;case Hh:for(;t.have<t.nlen+t.ndist;){for(;w=t.lencode[u&(1<<t.lenbits)-1],y=w>>>24,b=w>>>16&255,g=w&65535,!(y<=d);){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(g<16)u>>>=y,d-=y,t.lens[t.have++]=g;else{if(g===16){for(Y=y+2;d<Y;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(u>>>=y,d-=y,t.have===0){r.msg="invalid bit length repeat",t.mode=X;break}M=t.lens[t.have-1],h=3+(u&3),u>>>=2,d-=2}else if(g===17){for(Y=y+3;d<Y;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}u>>>=y,d-=y,M=0,h=3+(u&7),u>>>=3,d-=3}else{for(Y=y+7;d<Y;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}u>>>=y,d-=y,M=0,h=11+(u&127),u>>>=7,d-=7}if(t.have+h>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=X;break}for(;h--;)t.lens[t.have++]=M}}if(t.mode===X)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=X;break}if(t.lenbits=9,R={bits:t.lenbits},k=Li(kp,t.lens,0,t.nlen,t.lencode,0,t.work,R),t.lenbits=R.bits,k){r.msg="invalid literal/lengths set",t.mode=X;break}if(t.distbits=6,t.distcode=t.distdyn,R={bits:t.distbits},k=Li(Tp,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,R),t.distbits=R.bits,k){r.msg="invalid distances set",t.mode=X;break}if(t.mode=bo,e===6)break e;case bo:t.mode=vo;case vo:if(o>=6&&c>=258){r.next_out=a,r.avail_out=c,r.next_in=s,r.avail_in=o,t.hold=u,t.bits=d,$0(r,l),a=r.next_out,i=r.output,c=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,u=t.hold,d=t.bits,t.mode===Tt&&(t.back=-1);break}for(t.back=0;w=t.lencode[u&(1<<t.lenbits)-1],y=w>>>24,b=w>>>16&255,g=w&65535,!(y<=d);){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(b&&(b&240)===0){for(x=y,P=b,I=g;w=t.lencode[I+((u&(1<<x+P)-1)>>x)],y=w>>>24,b=w>>>16&255,g=w&65535,!(x+y<=d);){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}u>>>=x,d-=x,t.back+=x}if(u>>>=y,d-=y,t.back+=y,t.length=g,b===0){t.mode=Jh;break}if(b&32){t.back=-1,t.mode=Tt;break}if(b&64){r.msg="invalid literal/length code",t.mode=X;break}t.extra=b&15,t.mode=Xh;case Xh:if(t.extra){for(Y=t.extra;d<Y;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.length+=u&(1<<t.extra)-1,u>>>=t.extra,d-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=Yh;case Yh:for(;w=t.distcode[u&(1<<t.distbits)-1],y=w>>>24,b=w>>>16&255,g=w&65535,!(y<=d);){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if((b&240)===0){for(x=y,P=b,I=g;w=t.distcode[I+((u&(1<<x+P)-1)>>x)],y=w>>>24,b=w>>>16&255,g=w&65535,!(x+y<=d);){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}u>>>=x,d-=x,t.back+=x}if(u>>>=y,d-=y,t.back+=y,b&64){r.msg="invalid distance code",t.mode=X;break}t.offset=g,t.extra=b&15,t.mode=Kh;case Kh:if(t.extra){for(Y=t.extra;d<Y;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}t.offset+=u&(1<<t.extra)-1,u>>>=t.extra,d-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){r.msg="invalid distance too far back",t.mode=X;break}t.mode=Qh;case Qh:if(c===0)break e;if(h=l-c,t.offset>h){if(h=t.offset-h,h>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=X;break}h>t.wnext?(h-=t.wnext,p=t.wsize-h):p=t.wnext-h,h>t.length&&(h=t.length),_=t.window}else _=i,p=a-t.offset,h=t.length;h>c&&(h=c),c-=h,t.length-=h;do i[a++]=_[p++];while(--h);t.length===0&&(t.mode=vo);break;case Jh:if(c===0)break e;i[a++]=t.length,c--,t.mode=vo;break;case Uc:if(t.wrap){for(;d<32;){if(o===0)break e;o--,u|=n[s++]<<d,d+=8}if(l-=c,r.total_out+=l,t.total+=l,t.wrap&4&&l&&(r.adler=t.check=t.flags?pe(t.check,i,l,a-l):Ni(t.check,i,l,a-l)),l=c,t.wrap&4&&(t.flags?u:rp(u))!==t.check){r.msg="incorrect data check",t.mode=X;break}u=0,d=0}t.mode=ep;case ep:if(t.wrap&&t.flags){for(;d<32;){if(o===0)break e;o--,u+=n[s++]<<d,d+=8}if(t.wrap&4&&u!==(t.total&4294967295)){r.msg="incorrect length check",t.mode=X;break}u=0,d=0}t.mode=tp;case tp:k=1;break e;case X:k=-3;break e;case Yc:return-4;case Mp:default:return-2}return r.next_out=a,r.avail_out=c,r.next_in=s,r.avail_in=o,t.hold=u,t.bits=d,(t.wsize||l!==r.avail_out&&t.mode<X&&(t.mode<Uc||e!==4))&&Pp(r,r.output,r.next_out,l-r.avail_out)?(t.mode=Yc,-4):(f-=r.avail_in,l-=r.avail_out,r.total_in+=f,r.total_out+=l,t.total+=l,t.wrap&4&&l&&(r.adler=t.check=t.flags?pe(t.check,i,l,r.next_out-l):Ni(t.check,i,l,r.next_out-l)),r.data_type=t.bits+(t.last?64:0)+(t.mode===Tt?128:0)+(t.mode===bo||t.mode===Lc?256:0),(f===0&&l===0||e===4)&&k===0&&(k=-5),k)},ip=r=>{if(In(r))return-2;let e=r.state;return e.window&&(e.window=null),r.state=null,0};var sp=(r,e)=>{let t=e.length,n,i,s;return In(r)||(n=r.state,n.wrap!==0&&n.mode!==Eo)?-2:n.mode===Eo&&(i=1,i=Ni(i,e,t,0),i!==n.check)?-3:(s=Pp(r,e,t,t),s?(n.mode=Yc,-4):(n.havedict=1,0))},zp=class{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}};var Rp=r=>{let e=new Uint8Array(r.reduce((n,i)=>n+i.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e},op=Object.prototype.toString,ey={level:-1,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,raw:!1,gzip:!1,legacyHash:!1,dictionary:new Uint8Array(0)},Fp=class{options;err;msg;ended;started;chunks;strm;result;constructor(r={}){this.options=Object.assign({},ey,r);let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.started=!1,this.chunks=[],this.result=new Uint8Array(0),this.strm=new zp,this.strm.avail_out=0;let t=O0(this.strm,e.level,8,e.windowBits,e.memLevel,e.strategy,e.legacyHash);if(t!==0)throw new Error(Pr[t]);op.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary));let n=e.dictionary;if(n.length){if(e.gzip)throw new Error("dictionary is not supported with gzip");if(t=U0(this.strm,n),t!==0)throw new Error(Pr[t])}}push(r,e=!1){let t=this.strm,n=this.options.chunkSize,i,s;if(this.ended)return!1;for(typeof e=="number"?s=e:s=e===!0?4:0,typeof r=="string"?t.input=new TextEncoder().encode(r):op.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length,this.started||(this.started=!0,this.onStart(t));;){if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(s===2||s===3)&&t.avail_out<=6){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(i=V0(t,s),i===-2)break;if(i===1){t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=L0(this.strm);break}if(t.avail_out===0){this.onData(t.output);continue}if(s>0&&t.next_out>0){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(t.avail_in===0)return!0}return this.err=i,this.msg=t.msg||Pr[i],this.ended=!0,this.onEnd(i),i===0}onStart(r){}onData(r){this.chunks.push(r)}onEnd(r){r===0&&(this.result=Rp(this.chunks)),this.chunks=[]}};var ap=Object.prototype.toString,ty={chunkSize:1024*64,windowBits:15,raw:!1,dictionary:new Uint8Array(0)},Dp=class{options;err;msg;ended;started;chunks;strm;result;constructor(r={}){this.options=Object.assign({},ty,r);let e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!r.windowBits&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.started=!1,this.chunks=[],this.result=new Uint8Array(0),this.strm=new zp,this.strm.avail_out=0;let t=Q0(this.strm,e.windowBits);if(t!==0)throw new Error(Pr[t]);ap.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary));let n=e.dictionary;if(e.raw&&n.length&&(t=sp(this.strm,n),t!==0))throw new Error(Pr[t])}push(r,e=!1){let t=this.strm,n=this.options.chunkSize,i,s,a;if(this.ended)return this.err===0;for(typeof e=="number"?s=e:s=e===!0?4:0,ap.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length,this.started||(this.started=!0,this.onStart(t));;){if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),i=Nc(t,s),i===2){let o=this.options.dictionary;o.length&&(i=sp(t,o),i===0?i=Nc(t,s):i===-3&&(i=2))}for(;t.avail_in>0&&i===1&&t.state.wrap&2&&t.state.flags!==0&&t.input[t.next_in]!==0;)Ip(t),i=Nc(t,s);if(i===-2||i===-3||i===2||i===-4)break;if(a=t.avail_out,t.next_out&&(t.avail_out===0||i===1||s>0)&&(this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out)),t.avail_out=0,t.next_out=0),!((i===0||i===-5)&&a===0)){if(i===1){i=ip(this.strm);break}if(t.avail_in===0){if(s===4){i=ip(this.strm),i===0&&(i=-5);break}return!0}}}return this.err=i,this.msg=t.msg||Pr[i],this.ended=!0,this.onEnd(i),i===0}onStart(r){}onData(r){this.chunks.push(r)}onEnd(r){r===0&&(this.result=Rp(this.chunks)),this.chunks=[]}};var ny=6,iy=64*1024*1024,Cp=new Uint8Array([0,0,255,255]);function sy(r,e){if(r.length===1)return r[0];let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var Mo=class{#e;#t=[];#r=0;constructor(e={}){let t=e.level??ny;this.#e=new Fp({raw:!0,level:t}),this.#e.onData=n=>{let i=n;this.#t.push(i),this.#r+=i.length}}frame(e){if(e.length===0)return e;this.#t=[],this.#r=0,this.#e.push(e,tu);let t=new Uint8Array(this.#r-Cp.length),n=0;for(let i of this.#t){if(n>=t.length)break;let s=Math.min(i.length,t.length-n);t.set(i.subarray(0,s),n),n+=s}return t}},Io=class{#e=new Dp({raw:!0});#t=[];#r=0;#n=!1;#i;constructor(e={}){this.#i=e.maxFrameSize??iy,this.#e.onData=t=>{let n=t;if(this.#r+=n.length,this.#r>this.#i){this.#n=!0;return}this.#t.push(n)}}frame(e){if(e.length===0)return e;if(this.#t=[],this.#r=0,this.#n=!1,this.#e.push(e,!1),this.#e.push(Cp,tu),this.#e.err)throw new Error(`decompression failed: ${this.#e.msg}`);if(this.#n)throw new Error(`decompressed frame exceeded ${this.#i} bytes`);return sy(this.#t,this.#r)}};var Pn=class{#e;#t;#r;#n;constructor(e={}){this.#e=e.schema,this.#t=e.compression??!1}snapshot(e){this.#r=this.#t?new Io:void 0,this.#n=this.#i(e)}delta(e){if(this.#n===void 0)throw new Error("delta before snapshot");this.#n=Pc(this.#n,this.#i(e))}get value(){return this.#n===void 0?void 0:structuredClone(this.#n)}decode(){if(this.#n!==void 0)return this.#e?this.#e.parse(this.#n):structuredClone(this.#n)}#i(e){let t=this.#r?this.#r.frame(e):e;return JSON.parse(new TextDecoder().decode(t))}};var Po=class{#e;#t;#r;#n=0;constructor(e,t={}){this.#e=e,this.#t=new Pn(t)}async next(){for(;;){if(!this.#r){if(this.#r=await this.#e.nextGroup(),!this.#r)return;this.#n=0}let e=!1;for(let n=this.#r.tryReadFrame();n!==void 0;n=this.#r.tryReadFrame())this.#i(n.payload),e=!0;if(e)return this.#t.decode();let t;try{t=await this.#r.readFrame()}catch{this.#r=void 0;continue}if(t===void 0){this.#r=void 0;continue}return this.#i(t.payload),this.#t.decode()}}async*[Symbol.asyncIterator](){for(;;){let e=await this.next();if(e===void 0)return;yield e}}#i(e){this.#n===0?this.#t.snapshot(e):this.#t.delta(e),this.#n+=1}};var oy=256,iu=8,zn=class{#e;#t;#r;#n=0;#i=0;#s=0;#o;#a=!1;#c=0;#d=!1;constructor(e={}){this.#e=e,this.#t=e.compression??!1}get value(){return this.#r===void 0?void 0:structuredClone(this.#r)}reset(){this.#o=void 0,this.#n=0,this.#i=0,this.#s=0,this.#d=!0,this.#a=!1}update(e){this.#a&&this.reset();let t=this.#e.schema?this.#e.schema.parse(e):e,n=JSON.stringify(t);if(n===void 0)throw new Error("value is not representable as JSON");let i=JSON.parse(n);if(!this.#d&&this.#r!==void 0&&Ri(this.#r,i))return;let s=this.#f(i);if(s){let o=this.#m(s);return this.#r=i,this.#n+=o.length,this.#s+=1,this.#l({payload:o,keyframe:!1})}let a=this.#p(new TextEncoder().encode(n));return this.#r=i,this.#l({payload:a,keyframe:!0})}#l(e){this.#a=!0;let t=++this.#c;return{...e,commit:()=>{this.#c===t&&(this.#a=!1)}}}get#u(){return this.#e.deltaRatio??iu}#f(e){if(this.#d)return;let t=this.#u;if(t===0||this.#r===void 0||this.#s===0||this.#s>=oy||this.#n>t*this.#i)return;let n=vh(this.#r,e);if(!n.forcedSnapshot)return new TextEncoder().encode(JSON.stringify(n.patch))}#p(e){let t=this.#t?new Mo:void 0,n=t?t.frame(e):e;return this.#o=t,this.#i=n.length,this.#n=0,this.#s=1,this.#d=!1,n}#m(e){return this.#o?this.#o.frame(e):e}};var zo=class{#e;#t;#r;#n;#i;constructor(e){this.#e=e.track,this.#t=new zn(e),this.#r=e.initial,this.#i=(e.deltaRatio??iu)!==0}update(e){let t=this.#t.update(e);t&&(this.#s(t),t.commit())}#s(e){if(e.keyframe){this.#n?.close(),this.#n=void 0;let t=this.#e.appendGroup();try{t.writeFrame({payload:e.payload,timestamp:E.Timestamp.now()})}catch(n){throw t.close(),n}this.#i?this.#n=t:(t.close(),this.#n=void 0);return}if(!this.#n)throw new Error("delta with no open group");this.#n.writeFrame({payload:e.payload,timestamp:E.Timestamp.now()})}mutate(e){let t=this.#t.value??this.#r;if(t===void 0)throw new Error("mutate() requires a prior update() or `initial` in the config");let n=structuredClone(t);e(n),this.update(n)}finish(){this.#n?.close(),this.#n=void 0,this.#t.reset(),this.#e.close()}};function qi(r,e){if(r.length===0)return e;if(e.length===0)return r;let t=[],n=[...r,...e].sort((i,s)=>i.start-s.start);for(let i of n){let s=t.at(-1);s&&s.end>=i.start?s.end=E.Milli.max(s.end,i.end):t.push({...i})}return t}var Ji={};ke(Ji,{polyfill:()=>VA});var yu;async function VA(){return globalThis.AudioEncoder&&globalThis.AudioDecoder?!0:(yu||(console.warn("using Opus polyfill; performance may be degraded"),yu=Promise.all([Promise.resolve().then(()=>(Vp(),Op)),Promise.resolve().then(()=>(sm(),im))]).then(async([r,e])=>(await e.load({LibAV:r,polyfill:!0}),!0))),await yu)}var UA=it([xa(["loc","cmaf","legacy","mediatimeline","eventtimeline"]),q()]),BA=it([xa(["video","audio","audiodescription","caption","subtitle","signlanguage"]),q()]),om={name:q(),packaging:UA,isLive:F(pr()),role:F(BA),codec:F(q()),width:F(we()),height:F(we()),framerate:F(we()),samplerate:F(we()),channelConfig:F(q()),bitrate:F(we()),stalled:F(pr()),initData:F(q()),renderGroup:F(we()),altGroup:F(we()),maxGrpSapStartingType:F(we()),maxObjSapStartingType:F(we()),jitter:F(we())},$A=K(om),Ez=K({tracks:qr($A)});var NA=K({id:q(),type:q(),data:q()}),qA=K({...om,initRef:F(q())}),ZA=K({version:it([Zr(1),q()]),tracks:F(qr(qA)),initDataList:F(qr(NA))});function GA(r){let e=new TextDecoder().decode(r);try{let t=ZA.parse(JSON.parse(e)),n=new Map((t.initDataList??[]).filter(s=>s.type==="inline").map(s=>[s.id,s.data]));return{tracks:(t.tracks??[]).map(({initRef:s,...a})=>(a.isLive??=!1,a.initData===void 0&&s!==void 0&&(a.initData=n.get(s)),a))}}catch(t){throw console.warn("invalid MSF catalog",e),t}}async function am(r){let e=await r.readFrame();if(e)return GA(e.payload)}function rs(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var pt=0,He=1,es=2,Cr=3,jA=4;function mm(r,e,t,n=!1){if(r<=0)throw Error("invalid channels");if(e<=0)throw Error("invalid capacity");if(t<=0)throw Error("invalid sample rate");let i=new SharedArrayBuffer(r*e*Float32Array.BYTES_PER_ELEMENT),s=new SharedArrayBuffer(jA*Int32Array.BYTES_PER_ELEMENT),a=new Int32Array(s);return Atomics.store(a,Cr,1),{channels:r,capacity:e,rate:t,samples:i,control:s,buffered:n}}function WA(r,e){return(r-e|0)>0?r:e}function ts(r,e){return(r%e+e)%e}function bu(r,e,t){for(;;){let n=Atomics.load(r,e);if((t-n|0)<=0)return n;if(Atomics.compareExchange(r,e,n,t)===n)return t}}var HA=class _m{channels;capacity;rate;buffered;init;#e;#t;#r=!1;constructor(e){this.channels=e.channels,this.capacity=e.capacity,this.rate=e.rate,this.buffered=e.buffered,this.init=e,this.#e=new Int32Array(e.control),this.#t=[];for(let t=0;t<this.channels;t++)this.#t.push(new Float32Array(e.samples,t*this.capacity*Float32Array.BYTES_PER_ELEMENT,this.capacity))}insert(e,t){if(t.length!==this.channels)throw Error("wrong number of channels");let n=Math.round(E.Second.fromMicro(e)*this.rate),i=t[0].length,s=0;this.buffered&&!this.#r&&(Atomics.store(this.#e,He,n|0),Atomics.store(this.#e,pt,n|0),this.#r=!0);let a=n+i|0,o=Atomics.load(this.#e,He),c=o-n|0;if(c>0){if(c>=i)return;s=c,n=n+c|0}let u=i-s;(a-o|0)>this.capacity&&bu(this.#e,He,a-this.capacity|0);let d=Atomics.load(this.#e,pt),f=n-d|0;if(f>0){let _=Math.min(f,this.capacity);for(let w=0;w<this.channels;w++){let y=this.#t[w];for(let b=0;b<_;b++)y[ts(d+b|0,this.capacity)]=0}}for(let _=0;_<this.channels;_++){let w=t[_],y=this.#t[_];for(let b=0;b<u;b++)y[ts(n+b|0,this.capacity)]=w[s+b]}Atomics.store(this.#e,pt,WA(Atomics.load(this.#e,pt),a));let l=Atomics.load(this.#e,He),h=Atomics.load(this.#e,pt),p=Atomics.load(this.#e,es);(h-l|0)>=p&&p>0&&Atomics.store(this.#e,Cr,0)}read(e){if(Atomics.load(this.#e,Cr)===1)return 0;let t=Atomics.load(this.#e,He),n=Atomics.load(this.#e,pt),i=Atomics.load(this.#e,es),s=n-t|0;if(!this.buffered&&i>0&&s>i){let c=n-i|0;t=bu(this.#e,He,c)}let a=n-t|0,o=Math.min(a,e[0].length);if(o<=0)return 0;for(let c=0;c<this.channels;c++){let u=this.#t[c],d=e[c];for(let f=0;f<o;f++)d[f]=u[ts(t+f|0,this.capacity)]}return bu(this.#e,He,t+o|0),o}setLatency(e){Atomics.store(this.#e,es,e)}reset(){this.#r=!1,Atomics.store(this.#e,Cr,1);let e=Atomics.load(this.#e,pt);Atomics.store(this.#e,He,e)}resize(e){let t=mm(this.channels,e,this.rate,this.buffered),n=new _m(t);n.#r=this.#r;let i=Atomics.load(this.#e,He),s=Atomics.load(this.#e,pt),a=Atomics.load(this.#e,es),o=Atomics.load(this.#e,Cr),c=s-i|0,u=Math.max(0,Math.min(c,n.capacity)),d=s-u|0;for(let f=0;f<this.channels;f++){let l=this.#t[f],h=n.#t[f];for(let p=0;p<u;p++){let _=d+p|0;h[ts(_,n.capacity)]=l[ts(_,this.capacity)]}}return Atomics.store(n.#e,He,d),Atomics.store(n.#e,pt,s),Atomics.store(n.#e,es,a),Atomics.store(n.#e,Cr,o),n}get timestamp(){let e=Atomics.load(this.#e,He);return E.Micro.fromSecond(e/this.rate)}get stalled(){return Atomics.load(this.#e,Cr)===1}get length(){return Atomics.load(this.#e,pt)-Atomics.load(this.#e,He)|0}},wm=class{#e;#t;#r=[];constructor(r,e){this.#e=r,this.#t=e}setHeadroom(r){this.#t=r}wait(r,e){return!this.#e||e>=(r-this.#t|0)?Promise.resolve():new Promise(t=>this.#r.push({timestamp:r,resolve:t}))}advance(r){this.#r.length!==0&&(this.#r=this.#r.filter(({timestamp:e,resolve:t})=>r<(e-this.#t|0)||(t(),!1)))}flush(){for(let{resolve:r}of this.#r)r();this.#r=[]}};function $o(r,e){return E.Micro.fromSecond(r/e)}function XA(){return!(typeof SharedArrayBuffer>"u"||typeof crossOriginIsolated<"u"&&!crossOriginIsolated)}function YA(r,e,t,n,i=!1){return XA()?(console.log("[audio] using SharedArrayBuffer audio buffer"),new KA(r,e,t,n,i)):(console.log("[audio] using postMessage audio buffer (SharedArrayBuffer unavailable)"),new QA(r,e,t,n,i))}var KA=class{rate;channels;#e;#t;#r=new A(0);timestamp=this.#r;#n=new A(!0);stalled=this.#n;#i;#s=new j;constructor(r,e,t,n,i){this.#e=r,this.channels=e,this.rate=t;let s=Math.max(t,n*2);this.#i=new wm(i,$o(n,t));let a=mm(e,s,t,i);this.#t=new HA(a),this.#t.setLatency(n);let o={type:"init-shared",...a};r.port.postMessage(o),this.#s.interval(()=>{let c=this.#t.stalled;this.#r.set(this.#t.timestamp),this.#n.set(c),c?this.#i.flush():this.#i.advance(this.#t.timestamp)},50)}insert(r,e){this.#t.insert(r,e)}setLatency(r){if(this.#i.setHeadroom($o(r,this.rate)),this.#t.capacity<r*1.5){let e=Math.max(this.rate,r*2);this.#t=this.#t.resize(e),this.#t.setLatency(r);let t={type:"init-shared",...this.#t.init};this.#e.port.postMessage(t)}else this.#t.setLatency(r)}reset(){this.#t.reset(),this.#i.flush()}wait(r){return this.#t.stalled?Promise.resolve():this.#i.wait(r,this.#t.timestamp)}close(){this.#i.flush(),this.#s.close()}},QA=class{rate;channels;#e;#t=new A(0);timestamp=this.#t;#r=new A(!0);stalled=this.#r;#n;#i=new j;constructor(r,e,t,n,i){this.#e=r,this.channels=e,this.rate=t,this.#n=new wm(i,$o(n,t));let s={type:"init-post",channels:e,rate:t,latency:E.Milli.fromSecond(n/t),buffered:i};r.port.postMessage(s),this.#i.event(r.port,"message",a=>{let o=a.data;o?.type==="state"&&(this.#t.set(o.timestamp),this.#r.set(o.stalled),o.stalled?this.#n.flush():this.#n.advance(o.timestamp))}),r.port.start()}insert(r,e){let t={type:"data",data:e,timestamp:r};this.#e.port.postMessage(t,e.map(n=>n.buffer))}setLatency(r){this.#n.setHeadroom($o(r,this.rate));let e={type:"latency",latency:E.Milli.fromSecond(r/this.rate)};this.#e.port.postMessage(e)}reset(){this.#e.port.postMessage({type:"reset"}),this.#n.flush()}wait(r){return this.#r.peek()?Promise.resolve():this.#n.wait(r,this.#t.peek())}close(){this.#n.flush(),this.#i.close()}},JA=new Blob([`var __defProp = Object.defineProperty;
|
|
3
|
+
var __export = (target, all) => {
|
|
4
|
+
for (var name in all)
|
|
5
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// ../net/src/time.ts
|
|
9
|
+
var time_exports = {};
|
|
10
|
+
__export(time_exports, {
|
|
11
|
+
Micro: () => Micro,
|
|
12
|
+
Milli: () => Milli,
|
|
13
|
+
Nano: () => Nano,
|
|
14
|
+
Second: () => Second,
|
|
15
|
+
Timescale: () => Timescale,
|
|
16
|
+
Timestamp: () => Timestamp
|
|
17
|
+
});
|
|
18
|
+
var Nano = Object.assign((value) => value, {
|
|
19
|
+
zero: 0,
|
|
20
|
+
fromMicro: (us) => us * 1e3,
|
|
21
|
+
fromMilli: (ms) => ms * 1e6,
|
|
22
|
+
fromSecond: (s) => s * 1e9,
|
|
23
|
+
toMicro: (ns) => ns / 1e3,
|
|
24
|
+
toMilli: (ns) => ns / 1e6,
|
|
25
|
+
toSecond: (ns) => ns / 1e9,
|
|
26
|
+
now: () => performance.now() * 1e6,
|
|
27
|
+
add: (a, b) => a + b,
|
|
28
|
+
sub: (a, b) => a - b,
|
|
29
|
+
mul: (a, b) => a * b,
|
|
30
|
+
div: (a, b) => a / b,
|
|
31
|
+
max: (a, b) => Math.max(a, b),
|
|
32
|
+
min: (a, b) => Math.min(a, b)
|
|
33
|
+
});
|
|
34
|
+
var Micro = Object.assign((value) => value, {
|
|
35
|
+
zero: 0,
|
|
36
|
+
fromNano: (ns) => ns / 1e3,
|
|
37
|
+
fromMilli: (ms) => ms * 1e3,
|
|
38
|
+
fromSecond: (s) => s * 1e6,
|
|
39
|
+
toNano: (us) => us * 1e3,
|
|
40
|
+
toMilli: (us) => us / 1e3,
|
|
41
|
+
toSecond: (us) => us / 1e6,
|
|
42
|
+
now: () => performance.now() * 1e3,
|
|
43
|
+
add: (a, b) => a + b,
|
|
44
|
+
sub: (a, b) => a - b,
|
|
45
|
+
mul: (a, b) => a * b,
|
|
46
|
+
div: (a, b) => a / b,
|
|
47
|
+
max: (a, b) => Math.max(a, b),
|
|
48
|
+
min: (a, b) => Math.min(a, b)
|
|
49
|
+
});
|
|
50
|
+
var Milli = Object.assign((value) => value, {
|
|
51
|
+
zero: 0,
|
|
52
|
+
fromNano: (ns) => ns / 1e6,
|
|
53
|
+
fromMicro: (us) => us / 1e3,
|
|
54
|
+
fromSecond: (s) => s * 1e3,
|
|
55
|
+
toNano: (ms) => ms * 1e6,
|
|
56
|
+
toMicro: (ms) => ms * 1e3,
|
|
57
|
+
toSecond: (ms) => ms / 1e3,
|
|
58
|
+
now: () => performance.now(),
|
|
59
|
+
add: (a, b) => a + b,
|
|
60
|
+
sub: (a, b) => a - b,
|
|
61
|
+
mul: (a, b) => a * b,
|
|
62
|
+
div: (a, b) => a / b,
|
|
63
|
+
max: (a, b) => Math.max(a, b),
|
|
64
|
+
min: (a, b) => Math.min(a, b)
|
|
65
|
+
});
|
|
66
|
+
var Timescale = Object.assign(
|
|
67
|
+
(unitsPerSecond) => {
|
|
68
|
+
if (!Number.isInteger(unitsPerSecond) || unitsPerSecond <= 0) {
|
|
69
|
+
throw new Error(\`invalid timescale: \${unitsPerSecond}\`);
|
|
70
|
+
}
|
|
71
|
+
return unitsPerSecond;
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
/** One unit per second. */
|
|
75
|
+
SECOND: 1,
|
|
76
|
+
/** 1,000 units per second. */
|
|
77
|
+
MILLI: 1e3,
|
|
78
|
+
/** 1,000,000 units per second. */
|
|
79
|
+
MICRO: 1e6,
|
|
80
|
+
/** 1,000,000,000 units per second. */
|
|
81
|
+
NANO: 1e9
|
|
82
|
+
}
|
|
83
|
+
);
|
|
84
|
+
var Timestamp = class _Timestamp {
|
|
85
|
+
/** The raw value, in \`scale\` units. */
|
|
86
|
+
value;
|
|
87
|
+
/** Units per second the {@link value} is measured in. */
|
|
88
|
+
scale;
|
|
89
|
+
/** Build a timestamp of \`value\` units at \`scale\`. */
|
|
90
|
+
constructor(value, scale) {
|
|
91
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
92
|
+
throw new Error(\`invalid timestamp: \${value}\`);
|
|
93
|
+
}
|
|
94
|
+
this.value = value;
|
|
95
|
+
this.scale = scale;
|
|
96
|
+
}
|
|
97
|
+
/** Monotonic now (\`performance.now()\`, milliseconds since page load), not wall-clock time. */
|
|
98
|
+
static now() {
|
|
99
|
+
return new _Timestamp(performance.now(), Timescale.MILLI);
|
|
100
|
+
}
|
|
101
|
+
/** A timestamp of \`ms\` milliseconds. */
|
|
102
|
+
static fromMillis(ms) {
|
|
103
|
+
return new _Timestamp(ms, Timescale.MILLI);
|
|
104
|
+
}
|
|
105
|
+
/** A timestamp of \`us\` microseconds. */
|
|
106
|
+
static fromMicros(us) {
|
|
107
|
+
return new _Timestamp(us, Timescale.MICRO);
|
|
108
|
+
}
|
|
109
|
+
/** This timestamp's value re-expressed at \`scale\` (a raw number, not a new Timestamp). */
|
|
110
|
+
as(scale) {
|
|
111
|
+
return scale === this.scale ? this.value : this.value * scale / this.scale;
|
|
112
|
+
}
|
|
113
|
+
/** The value in milliseconds. */
|
|
114
|
+
asMillis() {
|
|
115
|
+
return this.as(Timescale.MILLI);
|
|
116
|
+
}
|
|
117
|
+
/** The value in microseconds. */
|
|
118
|
+
asMicros() {
|
|
119
|
+
return this.as(Timescale.MICRO);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
var Second = Object.assign((value) => value, {
|
|
123
|
+
zero: 0,
|
|
124
|
+
fromNano: (ns) => ns / 1e9,
|
|
125
|
+
fromMicro: (us) => us / 1e6,
|
|
126
|
+
fromMilli: (ms) => ms / 1e3,
|
|
127
|
+
toNano: (s) => s * 1e9,
|
|
128
|
+
toMicro: (s) => s * 1e6,
|
|
129
|
+
toMilli: (s) => s * 1e3,
|
|
130
|
+
now: () => performance.now() / 1e3,
|
|
131
|
+
add: (a, b) => a + b,
|
|
132
|
+
sub: (a, b) => a - b,
|
|
133
|
+
mul: (a, b) => a * b,
|
|
134
|
+
div: (a, b) => a / b,
|
|
135
|
+
max: (a, b) => Math.max(a, b),
|
|
136
|
+
min: (a, b) => Math.min(a, b)
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// src/audio/ring-buffer.ts
|
|
140
|
+
var AudioRingBuffer = class {
|
|
141
|
+
#buffer;
|
|
142
|
+
#writeIndex = 0;
|
|
143
|
+
#readIndex = 0;
|
|
144
|
+
rate;
|
|
145
|
+
channels;
|
|
146
|
+
#stalled = true;
|
|
147
|
+
// Buffered mode: anchor to the first sample, play through without skipping ahead.
|
|
148
|
+
#buffered;
|
|
149
|
+
// Un-stall threshold in samples (how much to buffer before playback starts).
|
|
150
|
+
#latencySamples;
|
|
151
|
+
// Whether the read/write indices have been anchored to the first inserted sample.
|
|
152
|
+
#anchored = false;
|
|
153
|
+
constructor(props) {
|
|
154
|
+
if (props.channels <= 0) throw new Error("invalid channels");
|
|
155
|
+
if (props.rate <= 0) throw new Error("invalid sample rate");
|
|
156
|
+
if (props.latency <= 0) throw new Error("invalid latency");
|
|
157
|
+
this.#latencySamples = Math.ceil(props.rate * time_exports.Second.fromMilli(props.latency));
|
|
158
|
+
if (this.#latencySamples === 0) throw new Error("empty buffer");
|
|
159
|
+
this.rate = props.rate;
|
|
160
|
+
this.channels = props.channels;
|
|
161
|
+
this.#buffered = props.buffered ?? false;
|
|
162
|
+
const capacity = this.#capacityFor(this.#latencySamples);
|
|
163
|
+
this.#buffer = [];
|
|
164
|
+
for (let i = 0; i < this.channels; i++) {
|
|
165
|
+
this.#buffer[i] = new Float32Array(capacity);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
#capacityFor(latencySamples) {
|
|
169
|
+
return this.#buffered ? latencySamples * 2 : latencySamples;
|
|
170
|
+
}
|
|
171
|
+
get stalled() {
|
|
172
|
+
return this.#stalled;
|
|
173
|
+
}
|
|
174
|
+
get timestamp() {
|
|
175
|
+
return time_exports.Micro.fromSecond(this.#readIndex / this.rate);
|
|
176
|
+
}
|
|
177
|
+
get length() {
|
|
178
|
+
return this.#writeIndex - this.#readIndex;
|
|
179
|
+
}
|
|
180
|
+
get capacity() {
|
|
181
|
+
return this.#buffer[0]?.length;
|
|
182
|
+
}
|
|
183
|
+
resize(latency) {
|
|
184
|
+
this.#latencySamples = Math.ceil(this.rate * time_exports.Second.fromMilli(latency));
|
|
185
|
+
const newCapacity = this.#capacityFor(this.#latencySamples);
|
|
186
|
+
if (newCapacity === this.capacity) return;
|
|
187
|
+
if (newCapacity === 0) throw new Error("empty buffer");
|
|
188
|
+
const newBuffer = [];
|
|
189
|
+
for (let i = 0; i < this.channels; i++) {
|
|
190
|
+
newBuffer[i] = new Float32Array(newCapacity);
|
|
191
|
+
}
|
|
192
|
+
const samplesToKeep = Math.min(this.length, newCapacity);
|
|
193
|
+
if (samplesToKeep > 0) {
|
|
194
|
+
const copyStart = this.#writeIndex - samplesToKeep;
|
|
195
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
196
|
+
const src = this.#buffer[channel];
|
|
197
|
+
const dst = newBuffer[channel];
|
|
198
|
+
for (let i = 0; i < samplesToKeep; i++) {
|
|
199
|
+
const srcPos = (copyStart + i) % src.length;
|
|
200
|
+
const dstPos = (copyStart + i) % dst.length;
|
|
201
|
+
dst[dstPos] = src[srcPos];
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
this.#buffer = newBuffer;
|
|
206
|
+
this.#readIndex = this.#writeIndex - samplesToKeep;
|
|
207
|
+
if (samplesToKeep === 0) this.#stalled = true;
|
|
208
|
+
}
|
|
209
|
+
write(timestamp, data) {
|
|
210
|
+
if (data.length !== this.channels) throw new Error("wrong number of channels");
|
|
211
|
+
let start = Math.round(time_exports.Second.fromMicro(timestamp) * this.rate);
|
|
212
|
+
let samples = data[0].length;
|
|
213
|
+
if (this.#buffered && !this.#anchored) {
|
|
214
|
+
this.#readIndex = start;
|
|
215
|
+
this.#writeIndex = start;
|
|
216
|
+
this.#anchored = true;
|
|
217
|
+
}
|
|
218
|
+
let offset = this.#readIndex - start;
|
|
219
|
+
if (offset > samples) {
|
|
220
|
+
return;
|
|
221
|
+
} else if (offset > 0) {
|
|
222
|
+
samples -= offset;
|
|
223
|
+
start += offset;
|
|
224
|
+
} else {
|
|
225
|
+
offset = 0;
|
|
226
|
+
}
|
|
227
|
+
const end = start + samples;
|
|
228
|
+
const overflow = end - this.#readIndex - this.#buffer[0].length;
|
|
229
|
+
if (overflow >= 0) {
|
|
230
|
+
this.#stalled = false;
|
|
231
|
+
this.#readIndex += overflow;
|
|
232
|
+
}
|
|
233
|
+
if (start > this.#writeIndex) {
|
|
234
|
+
const gapSize = Math.min(start - this.#writeIndex, this.#buffer[0].length);
|
|
235
|
+
if (gapSize === 1) {
|
|
236
|
+
console.warn("floating point inaccuracy detected");
|
|
237
|
+
}
|
|
238
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
239
|
+
const dst = this.#buffer[channel];
|
|
240
|
+
for (let i = 0; i < gapSize; i++) {
|
|
241
|
+
const writePos = (this.#writeIndex + i) % dst.length;
|
|
242
|
+
dst[writePos] = 0;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
247
|
+
let src = data[channel];
|
|
248
|
+
src = src.subarray(src.length - samples);
|
|
249
|
+
const dst = this.#buffer[channel];
|
|
250
|
+
if (src.length !== samples) throw new Error("mismatching number of samples");
|
|
251
|
+
for (let i = 0; i < samples; i++) {
|
|
252
|
+
const writePos = (start + i) % dst.length;
|
|
253
|
+
dst[writePos] = src[i];
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (end > this.#writeIndex) {
|
|
257
|
+
this.#writeIndex = end;
|
|
258
|
+
}
|
|
259
|
+
if (this.#buffered && this.length >= this.#latencySamples) {
|
|
260
|
+
this.#stalled = false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// Flush all buffered samples and re-stall, ready to anchor the next utterance.
|
|
264
|
+
reset() {
|
|
265
|
+
this.#readIndex = 0;
|
|
266
|
+
this.#writeIndex = 0;
|
|
267
|
+
this.#stalled = true;
|
|
268
|
+
this.#anchored = false;
|
|
269
|
+
}
|
|
270
|
+
read(output) {
|
|
271
|
+
if (output.length !== this.channels) throw new Error("wrong number of channels");
|
|
272
|
+
if (this.#stalled) return 0;
|
|
273
|
+
const samples = Math.min(this.#writeIndex - this.#readIndex, output[0].length);
|
|
274
|
+
if (samples === 0) return 0;
|
|
275
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
276
|
+
const dst = output[channel];
|
|
277
|
+
const src = this.#buffer[channel];
|
|
278
|
+
if (dst.length !== output[0].length) throw new Error("mismatching number of samples");
|
|
279
|
+
for (let i = 0; i < samples; i++) {
|
|
280
|
+
const readPos = (this.#readIndex + i) % src.length;
|
|
281
|
+
dst[i] = src[readPos];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
this.#readIndex += samples;
|
|
285
|
+
return samples;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// src/audio/shared-ring-buffer.ts
|
|
290
|
+
var WRITE = 0;
|
|
291
|
+
var READ = 1;
|
|
292
|
+
var LATENCY = 2;
|
|
293
|
+
var STALLED = 3;
|
|
294
|
+
var CONTROL_SLOTS = 4;
|
|
295
|
+
function allocSharedRingBuffer(channels, capacity, rate, buffered = false) {
|
|
296
|
+
if (channels <= 0) throw new Error("invalid channels");
|
|
297
|
+
if (capacity <= 0) throw new Error("invalid capacity");
|
|
298
|
+
if (rate <= 0) throw new Error("invalid sample rate");
|
|
299
|
+
const samples = new SharedArrayBuffer(channels * capacity * Float32Array.BYTES_PER_ELEMENT);
|
|
300
|
+
const control = new SharedArrayBuffer(CONTROL_SLOTS * Int32Array.BYTES_PER_ELEMENT);
|
|
301
|
+
const ctrl = new Int32Array(control);
|
|
302
|
+
Atomics.store(ctrl, STALLED, 1);
|
|
303
|
+
return { channels, capacity, rate, samples, control, buffered };
|
|
304
|
+
}
|
|
305
|
+
function i32Max(a, b) {
|
|
306
|
+
return (a - b | 0) > 0 ? a : b;
|
|
307
|
+
}
|
|
308
|
+
function slot(idx, capacity) {
|
|
309
|
+
return (idx % capacity + capacity) % capacity;
|
|
310
|
+
}
|
|
311
|
+
function casAdvance(arr, idx, candidate) {
|
|
312
|
+
for (; ; ) {
|
|
313
|
+
const current = Atomics.load(arr, idx);
|
|
314
|
+
if ((candidate - current | 0) <= 0) return current;
|
|
315
|
+
const witnessed = Atomics.compareExchange(arr, idx, current, candidate);
|
|
316
|
+
if (witnessed === current) return candidate;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
var SharedRingBuffer = class _SharedRingBuffer {
|
|
320
|
+
channels;
|
|
321
|
+
capacity;
|
|
322
|
+
rate;
|
|
323
|
+
buffered;
|
|
324
|
+
init;
|
|
325
|
+
#control;
|
|
326
|
+
#samples;
|
|
327
|
+
// Whether READ/WRITE have been anchored to the first inserted sample (buffered mode).
|
|
328
|
+
#anchored = false;
|
|
329
|
+
constructor(init) {
|
|
330
|
+
this.channels = init.channels;
|
|
331
|
+
this.capacity = init.capacity;
|
|
332
|
+
this.rate = init.rate;
|
|
333
|
+
this.buffered = init.buffered;
|
|
334
|
+
this.init = init;
|
|
335
|
+
this.#control = new Int32Array(init.control);
|
|
336
|
+
this.#samples = [];
|
|
337
|
+
for (let i = 0; i < this.channels; i++) {
|
|
338
|
+
this.#samples.push(
|
|
339
|
+
new Float32Array(init.samples, i * this.capacity * Float32Array.BYTES_PER_ELEMENT, this.capacity)
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Insert audio samples at the given timestamp.
|
|
345
|
+
* Main thread only. Handles out-of-order writes, gap filling, and overflow.
|
|
346
|
+
*/
|
|
347
|
+
insert(timestamp, data) {
|
|
348
|
+
if (data.length !== this.channels) throw new Error("wrong number of channels");
|
|
349
|
+
let start = Math.round(time_exports.Second.fromMicro(timestamp) * this.rate);
|
|
350
|
+
const originalLength = data[0].length;
|
|
351
|
+
let offset = 0;
|
|
352
|
+
if (this.buffered && !this.#anchored) {
|
|
353
|
+
Atomics.store(this.#control, READ, start | 0);
|
|
354
|
+
Atomics.store(this.#control, WRITE, start | 0);
|
|
355
|
+
this.#anchored = true;
|
|
356
|
+
}
|
|
357
|
+
const end = start + originalLength | 0;
|
|
358
|
+
const read = Atomics.load(this.#control, READ);
|
|
359
|
+
const behind = read - start | 0;
|
|
360
|
+
if (behind > 0) {
|
|
361
|
+
if (behind >= originalLength) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
offset = behind;
|
|
365
|
+
start = start + behind | 0;
|
|
366
|
+
}
|
|
367
|
+
const samples = originalLength - offset;
|
|
368
|
+
if ((end - read | 0) > this.capacity) {
|
|
369
|
+
casAdvance(this.#control, READ, end - this.capacity | 0);
|
|
370
|
+
}
|
|
371
|
+
const write = Atomics.load(this.#control, WRITE);
|
|
372
|
+
const gap = start - write | 0;
|
|
373
|
+
if (gap > 0) {
|
|
374
|
+
const gapSize = Math.min(gap, this.capacity);
|
|
375
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
376
|
+
const dst = this.#samples[channel];
|
|
377
|
+
for (let i = 0; i < gapSize; i++) {
|
|
378
|
+
dst[slot(write + i | 0, this.capacity)] = 0;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
383
|
+
const src = data[channel];
|
|
384
|
+
const dst = this.#samples[channel];
|
|
385
|
+
for (let i = 0; i < samples; i++) {
|
|
386
|
+
dst[slot(start + i | 0, this.capacity)] = src[offset + i];
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
Atomics.store(this.#control, WRITE, i32Max(Atomics.load(this.#control, WRITE), end));
|
|
390
|
+
const currentRead = Atomics.load(this.#control, READ);
|
|
391
|
+
const currentWrite = Atomics.load(this.#control, WRITE);
|
|
392
|
+
const latency = Atomics.load(this.#control, LATENCY);
|
|
393
|
+
if ((currentWrite - currentRead | 0) >= latency && latency > 0) {
|
|
394
|
+
Atomics.store(this.#control, STALLED, 0);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Read audio samples into the output buffers.
|
|
399
|
+
* AudioWorklet only. Returns the number of samples read.
|
|
400
|
+
*/
|
|
401
|
+
read(output) {
|
|
402
|
+
if (Atomics.load(this.#control, STALLED) === 1) return 0;
|
|
403
|
+
let read = Atomics.load(this.#control, READ);
|
|
404
|
+
const write = Atomics.load(this.#control, WRITE);
|
|
405
|
+
const latency = Atomics.load(this.#control, LATENCY);
|
|
406
|
+
const buffered = write - read | 0;
|
|
407
|
+
if (!this.buffered && latency > 0 && buffered > latency) {
|
|
408
|
+
const skipTo = write - latency | 0;
|
|
409
|
+
read = casAdvance(this.#control, READ, skipTo);
|
|
410
|
+
}
|
|
411
|
+
const available = write - read | 0;
|
|
412
|
+
const count = Math.min(available, output[0].length);
|
|
413
|
+
if (count <= 0) return 0;
|
|
414
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
415
|
+
const src = this.#samples[channel];
|
|
416
|
+
const dst = output[channel];
|
|
417
|
+
for (let i = 0; i < count; i++) {
|
|
418
|
+
dst[i] = src[slot(read + i | 0, this.capacity)];
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
casAdvance(this.#control, READ, read + count | 0);
|
|
422
|
+
return count;
|
|
423
|
+
}
|
|
424
|
+
/** Update the target latency in samples. */
|
|
425
|
+
setLatency(samples) {
|
|
426
|
+
Atomics.store(this.#control, LATENCY, samples);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Flush buffered samples and re-stall, ready to anchor the next utterance (buffered mode).
|
|
430
|
+
* Main thread only. The worklet reader sees STALLED and stops until the next insert.
|
|
431
|
+
*/
|
|
432
|
+
reset() {
|
|
433
|
+
this.#anchored = false;
|
|
434
|
+
Atomics.store(this.#control, STALLED, 1);
|
|
435
|
+
const write = Atomics.load(this.#control, WRITE);
|
|
436
|
+
Atomics.store(this.#control, READ, write);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Allocate a new ring with \`newCapacity\` samples and copy the unread window
|
|
440
|
+
* [READ, WRITE) plus control state into it. Used when growing capacity so
|
|
441
|
+
* we don't drop buffered audio. If \`newCapacity\` is smaller than the unread
|
|
442
|
+
* span, the oldest samples are truncated.
|
|
443
|
+
*
|
|
444
|
+
* Main thread only. \`resize()\` reads from the source \`SharedRingBuffer\` and
|
|
445
|
+
* writes into a freshly allocated buffer from \`allocSharedRingBuffer\`, so it
|
|
446
|
+
* relies on the same invariant as \`insert()\`: no concurrent main-thread
|
|
447
|
+
* writers. The AudioWorklet reader is tolerated via the CAS discipline used
|
|
448
|
+
* by READ/WRITE elsewhere.
|
|
449
|
+
*/
|
|
450
|
+
resize(newCapacity) {
|
|
451
|
+
const init = allocSharedRingBuffer(this.channels, newCapacity, this.rate, this.buffered);
|
|
452
|
+
const dst = new _SharedRingBuffer(init);
|
|
453
|
+
dst.#anchored = this.#anchored;
|
|
454
|
+
const read = Atomics.load(this.#control, READ);
|
|
455
|
+
const write = Atomics.load(this.#control, WRITE);
|
|
456
|
+
const latency = Atomics.load(this.#control, LATENCY);
|
|
457
|
+
const stalled = Atomics.load(this.#control, STALLED);
|
|
458
|
+
const available = write - read | 0;
|
|
459
|
+
const copyCount = Math.max(0, Math.min(available, dst.capacity));
|
|
460
|
+
const copyStart = write - copyCount | 0;
|
|
461
|
+
for (let channel = 0; channel < this.channels; channel++) {
|
|
462
|
+
const src = this.#samples[channel];
|
|
463
|
+
const out = dst.#samples[channel];
|
|
464
|
+
for (let i = 0; i < copyCount; i++) {
|
|
465
|
+
const idx = copyStart + i | 0;
|
|
466
|
+
out[slot(idx, dst.capacity)] = src[slot(idx, this.capacity)];
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
Atomics.store(dst.#control, READ, copyStart);
|
|
470
|
+
Atomics.store(dst.#control, WRITE, write);
|
|
471
|
+
Atomics.store(dst.#control, LATENCY, latency);
|
|
472
|
+
Atomics.store(dst.#control, STALLED, stalled);
|
|
473
|
+
return dst;
|
|
474
|
+
}
|
|
475
|
+
/** Current playback timestamp derived from READ position. */
|
|
476
|
+
get timestamp() {
|
|
477
|
+
const read = Atomics.load(this.#control, READ);
|
|
478
|
+
return time_exports.Micro.fromSecond(read / this.rate);
|
|
479
|
+
}
|
|
480
|
+
/** Whether the buffer is stalled (waiting to fill). */
|
|
481
|
+
get stalled() {
|
|
482
|
+
return Atomics.load(this.#control, STALLED) === 1;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Number of buffered samples (WRITE - READ).
|
|
486
|
+
*
|
|
487
|
+
* Non-atomic: WRITE and READ are loaded separately, so a concurrent
|
|
488
|
+
* writer/reader can make the two loads inconsistent. Intended for
|
|
489
|
+
* tests and diagnostics, not control-flow decisions.
|
|
490
|
+
*/
|
|
491
|
+
get length() {
|
|
492
|
+
return Atomics.load(this.#control, WRITE) - Atomics.load(this.#control, READ) | 0;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
// src/audio/render-worklet.ts
|
|
497
|
+
var Render = class extends AudioWorkletProcessor {
|
|
498
|
+
// Set after init, depending on which path the main thread chose.
|
|
499
|
+
#backend;
|
|
500
|
+
#underflow = 0;
|
|
501
|
+
#stateCounter = 0;
|
|
502
|
+
constructor() {
|
|
503
|
+
super();
|
|
504
|
+
this.port.onmessage = (event) => {
|
|
505
|
+
const msg = event.data;
|
|
506
|
+
if (msg.type === "init-shared") {
|
|
507
|
+
console.log("[audio-worklet] init-shared: using SharedArrayBuffer path");
|
|
508
|
+
this.#backend = new SharedRingBuffer(msg);
|
|
509
|
+
this.#underflow = 0;
|
|
510
|
+
} else if (msg.type === "init-post") {
|
|
511
|
+
console.log("[audio-worklet] init-post: using postMessage path");
|
|
512
|
+
this.#backend = new AudioRingBuffer(msg);
|
|
513
|
+
this.#underflow = 0;
|
|
514
|
+
} else if (msg.type === "data") {
|
|
515
|
+
if (this.#backend instanceof AudioRingBuffer) this.#backend.write(msg.timestamp, msg.data);
|
|
516
|
+
} else if (msg.type === "latency") {
|
|
517
|
+
if (this.#backend instanceof AudioRingBuffer) this.#backend.resize(msg.latency);
|
|
518
|
+
} else if (msg.type === "reset") {
|
|
519
|
+
if (this.#backend instanceof AudioRingBuffer) this.#backend.reset();
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
process(_inputs, outputs, _parameters) {
|
|
524
|
+
const output = outputs[0];
|
|
525
|
+
const backend = this.#backend;
|
|
526
|
+
const samplesRead = backend?.read(output) ?? 0;
|
|
527
|
+
if (samplesRead < output[0].length) {
|
|
528
|
+
this.#underflow += output[0].length - samplesRead;
|
|
529
|
+
} else if (this.#underflow > 0 && backend) {
|
|
530
|
+
console.debug(\`audio underflow: \${Math.round(1e3 * this.#underflow / backend.rate)}ms\`);
|
|
531
|
+
this.#underflow = 0;
|
|
532
|
+
}
|
|
533
|
+
if (backend instanceof AudioRingBuffer) {
|
|
534
|
+
this.#stateCounter++;
|
|
535
|
+
if (this.#stateCounter >= 5) {
|
|
536
|
+
this.#stateCounter = 0;
|
|
537
|
+
const state = {
|
|
538
|
+
type: "state",
|
|
539
|
+
timestamp: backend.timestamp,
|
|
540
|
+
stalled: backend.stalled
|
|
541
|
+
};
|
|
542
|
+
this.port.postMessage(state);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
registerProcessor("render", Render);
|
|
549
|
+
`],{type:"application/javascript"}),ex=URL.createObjectURL(JA),tx=class{#e=0;#t;#r;#n=0;#i;get end(){return this.#t}clear(r=0){this.#e=0,this.#t=void 0,this.#n=r,this.#s()}update(r){let e=r.discontinuity!==this.#e;return e&&(this.#e=r.discontinuity,this.#t=void 0,this.#s()),r.frame&&this.#r===void 0&&(this.#r=r.frame.timestamp),r.end!==void 0&&(this.#t=r.end),e}span(r){let e=this.#r??r.timestamp;this.#r=e;let t=Math.floor(this.#n*r.sampleRate/48e3),n=this.#i??t,i=Math.min(n,r.numberOfFrames);this.#i=n-i;let s=Math.round(t*1e6/r.sampleRate),a=Math.max(e,r.timestamp-s),o=r.numberOfFrames-i;if(this.#t!==void 0)if(this.#t<=a)o=0;else{let c=this.#t-a,u=Math.round(c*r.sampleRate/1e6);o=Math.min(o,u)}return{timestamp:a,frameOffset:i,frames:o}}#s(){this.#r=void 0,this.#i=void 0}};function rx(r,e){let t=new A(e.state==="running");r.event(e,"statechange",()=>t.set(e.state==="running")),r.run(n=>{if(n.get(t))return;let i=()=>{e.resume().catch(()=>{})};i(),n.event(document,"pointerdown",i),n.event(document,"keydown",i)})}var nx=class{#e;constructor(r){this.#e=r}drop(){return this.#e!==0&&(this.#e--,!0)}},ix=150,sx=3,Au=class{in;source;sync;#e={context:new A(void 0),root:new A(void 0),sampleRate:new A(void 0),stats:new A(void 0),timestamp:new A(void 0),stalled:new A(!0),buffered:new A([])};out=this.#e;#t=new A([]);#r;#n=new A(void 0);#i=new tx;#s=new A(E.Milli.zero);#o;#a=new j;constructor(r,e,t){this.in={enabled:N(t?.enabled??!1)},this.source=r,this.sync=e,this.#a.run(n=>{this.#s.set(n.get(this.sync.out.maxBuffer))}),this.#a.run(this.#c.bind(this)),this.#a.run(this.#d.bind(this)),this.#a.run(this.#l.bind(this)),this.#a.run(this.#u.bind(this)),this.#a.run(this.#f.bind(this))}#c(r){let e=r.get(this.source.out.config);if(!e)return;let t=r.get(this.#n)??e.sampleRate,n=e.numberOfChannels;r.set(this.#e.sampleRate,t);let i=new AudioContext({latencyHint:"interactive",sampleRate:t});r.set(this.#e.context,i),r.cleanup(()=>i.close()),r.spawn(async()=>{if(!await Promise.race([i.audioWorklet.addModule(ex).then(()=>!0),r.cancel]))return;let s=new AudioWorkletNode(i,"render",{channelCount:n,channelCountMode:"explicit",outputChannelCount:[n]});r.cleanup(()=>s.disconnect());let a=this.sync.out.buffer.peek(),o=Math.ceil(t*E.Second.fromMilli(a)),c=this.sync.out.buffered.peek(),u=YA(s,n,t,o,c);this.#r=u,r.cleanup(()=>{u.close(),this.#r=void 0}),r.run(d=>{let f=E.Milli.fromMicro(d.get(u.timestamp));this.#e.timestamp.set(f),this.#v(f)}),r.run(d=>{this.#e.stalled.set(d.get(u.stalled))}),r.set(this.#e.root,s)})}#d(r){if(!r.get(this.in.enabled))return;let e=r.get(this.#e.context);e&&rx(r,e)}#l(r){if(!r.get(this.#e.root))return;let e=this.#r;if(!e)return;let t=r.get(this.sync.out.buffer),n=Math.ceil(e.rate*E.Second.fromMilli(t));e.setLatency(n)}#u(r){let e=Ke(r.get(this.sync.in.latency)).min;if(this.#o===void 0){this.#o=e;return}let t=this.#o;r.timer(()=>{let n=i=>i==="real-time"?0:i;n(e)>n(t)&&this.reset(),this.#o=e},ix)}#f(r){if(!r.get(this.in.enabled))return;let e=r.get(this.source.in.broadcast);if(!e)return;let t=r.get(this.source.out.track);if(!t)return;let n=r.get(this.source.out.config);if(!n)return;let i=e.relativeBroadcast(r,n.broadcast);if(!i)return;let s=i.track(t).subscribe({priority:po.audio});r.cleanup(()=>s.close()),n.container.kind==="cmaf"?this.#m(r,s,n):this.#p(r,s,n)}#p(r,e,t){let n=t.codec==="opus"&&t.description?kr.preSkip(Ze.toBytes(t.description)):0;this.#i.clear(n);let i=t.container.kind==="loc"?new Mi.Format:new zi.Format,s=new Yt(e,{format:i,latency:this.#s});r.cleanup(()=>s.close()),r.run(a=>{let o=a.get(s.buffered),c=a.get(this.#t);this.#e.buffered.update(()=>qi(o,c))}),r.spawn(async()=>{if(!await Ji.polyfill())return;let a=new nx(sx),o=new AudioDecoder({output:d=>{let f=this.#i.span(d);if(a.drop()){d.close();return}this.#b(d,f)},error:d=>console.error("audio decoder error",d)});r.cleanup(()=>{o.state!=="closed"&&o.close()});let c=t.codec==="opus"?void 0:t.description?Ze.toBytes(t.description):void 0,u={...t,description:c};for(o.configure(u);;){let d=await s.next();if(!d)break;if(this.#g(d)&&(o.reset(),o.configure(u)),d.end!==void 0)continue;let{frame:f}=d;if(!f)continue;let l=E.Milli.fromMicro(f.timestamp);this.sync.received(l,"audio"),this.#e.stats.update(p=>({bytesReceived:(p?.bytesReceived??0)+f.payload.byteLength})),await this.#r?.wait(f.timestamp);let h=new EncodedAudioChunk({type:f.keyframe?"key":"delta",data:f.payload,timestamp:f.timestamp});if(o.state==="closed")break;o.decode(h)}})}#m(r,e,t){if(t.container.kind!=="cmaf")return;let n=rs(t.container.init),i=kt.decodeInitSegment(n),s=t.description?Ze.toBytes(t.description):i.description,a=t.codec==="opus"&&s?kr.preSkip(s):0;this.#i.clear(a);let o=t.codec==="opus"?void 0:t.description?Ze.toBytes(t.description):i.description,c=new Yt(e,{format:new kt.Format(i),latency:this.#s});r.cleanup(()=>c.close()),r.run(u=>{let d=u.get(c.buffered),f=u.get(this.#t);this.#e.buffered.update(()=>qi(d,f))}),r.spawn(async()=>{if(!await Ji.polyfill())return;let u=new AudioDecoder({output:f=>this.#b(f),error:f=>console.error("audio decoder error",f)});r.cleanup(()=>{u.state!=="closed"&&u.close()});let d={codec:t.codec,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,description:o};for(u.configure(d);;){let f=await c.next();if(!f)break;this.#g(f)&&(u.reset(),u.configure(d));let{frame:l}=f;if(!l)continue;let h=E.Milli.fromMicro(l.timestamp);if(this.sync.received(h,"audio"),this.#e.stats.update(p=>({bytesReceived:(p?.bytesReceived??0)+l.payload.byteLength})),await this.#r?.wait(l.timestamp),u.state==="closed")break;u.decode(new EncodedAudioChunk({type:l.keyframe?"key":"delta",data:l.payload,timestamp:l.timestamp}))}})}#b(r,e=this.#i.span(r)){let{timestamp:t,frameOffset:n,frames:i}=e,s=E.Milli.fromMicro(t);if(i===0){r.close();return}let a=this.#r;if(!a){r.close();return}if(r.sampleRate!==a.rate){this.#n.set(r.sampleRate),r.close();return}let o=i/r.sampleRate*1e6,c=E.Milli.fromMicro(o),u=E.Milli.add(s,c);this.#x(s,u);let d=Math.min(r.numberOfChannels,a.channels),f=[];for(let l=0;l<d;l++){let h=new Float32Array(i);r.copyTo(h,{format:"f32-planar",planeIndex:l,frameOffset:n,frameCount:i}),f.push(h)}a.insert(t,f),r.close()}#x(r,e){r>e||this.#t.mutate(t=>{for(let n of t)if(r<=n.end+1&&e>=n.start){n.start=E.Milli.min(n.start,r),n.end=E.Milli.max(n.end,e);return}t.push({start:r,end:e}),t.sort((n,i)=>n.start-i.start)})}#v(r){this.#t.mutate(e=>{for(;e.length>0;){if(e[0].end>=r){e[0].start=E.Milli.max(e[0].start,r);break}e.shift()}})}reset(){this.#r?.reset()}#g(r){return this.#i.update(r)?(this.#r?.reset(),this.sync.reset(),!0):!1}close(){this.#a.close()}static supported=ox};async function ox(r){if(!dc(r.container)){let t=r.container.kind==="unknown"?r.container.raw.kind:r.container.kind;return console.warn(`audio: ignoring rendition with unknown container: ${t}`),!1}r.codec==="opus"&&!kr.supportsRate(r.sampleRate)&&console.warn(`audio: opus advertised at ${r.sampleRate}Hz, which some browsers cannot decode`);let e;if(r.codec!=="opus"){if(r.description)e=Ze.toBytes(r.description);else if(r.container.kind==="cmaf")try{e=kt.decodeInitSegment(rs(r.container.init)).description}catch(t){return console.warn(`audio: malformed CMAF init segment for codec ${r.codec}`,t),!1}}return(await AudioDecoder.isConfigSupported({...r,description:e})).supported??!1}var cm=.001,vu=.2,gm=class{source;in;#e={enabled:new A(!1)};out=this.#e;#t=new j;#r=new A(void 0);constructor(r,e){this.source=r,this.in={volume:N(e?.volume??.5),muted:N(e?.muted??!1),paused:N(e?.paused??!1)},this.#t.run(t=>{let n=!t.get(this.in.paused)&&!t.get(this.in.muted);this.#e.enabled.set(n)}),this.#t.run(t=>{let n=t.get(this.source.out.root);if(!n)return;let i=new GainNode(n.context,{gain:t.get(this.in.volume)});n.connect(i),t.set(this.#r,i),t.run(s=>{s.get(this.#e.enabled)&&(i.connect(n.context.destination),s.cleanup(()=>i.disconnect()))})}),this.#t.run(t=>{let n=t.get(this.#r);if(!n)return;t.cleanup(()=>n.gain.cancelScheduledValues(n.context.currentTime));let i=t.get(this.in.volume);i<cm?(n.gain.exponentialRampToValueAtTime(cm,n.context.currentTime+vu),n.gain.setValueAtTime(0,n.context.currentTime+vu+.01)):n.gain.exponentialRampToValueAtTime(i,n.context.currentTime+vu)})}close(){this.#t.close()}},ax=128,ym=class{in;#e={catalog:new A(void 0),available:new A({}),track:new A(void 0),config:new A(void 0),jitter:new A(void 0)};out=this.#e;#t=new j;constructor(r){this.in={broadcast:N(r?.broadcast),target:N(r?.target),supported:N(r?.supported)},this.#t.run(this.#r.bind(this)),this.#t.run(this.#n.bind(this)),this.#t.run(this.#i.bind(this))}#r(r){let e=r.get(this.in.broadcast);if(!e)return;let t=r.get(e.out.catalog)?.audio;t&&r.set(this.#e.catalog,t)}#n(r){let e=r.get(this.#e.catalog)?.renditions??{},t=r.get(this.in.supported);t&&r.spawn(async()=>{let n={},i=r.cancel.then(()=>{});for(let[s,a]of Object.entries(e)){let o=await Promise.race([t(a),i]);if(r.abort.aborted)return;o&&(n[s]=a)}Object.keys(n).length===0&&Object.keys(e).length>0&&console.warn("no supported audio renditions found:",e),this.#e.available.set(n)})}#i(r){let e=r.get(this.#e.available);if(Object.keys(e).length===0)return;let t=r.get(this.in.target),n;if(t?.name&&t.name in e)n={track:t.name,config:e[t.name]};else if(n=this.#s(e),!n)return;r.set(this.#e.track,n.track),r.set(this.#e.config,n.config);let i=(n.config.jitter??cx(n.config)??0)+Math.ceil(ax/n.config.sampleRate*1e3);r.set(this.#e.jitter,E.Milli(i))}#s(r){let e=Object.entries(r);if(e.length!==0){for(let[t,n]of e)if(n.container.kind==="legacy")return{track:t,config:n};for(let[t,n]of e)if(n.container.kind==="loc")return{track:t,config:n};for(let[t,n]of e)if(n.container.kind==="cmaf")return{track:t,config:n}}}close(){this.#t.close()}};function cx(r){if(r.codec.startsWith("opus"))return 20;if(r.codec.startsWith("mp4a"))return Math.ceil(1024/r.sampleRate*1e3);if(r.codec==="mp3"){let e=r.sampleRate>=32e3?1152:576;return Math.ceil(e/r.sampleRate*1e3)}}var ux=48e3,um=2;function dx(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function bm(r){let e;try{e=r.initData?rs(r.initData):void 0}catch{e=void 0}let t=e?dx(e):void 0;switch(r.packaging){case"cmaf":return!r.initData||!e?void 0:{container:{kind:"cmaf",init:r.initData},description:void 0};case"loc":return{container:{kind:"loc"},description:t};case"legacy":return{container:{kind:"legacy"},description:t};default:return}}function lx(r){if(!r.codec)return;let e=bm(r);if(!e)return;let{container:t,description:n}=e;return{codec:r.codec,container:t,description:n,codedWidth:r.width==null?void 0:Qe(r.width),codedHeight:r.height==null?void 0:Qe(r.height),framerate:r.framerate,bitrate:r.bitrate==null?void 0:Qe(r.bitrate),stalled:r.stalled,jitter:r.jitter==null?void 0:Qe(r.jitter)}}function fx(r){if(!r.codec)return;let e=(()=>{if(!r.channelConfig)return um;let s=Number.parseInt(r.channelConfig,10);return Number.isFinite(s)?s:um})(),t=bm(r);if(!t)return;let{container:n,description:i}=t;return{codec:r.codec,container:n,description:i,sampleRate:Qe(r.samplerate??ux),numberOfChannels:Qe(e),bitrate:r.bitrate==null?void 0:Qe(r.bitrate),jitter:r.jitter==null?void 0:Qe(r.jitter)}}function hx(r){let e={},t={};for(let i of r.tracks)if(i.role==="video"){let s=lx(i);s&&(e[i.name]=s)}else if(i.role==="audio"){let s=fx(i);s&&(t[i.name]=s)}let n={};return Object.keys(e).length>0&&(n.video={renditions:e}),Object.keys(t).length>0&&(n.audio={renditions:t}),n}var dm=new WeakSet;function lm(r){return!r.discovery&&(dm.has(r)||(dm.add(r),console.warn("relay does not support broadcast discovery; subscribing to siblings blind.")),!0)}function fm(r,e){return Object.fromEntries(Object.entries(r).filter(([,t])=>e(t.broadcast)))}function px(r,e){return{...r,video:r.video?{...r.video,renditions:fm(r.video.renditions,e)}:void 0,audio:r.audio?{...r.audio,renditions:fm(r.audio.renditions,e)}:void 0}}var mx=[...lc,"hangz","manual"];function vm(r){if(r!==null)return mx.find(e=>e===r)}var Am=class{in;#e={status:new A("offline"),active:new A(void 0),catalog:new A(void 0)};out=this.#e;#t=new A(void 0);#r=new A(!1);#n=new A(void 0);#i=new j;constructor(r){this.in={connection:N(r?.connection),name:N(r?.name??W.empty()),enabled:N(r?.enabled??!1),reload:N(r?.reload??!0),catalogFormat:N(r?.catalogFormat),catalog:N(r?.catalog)},this.#i.run(this.#s.bind(this)),this.#i.run(this.#c.bind(this)),this.#i.run(this.#d.bind(this)),this.#i.run(this.#o.bind(this))}#s(r){if(this.#t.set(void 0),!r.get(this.#r)||!r.get(this.in.reload))return;let e=r.get(this.in.connection);if(!e||lm(e))return;let t=e.announced(W.empty());r.cleanup(()=>t.close()),this.#t.set(new Set),r.spawn(async()=>{for(;;){let n=await Promise.race([r.cancel,t.next()]);if(!n)break;this.#t.mutate(i=>{i&&(n.active?i.add(n.path):i.delete(n.path))})}})}#o(r){let e=r.get(this.#n);r.set(this.#e.catalog,e?px(e,t=>this.#l(r,t)!==void 0):void 0)}#a(r,e){if(!r.get(this.in.reload))return!0;let t=r.get(this.in.connection);if(!t||lm(t))return!0;this.#r.set(!0);let n=r.get(this.#t);return n?n.has(e):!1}#c(r){if(!r.get(this.in.enabled))return;let e=r.get(this.in.connection);if(!e)return;let t=r.get(this.in.name);if(!r.get(this.in.reload)){let i=e.consume(t);r.cleanup(()=>i.close()),r.set(this.#e.active,i,void 0);return}let n=e.announcedBroadcast(t);r.cleanup(()=>n.close()),r.run(i=>{i.set(this.#e.active,i.get(n.active),void 0)})}#d(r){if(!r.get(this.in.enabled))return;let e=r.get(this.in.catalogFormat),t=r.get(this.in.name),n=e??gf(t)??wf;if(n==="manual"){let c=r.get(this.in.catalog);this.#n.set(c,!0),r.cleanup(()=>this.#n.set(void 0,!0)),this.#e.status.set(c?"live":"loading");return}let i=r.get(this.out.active);if(!i)return;this.#e.status.set("loading");let s=n==="hang"?mf:n==="hangz"?_f:"catalog",a=i.track(s).subscribe({priority:po.catalog});r.cleanup(()=>a.close());let o;if(n==="hang"||n==="hangz"){let c=new Ro.Consumer(a,{schema:vf,compression:n==="hangz"});o=()=>c.next()}else o=async()=>{let c=await am(a);return c?hx(c):void 0};r.spawn(async()=>{try{for(;;){let c=await Promise.race([r.cancel,o()]);if(!c)break;console.debug("received catalog",n,this.in.name.peek(),c),this.#n.set(c,!0),this.#e.status.set("live")}}catch(c){console.warn("error fetching catalog",this.in.name.peek(),c)}finally{this.#n.set(void 0),this.#e.status.set("offline")}})}#l(r,e){if(!e)return{local:!0};let t=r.get(this.in.name),n=W.tryResolve(t,e);if(n!==void 0){if(n===t)return{local:!0};if(this.#a(r,n))return{local:!1,path:n}}}relativeBroadcast(r,e){let t=this.#l(r,e);if(!t)return;if(t.local)return r.get(this.out.active);if(!r.get(this.in.enabled))return;let n=r.get(this.in.connection);if(!n)return;let i=n.consume(t.path);return r.cleanup(()=>i.close()),i}close(){this.#i.close()}},xm=Symbol("supportCacheKey");function Sm(r){return{broadcast:r.broadcast,decoder:{codec:r.codec,container:r.container,description:r.description,displayAspectWidth:r.displayAspectWidth,displayAspectHeight:r.displayAspectHeight,optimizeForLatency:r.optimizeForLatency??!0}}}function _x(r){return JSON.stringify(Sm(r).decoder)}var wx=E.Milli(100);function hm(r){if(r.jitter!==void 0)return E.Milli(r.jitter);if(r.framerate)return E.Milli(Math.ceil(1e3/r.framerate))}function gx(r){return r.active===void 0||E.Milli.add(r.playhead,wx)>=r.active}function Em(r=0){let e=(r%360+360)%360;return Math.round(e/90)%4*90}function km(r,e=0){let t=Em(e);return t===90||t===270?{width:r.height,height:r.width}:{width:r.width,height:r.height}}function Un(r){return Object.is(r,-0)?0:r}function yx(r,e){let[t,n,i,s,a,o]=r;return[Un(-t),Un(n),Un(-i),Un(s),Un(e-a),Un(o)]}function bx(r,e){let t=Em(e?.rotation),n=km(r,t),i;switch(t){case 90:i=[0,1,-1,0,r.width,0];break;case 180:i=[-1,0,0,-1,r.width,r.height];break;case 270:i=[0,-1,1,0,0,r.height];break;default:i=[1,0,0,1,0,0]}return e?.flip&&(i=yx(i,r.width)),{matrix:i,source:n}}var vx=E.Milli(500),xu=class{in;source;sync;#e={frame:new A(void 0),timestamp:new A(void 0),display:new A(void 0),stalled:new A(!1),stats:new A(void 0),buffered:new A([])};out=this.#e;#t=new A(void 0);#r;#n=new j;#i(){this.#e.frame.update(r=>{r?.close()}),this.#e.timestamp.set(void 0)}constructor(r,e,t){this.in={enabled:N(t?.enabled??!1)},this.source=r,this.sync=e,this.#r=this.#n.computed(n=>{let i=n.get(this.source.out.config);return i?Sm(i):void 0}),this.#n.run(this.#s.bind(this)),this.#n.run(this.#o.bind(this)),this.#n.run(this.#a.bind(this)),this.#n.run(this.#c.bind(this))}#s(r){let e=r.getAll([this.in.enabled,this.source.in.broadcast,this.source.out.track,this.#r]);if(!e){this.#t.set(void 0);return}let[t,n,i,s]=e,a=n.relativeBroadcast(r,s.broadcast);if(!a){this.#t.set(void 0),this.#i(),this.#e.buffered.set([]);return}let o=new Ax({sync:this.sync,broadcast:a,track:i,config:s.decoder,stats:this.#e.stats});r.cleanup(()=>o?.close()),r.run(c=>{if(!o)return;let u=c.get(this.#t);if(u){let d=c.get(o.timestamp);if(d===void 0||!gx({playhead:d,active:c.get(u.timestamp)}))return}this.#t.set(o),o=void 0,c.close()})}#o(r){let e=r.get(this.#t);if(!e){this.#e.buffered.set([]);return}r.cleanup(()=>e.close()),r.run(t=>{let n=t.get(e.frame);this.#e.frame.update(i=>(i?.close(),n?.clone()))}),r.proxy(this.#e.timestamp,e.timestamp),r.proxy(this.#e.buffered,e.buffered)}#a(r){let e=r.get(this.source.out.catalog);if(!e)return;let t=e.display;if(t){r.set(this.#e.display,{width:t.width,height:t.height});return}let n=r.get(this.#e.frame);n&&r.set(this.#e.display,km({width:n.displayWidth,height:n.displayHeight},e.rotation))}#c(r){if(r.get(this.in.enabled)){if(!r.get(this.#e.frame)){this.#e.stalled.set(!0);return}this.#e.stalled.set(!1),r.timer(()=>{this.#e.stalled.set(!0)},vx)}}close(){this.#i(),this.#n.close()}static supported=Tm},Ax=class{sync;broadcast;track;config;stats;timestamp=new A(void 0);frame=new A(void 0);buffered=new A([]);#e=new A([]);#t=0;#r=new j;constructor(r){this.sync=r.sync,this.broadcast=r.broadcast,this.track=r.track,this.config=r.config,this.stats=r.stats,this.#r.run(this.#n.bind(this))}#n(r){let e=this.broadcast.track(this.track).subscribe({priority:po.video});r.cleanup(()=>e.close());let t=new VideoDecoder({output:async n=>{try{let i=this.#t,s=E.Milli.fromMicro(n.timestamp);if(s<(this.timestamp.peek()??0))return;this.frame.peek()===void 0&&this.frame.set(n.clone());let a=this.sync.wait(s).then(()=>!0);if(!await Promise.race([a,r.cancel])||i!==this.#t||s<(this.timestamp.peek()??0))return;this.timestamp.set(s),this.#c(s),this.frame.update(o=>(o?.close(),n.clone()))}finally{n.close()}},error:n=>{console.error(n),r.close()}});r.cleanup(()=>{t.state!=="closed"&&t.close()}),this.config.container.kind==="cmaf"?this.#s(r,e,t):this.#i(r,e,t)}#i(r,e,t){let n=this.config.container.kind==="loc"?new Mi.Format:new zi.Format,i=new Yt(e,{format:n,latency:this.sync.out.buffer});r.cleanup(()=>i.close()),r.run(a=>{let o=a.get(i.buffered),c=a.get(this.#e);this.buffered.update(()=>qi(o,c))}),t.configure({codec:this.config.codec,description:this.config.description?Ze.toBytes(this.config.description):void 0,displayAspectWidth:this.config.displayAspectWidth,displayAspectHeight:this.config.displayAspectHeight,optimizeForLatency:this.config.optimizeForLatency,flip:!1});let s;r.spawn(async()=>{for(;;){let a=await i.next();if(!a)break;this.#o(a.discontinuity)&&(s=void 0);let{frame:o}=a;if(!o)continue;let c=E.Milli.fromMicro(o.timestamp);this.sync.received(c,"video");let u=new EncodedVideoChunk({type:o.keyframe?"key":"delta",data:o.payload,timestamp:o.timestamp});this.stats.update(d=>({frameCount:(d?.frameCount??0)+1,bytesReceived:(d?.bytesReceived??0)+o.payload.byteLength})),s!==void 0&&a.continuous&&this.#a(E.Milli.fromMicro(s),E.Milli.fromMicro(o.timestamp)),s=o.timestamp,t.decode(u)}})}#s(r,e,t){let n=this.config.container;if(n.kind!=="cmaf")return;let i=rs(n.init),s=kt.decodeInitSegment(i),a=this.config.description?Ze.toBytes(this.config.description):s.description,o=new Yt(e,{format:new kt.Format(s),latency:this.sync.out.buffer});r.cleanup(()=>o.close()),r.run(u=>{let d=u.get(o.buffered),f=u.get(this.#e);this.buffered.update(()=>qi(d,f))}),t.configure({codec:this.config.codec,description:a,displayAspectWidth:this.config.displayAspectWidth,displayAspectHeight:this.config.displayAspectHeight,optimizeForLatency:this.config.optimizeForLatency,flip:!1});let c;r.spawn(async()=>{for(;;){let u=await o.next();if(!u)break;this.#o(u.discontinuity)&&(c=void 0);let{frame:d}=u;if(!d)continue;let f=E.Milli.fromMicro(d.timestamp);if(this.sync.received(f,"video"),this.stats.update(l=>({frameCount:(l?.frameCount??0)+1,bytesReceived:(l?.bytesReceived??0)+d.payload.byteLength})),c!==void 0&&u.continuous&&this.#a(E.Milli.fromMicro(c),E.Milli.fromMicro(d.timestamp)),c=d.timestamp,t.state==="closed")break;t.decode(new EncodedVideoChunk({type:d.keyframe?"key":"delta",data:d.payload,timestamp:d.timestamp}))}})}#o(r){return r!==this.#t&&(this.#t=r,this.timestamp.set(void 0),this.#e.set([]),this.sync.reset(),!0)}#a(r,e){r>e||this.#e.mutate(t=>{for(let n of t)if(n.start<=e&&n.end>=r){n.start=E.Milli.min(n.start,r),n.end=E.Milli.max(n.end,e);return}t.push({start:r,end:e}),t.sort((n,i)=>n.start-i.start)})}#c(r){this.#e.mutate(e=>{for(;e.length>0;){if(e[0].end>=r){e[0].start=E.Milli.max(e[0].start,r);break}e.shift()}})}close(){this.#r.close(),this.frame.update(r=>{r?.close()})}};async function Tm(r){if(!dc(r.container)){let n=r.container.kind==="unknown"?r.container.raw.kind:r.container.kind;return console.warn(`video: ignoring rendition with unknown container: ${n}`),!1}let e;if(r.description)e=Ze.toBytes(r.description);else if(r.container.kind==="cmaf")try{e=kt.decodeInitSegment(rs(r.container.init)).description}catch(n){return console.warn(`video: malformed CMAF init segment for codec ${r.codec}`,n),!1}let{supported:t}=await VideoDecoder.isConfigSupported({codec:r.codec,description:e,displayAspectWidth:r.displayAspectWidth,displayAspectHeight:r.displayAspectHeight,optimizeForLatency:r.optimizeForLatency??!0});if(t)return!0;if(r.codec.startsWith("avc3.")){let n=`avc1.${r.codec.slice(5)}`;if((await VideoDecoder.isConfigSupported({codec:n,description:e,displayAspectWidth:r.displayAspectWidth,displayAspectHeight:r.displayAspectHeight,optimizeForLatency:r.optimizeForLatency??!0})).supported)return r.codec=n,!0}return!1}Object.assign(Tm,{[xm]:_x});var pm=.01,Mm=class{decoder;in;#e={frame:new A(void 0),timestamp:new A(void 0),visible:new A(!1)};out=this.#e;#t=new A(void 0);#r=new j;constructor(r,e){this.decoder=r,this.in={canvas:N(e?.canvas),visible:N(e?.visible??"20%")},this.#r.run(t=>{let n=t.get(this.in.canvas);this.#t.set(n?.getContext("2d")??void 0)}),this.#r.run(this.#i.bind(this)),this.#r.run(this.#s.bind(this)),this.#r.run(this.#n.bind(this))}#n(r){let e=r.getAll([this.in.canvas,this.decoder.out.display]);if(!e)return;let[t,n]=e;(t.width!==n.width||t.height!==n.height)&&(t.width=n.width,t.height=n.height)}#i(r){let e=r.get(this.in.visible);if(e==="never"){this.#e.visible.set(!1);return}if(e==="always"){this.#e.visible.set(!0),r.cleanup(()=>this.#e.visible.set(!1));return}let t=r.get(this.in.canvas);if(!t){this.#e.visible.set(!1);return}let n=!1,i=()=>{this.#e.visible.set(n&&!document.hidden)},s=o=>{for(let c of o)n=c.isIntersecting,i()},a;try{a=new IntersectionObserver(s,{threshold:pm,rootMargin:e})}catch{console.warn(`moq-watch: invalid visible margin "${e}", using "0px"`),a=new IntersectionObserver(s,{threshold:pm})}i(),r.event(document,"visibilitychange",i),a.observe(t),r.cleanup(()=>a.disconnect()),r.cleanup(()=>this.#e.visible.set(!1))}#s(r){let e=r.get(this.#t);if(!e)return;let t=r.get(this.decoder.out.frame),n=r.get(this.decoder.source.out.catalog),i=requestAnimationFrame(()=>{this.#o(e,t,n),t?(this.#e.frame.update(s=>(s?.close(),t.clone())),this.#e.timestamp.set(E.Milli.fromMicro(t.timestamp))):(this.#e.frame.update(s=>{s?.close()}),this.#e.timestamp.set(void 0)),i=void 0});r.cleanup(()=>{i&&cancelAnimationFrame(i)})}#o(r,e,t){if(!e){r.fillStyle="#000",r.fillRect(0,0,r.canvas.width,r.canvas.height);return}if(r.save(),r.fillStyle="#000",r.fillRect(0,0,r.canvas.width,r.canvas.height),!t?.rotation)t?.flip&&(r.scale(-1,1),r.translate(-r.canvas.width,0)),r.drawImage(e,0,0,r.canvas.width,r.canvas.height);else{let n=bx(r.canvas,t);r.setTransform(...n.matrix),r.drawImage(e,0,0,n.source.width,n.source.height)}r.restore()}close(){this.#e.frame.update(r=>{r?.close()}),this.#e.timestamp.set(void 0),this.#r.close()}};function xx(r){return e=>{let t=[],n=[];for(let[i,s]of e)if(s.codedWidth&&s.codedHeight){let a=s.codedWidth*s.codedHeight;a<=r?t.push({name:i,size:a}):n.push({name:i,size:a})}return t.sort((i,s)=>s.size-i.size),t.length>0?t.map(i=>i.name):n.length>0?(n.sort((i,s)=>i.size-s.size),[n[0].name]):e.map(([i])=>i)}}function Im(r,e){return t=>{let n=[],i=[];for(let[s,a]of t){if(!a.codedWidth||!a.codedHeight)continue;let o=a.codedWidth*a.codedHeight,c=r==null||a.codedWidth<=r,u=e==null||a.codedHeight<=e;c&&u?n.push({name:s,size:o}):i.push({name:s,size:o})}return n.sort((s,a)=>a.size-s.size),n.length>0?n.map(s=>s.name):i.length>0?(i.sort((s,a)=>s.size-a.size),[i[0].name]):t.map(([s])=>s)}}function Pm(r){return e=>{let t=[],n=[];for(let[i,s]of e)s.bitrate!=null&&s.bitrate<=r?t.push({name:i,bitrate:s.bitrate}):s.bitrate!=null&&n.push({name:i,bitrate:s.bitrate});return t.sort((i,s)=>s.bitrate-i.bitrate),t.length>0?t.map(i=>i.name):n.length>0?(n.sort((i,s)=>i.bitrate-s.bitrate),[n[0].name]):e.map(([i])=>i)}}function Sx(r){let e=r[0];for(let t of r){let[,n]=t,[,i]=e,s=(n.codedWidth??0)*(n.codedHeight??0),a=(i.codedWidth??0)*(i.codedHeight??0);if(s!==a){s>a&&(e=t);continue}(n.bitrate??0)>(i.bitrate??0)&&(e=t)}return e[0]}function Ex(r){let e=Object.entries(r).filter(([,s])=>!s.stalled);if(e.length>0)return Object.fromEntries(e);let t=Object.entries(r);if(t.length===0)return{};let n=Pm(0)(t),i=n.length===1?n[0]:Im(0,0)(t)[0];return{[i]:r[i]}}var zm=class{in;#e={catalog:new A(void 0),available:new A({}),error:new A(void 0),track:new A(void 0),config:new A(void 0),jitter:new A(void 0)};out=this.#e;#t=new j;#r=new WeakMap;constructor(r){this.in={broadcast:N(r?.broadcast),target:N(r?.target),supported:N(r?.supported)},this.#t.run(this.#n.bind(this)),this.#t.run(this.#i.bind(this)),this.#t.run(this.#s.bind(this))}#n(r){let e=r.get(this.in.broadcast);if(!e)return;let t=r.get(e.out.catalog)?.video;t&&r.set(this.#e.catalog,t)}#i(r){let e=r.get(this.in.supported);if(!e){this.#e.error.set(void 0);return}let t=r.get(this.#e.catalog)?.renditions??{};this.#e.error.set(void 0);let n=this.#r.get(e);n||(n=new Map,this.#r.set(e,n));let i=new Set(Object.keys(t));for(let s of n.keys())i.has(s)||n.delete(s);r.spawn(async()=>{let s={},a=r.cancel.then(()=>{});for(let[c,u]of Object.entries(t)){let d=e[xm],f=d?d(u):JSON.stringify(u),l=n.get(c),h=!1;if(l?.key===f)h=l.supported;else{let p=!1;try{h=await Promise.race([e(u),a])}catch(_){p=!0,console.warn(`[Source] video rendition ${c} (${u.codec}) support probe failed; treating as unsupported`,_)}!p&&h!==void 0&&n.set(c,{key:d?d(u):JSON.stringify(u),supported:h})}if(r.abort.aborted)return;h&&(s[c]=u)}let o=Object.keys(s).length===0&&Object.keys(t).length>0?"unsupported":void 0;o==="unsupported"&&console.warn("[Source] No supported video renditions found:",t),this.#e.error.set(o),this.#e.available.set(s)})}#s(r){let e=Ex(r.get(this.#e.available));if(Object.keys(e).length===0)return;let t=r.get(this.in.target);if(t?.name&&t.name in e){let a=e[t.name];r.set(this.#e.track,t.name),r.set(this.#e.config,a),r.set(this.#e.jitter,hm(a));return}let n=t;if(!t?.bitrate){let a=r.get(this.in.broadcast),o=a?r.get(a.in.connection):void 0,c=o&&r.get(o.probe).estimatedRecvRate;if(c!=null){let u=Math.round(c*.8);n={...t,bitrate:u}}}let i=this.#o(e,n);if(!i)return;let s=e[i];r.set(this.#e.track,i),r.set(this.#e.config,s),r.set(this.#e.jitter,hm(s))}#o(r,e){let t=Object.entries(r);if(t.length===0)return;if(t.length===1)return t[0][0];let n=[];if(e?.pixels!=null&&n.push(xx(e.pixels)),(e?.width!=null||e?.height!=null)&&n.push(Im(e.width,e.height)),e?.bitrate!=null&&n.push(Pm(e.bitrate)),n.length===0)return Sx(t);let i=n.map(a=>a(t)),s=i.map(a=>new Set(a));for(let a of i[0])if(s.every(o=>o.has(a)))return a;console.warn("conflicting rendition filters, no rendition satisfies all criteria")}close(){this.#t.close()}};var kx=["url","name","paused","volume","muted","visible","reload","latency","latency-min","latency-max","jitter","catalog-format"];function Tx(r){let e=r?.trim();return e?e==="never"||e==="always"||/^-?\d+(\.\d+)?(px|%)$/.test(e)?e:/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:(console.warn(`moq-watch: invalid visible="${r}", expected "never", "always", or a CSS length like "200px"`),"20%"):"20%"}function Su(r,e){if(r===null)return e;let t=r.trim().toLowerCase();return t!=="false"&&t!=="0"}var Mx=new FinalizationRegistry(r=>r.close()),Ix=class extends HTMLElement{static observedAttributes=kx;connection;broadcast;video;audio;renderer;emitter;sync;controls={paused:new A(!1),volume:new A(.5),muted:new A(!1),visible:new A("20%"),latency:new A("real-time"),target:new A(void 0)};#e=new A(W.empty());#t=new A(!0);#r=new A(void 0);#n=new A(void 0);#i=new A(void 0);#s=new A(!1);#o=new A(!1);#a=new A(!1);#c=.5;signals=new j;constructor(){super(),Mx.register(this,this.signals),this.connection=new ao.Reload({enabled:this.#a}),this.signals.cleanup(()=>this.connection.close()),this.broadcast=new Am({connection:this.connection.established,enabled:this.#a,name:this.#e,reload:this.#t,catalogFormat:this.#r,catalog:this.#n}),this.signals.cleanup(()=>this.broadcast.close());let r=new zm({broadcast:this.broadcast,target:this.controls.target,supported:xu.supported}),e=new ym({broadcast:this.broadcast,supported:Au.supported});this.signals.cleanup(()=>{r.close(),e.close()}),this.sync=new lf({latency:this.controls.latency,connection:this.connection.established,video:r.out.jitter,audio:e.out.jitter}),this.signals.cleanup(()=>this.sync.close()),this.video=new xu(r,this.sync,{enabled:this.#s}),this.audio=new Au(e,this.sync,{enabled:this.#o}),this.signals.cleanup(()=>{this.video.close(),this.audio.close()}),this.emitter=new gm(this.audio,{volume:this.controls.volume,muted:this.controls.muted,paused:this.controls.paused}),this.renderer=new Mm(this.video,{canvas:this.#i,visible:this.controls.visible}),this.signals.cleanup(()=>{this.emitter.close(),this.renderer.close()}),this.signals.proxy(this.#o,this.emitter.out.enabled),this.signals.run(o=>{let c=o.get(this.renderer.out.visible);if(!o.get(this.controls.paused)){this.#s.set(c);return}let u=o.get(this.renderer.out.frame);this.#s.set(c&&!u)}),this.signals.run(o=>{o.get(this.controls.muted)?(this.#c=this.controls.volume.peek()||.5,this.controls.volume.set(0)):this.controls.volume.set(this.#c)}),this.signals.run(o=>{let c=o.get(this.controls.volume);this.controls.muted.set(c===0)});let t=()=>{let o=this.querySelector("canvas")??void 0;!o&&this.querySelector("video")&&console.warn("moq-watch: rendering requires a <canvas> child; a <video> child does nothing."),this.#i.set(o)},n=new MutationObserver(t);n.observe(this,{childList:!0,subtree:!0}),this.signals.cleanup(()=>n.disconnect()),t(),this.signals.run(o=>{let c=o.get(this.connection.url);c?this.setAttribute("url",c.toString()):this.removeAttribute("url")}),this.signals.run(o=>{let c=o.get(this.#e);this.setAttribute("name",c.toString())}),this.signals.run(o=>{o.get(this.controls.muted)?this.setAttribute("muted",""):this.removeAttribute("muted")}),this.signals.run(o=>{o.get(this.controls.paused)?this.setAttribute("paused",""):this.removeAttribute("paused")}),this.signals.run(o=>{let c=o.get(this.controls.volume);this.setAttribute("volume",c.toString())}),this.signals.run(o=>{let c=o.get(this.controls.visible);this.setAttribute("visible",c)}),this.signals.run(o=>{let{min:c,max:u}=Ke(o.get(this.controls.latency));if(c===u)if(c==="real-time")this.setAttribute("latency","real-time");else{let d=Math.floor(o.get(this.sync.out.jitter));this.setAttribute("latency",d.toString())}});let i=(o,c)=>{if(o<=0||c<=0)return;let u=window.devicePixelRatio||1;this.controls.target.update(d=>({...d,width:Math.round(o*u),height:Math.round(c*u)}))},s=new ResizeObserver(o=>{let c=o[0];c&&i(c.contentRect.width,c.contentRect.height)});s.observe(this),this.signals.cleanup(()=>s.disconnect());let a=this.getBoundingClientRect();i(a.width,a.height)}connectedCallback(){this.#a.set(!0),this.style.display="block",this.style.position="relative"}disconnectedCallback(){this.#a.set(!1)}#d(r){if(!r||r==="real-time")return"real-time";let e=Number.parseFloat(r);return E.Milli(Number.isFinite(e)?e:100)}attributeChangedCallback(r,e,t){if(e!==t)if(r==="url")this.connection.url.set(t?new URL(t):void 0);else if(r==="name")this.#e.set(W.from(t??""));else if(r==="paused")this.controls.paused.set(Su(t,!1));else if(r==="volume"){let n=t?Number.parseFloat(t):.5;this.controls.volume.set(n)}else if(r==="muted")this.controls.muted.set(Su(t,!1));else if(r==="visible")this.controls.visible.set(Tx(t));else if(r==="reload")this.#t.set(Su(t,!0));else if(r==="latency")this.latency=this.#d(t);else if(r==="latency-min")this.latencyMin=this.#d(t);else if(r==="latency-max")this.latencyMax=this.#d(t);else if(r==="jitter")this.latency=this.#d(t);else if(r==="catalog-format")this.#r.set(vm(t));else throw Error(`Invalid attribute: ${r}`)}get url(){return this.connection.url.peek()}set url(r){this.connection.url.set(r?new URL(r):void 0)}get name(){return this.#e.peek()}set name(r){this.#e.set(W.from(r))}get paused(){return this.controls.paused.peek()}set paused(r){this.controls.paused.set(r)}get volume(){return this.controls.volume.peek()}set volume(r){this.controls.volume.set(r)}get muted(){return this.controls.muted.peek()}set muted(r){this.controls.muted.set(r)}get visible(){return this.controls.visible.peek()}set visible(r){this.controls.visible.set(r)}get reload(){return this.#t.peek()}set reload(r){this.#t.set(r)}get latency(){return this.controls.latency.peek()}set latency(r){this.controls.latency.set(r)}get latencyMin(){return Ke(this.controls.latency.peek()).min}set latencyMin(r){let{max:e}=Ke(this.controls.latency.peek());this.controls.latency.set(uc(r,e))}get latencyMax(){return Ke(this.controls.latency.peek()).max}set latencyMax(r){let{min:e}=Ke(this.controls.latency.peek());this.controls.latency.set(uc(e,r))}get jitter(){return this.sync.out.jitter.peek()}reset(){this.sync.reset(),this.audio.reset()}get catalogFormat(){return this.#r.peek()}set catalogFormat(r){this.#r.set(r)}get catalog(){return this.broadcast.out.catalog.peek()}set catalog(r){this.#n.set(r)}};customElements.define("moq-watch",Ix);
|