@amityco/ts-sdk 7.27.0 → 7.27.1-331f416.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -10,4 +10,4 @@ var Amity=function(e){"use strict";var t,n,r,s,i;e.MembershipAcceptanceTypeEnum=
|
|
|
10
10
|
@babel/runtime/helpers/regenerator.js:
|
|
11
11
|
(*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *)
|
|
12
12
|
*/
|
|
13
|
-
class Sh{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let Eh;var Ih=()=>(Eh||(Eh=new Sh),Eh);const Th=e=>Ih().onSessionStateChange(e),Ah={[e.AmityAutoSubscription.NETWORK]:[Yt],[e.AmityAutoSubscription.CHAT]:[Qt,zt,Jt],[e.AmityAutoSubscription.LIVESTREAM]:[Xt],[e.AmityAutoSubscription.BLOCK]:[Wt,Ht]},Ch=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],_h=Object.values(e.AmityAutoSubscription);class Rh{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Ch.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Ah[e].map((e=>Zt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){_h.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return _h.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Ah[e].length})))}reset(){_h.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let Oh=null;const kh=()=>(Oh||(Oh=new Rh),Oh);class Ph{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Dh=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ph},Lh=async(e,t)=>new Promise((n=>{Dh().localStorage.setItem(e,t),n(!0)})),xh=async e=>new Promise((t=>{t(Dh().localStorage.getItem(e))}));var Mh={},Uh={},Fh={};Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.bytesToString=Fh.stringToBytes=Fh.NIL=Fh.X500=Fh.OID=Fh.URL=Fh.DNS=Fh.hexToByte=Fh.byteToHex=void 0;let Nh=[],Bh={};for(var jh=0;jh<256;jh++)Nh[jh]=(jh+256).toString(16).substr(1),Bh[Nh[jh]]=jh;Fh.byteToHex=Nh,Fh.hexToByte=Bh,Fh.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Fh.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Fh.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",Fh.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",Fh.NIL="00000000-0000-0000-0000-000000000000";Fh.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t};Fh.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Uh,"__esModule",{value:!0}),Uh.parse=void 0;const $h=Fh;Uh.parse=(e,t,n)=>{let r=t&&n||0,s=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(s<16&&t&&(t[r+s++]=$h.hexToByte[e]),"")));s<16;)t[r+s++]=0;return t};var qh={};Object.defineProperty(qh,"__esModule",{value:!0}),qh.unparse=void 0;const Kh=Fh;qh.unparse=(e,t)=>{let n=t||0,r=Kh.byteToHex;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]};var Gh={},Wh={};Object.defineProperty(Wh,"__esModule",{value:!0});Wh.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var Hh=nn&&nn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gh,"__esModule",{value:!0}),Gh.validate=void 0;const Vh=Hh(Wh);Gh.validate=e=>"string"==typeof e&&Vh.default.test(e);var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0}),Yh.version=void 0;const Qh=Gh;Yh.version=e=>{if(!Qh.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var zh={},Jh={};Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.stringify=void 0;const Xh=Gh,Zh=[];for(let e=0;e<256;++e)Zh.push((e+256).toString(16).substr(1));Jh.stringify=(e,t=0)=>{const n=(Zh[e[t+0]]+Zh[e[t+1]]+Zh[e[t+2]]+Zh[e[t+3]]+"-"+Zh[e[t+4]]+Zh[e[t+5]]+"-"+Zh[e[t+6]]+Zh[e[t+7]]+"-"+Zh[e[t+8]]+Zh[e[t+9]]+"-"+Zh[e[t+10]]+Zh[e[t+11]]+Zh[e[t+12]]+Zh[e[t+13]]+Zh[e[t+14]]+Zh[e[t+15]]).toLowerCase();if(!Xh.validate(n))throw TypeError("Stringified UUID is invalid");return n};var ef={};Object.defineProperty(ef,"__esModule",{value:!0}),ef.rng=void 0;ef.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(zh,"__esModule",{value:!0}),zh.v1=void 0;const tf=Jh,nf=ef;let rf,sf,af=0,of=0;zh.v1=(e,t,n=0)=>{let r=t&&n||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:rf,a=e&&e.clockseq?e.clockseq:sf;if(null==i||null==a){const t=e&&e.random?e.random:e&&e.rng?e.rng():nf.rng();null==i&&(i=rf=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==a&&(a=sf=16383&(t[6]<<8|t[7]))}let o=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:of+1;const c=o-af+(l-of)/1e4;if(c<0&&e&&!e.clockseq&&(a=a+1&16383),(c<0||o>af)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");af=o,of=l,sf=a,o+=122192928e5;const d=(1e4*(268435455&o)+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=255&d;const u=o/4294967296*1e4&268435455;s[r++]=u>>>8&255,s[r++]=255&u,s[r++]=u>>>24&15|16,s[r++]=u>>>16&255,s[r++]=a>>>8|128,s[r++]=255&a;for(let e=0;e<6;++e)s[r+e]=i[e];return t||tf.stringify(s)};var lf={};Object.defineProperty(lf,"__esModule",{value:!0}),lf.v4=void 0;const cf=qh,df=ef;lf.v4=(e,t,n)=>{let r=t&&n||0,s=df.rng();if(!e||e instanceof String||(e.random&&(s=e.random),e.rng&&(s=e.rng())),s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var i=0;i<16;i++)t[r+i]=s[i];return t||cf.unparse(s)};var uf={},hf={};Object.defineProperty(hf,"__esModule",{value:!0}),hf.v35=void 0;const ff=Jh,pf=Uh,gf=Fh;hf.v35=(e,t,n)=>(e,r,s,i=0)=>{if("string"==typeof e&&(e=gf.stringToBytes(e)),"string"==typeof r&&(r=pf.parse(r)),r&&16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+e.length);if(a.set(r),a.set(e,r.length),a=gf.stringToBytes(n(gf.bytesToString(a))),a[6]=15&a[6]|t,a[8]=63&a[8]|128,s)for(let e=0;e<16;++e)s[i+e]=a[e];return s||ff.stringify(a)};var mf={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,n="";e.hex_sha1=e=>i(r(l(e))),e.default=e.hex_sha1;e.b64_sha1=e=>a(r(l(e)));e.any_sha1=(e,t)=>o(r(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>a(s(l(e),l(t)));e.any_hmac_sha1=(e,t,n)=>o(s(l(e),l(t)),n);const r=e=>d(u(c(e),8*e.length)),s=(e,t)=>{let n=c(e);n.length>16&&(n=u(n,8*e.length));let r=Array(16),s=Array(16);for(var i=0;i<16;i++)r[i]=909522486^n[i],s[i]=1549556828^n[i];var a=u(r.concat(c(t)),512+8*t.length);return d(u(s.concat(a),672))},i=e=>{for(var n,r=t?"0123456789ABCDEF":"0123456789abcdef",s="",i=0;i<e.length;i++)n=e.charCodeAt(i),s+=r.charAt(n>>>4&15)+r.charAt(15&n);return s},a=e=>{for(var t="",r=e.length,s=0;s<r;s+=3)for(var i=e.charCodeAt(s)<<16|(s+1<r?e.charCodeAt(s+1)<<8:0)|(s+2<r?e.charCodeAt(s+2):0),a=0;a<4;a++)8*s+6*a>8*e.length?t+=n:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-a)&63);return t},o=(e,t)=>{var n,r,s,i,a=t.length,o=[],l=Array(Math.ceil(e.length/2));for(n=0;n<l.length;n++)l[n]=e.charCodeAt(2*n)<<8|e.charCodeAt(2*n+1);for(;l.length>0;){for(i=[],s=0,n=0;n<l.length;n++)s=(s<<16)+l[n],s-=(r=Math.floor(s/a))*a,(i.length>0||r>0)&&(i[i.length]=r);o[o.length]=s,l=i}var c="";for(n=o.length-1;n>=0;n--)c+=t.charAt(o[n]);var d=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(n=c.length;n<d;n++)c=t[0]+c;return c},l=e=>{for(var t,n,r="",s=-1;++s<e.length;)t=e.charCodeAt(s),n=s+1<e.length?e.charCodeAt(s+1):0,t>=55296&&t<=56319&&n>=56320&&n<=57343&&(t=65536+((1023&t)<<10)+(1023&n),s++),t<=127?r+=String.fromCharCode(t):t<=2047?r+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?r+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(r+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return r},c=e=>{for(var t=Array(e.length>>2),n=0;n<t.length;n++)t[n]=0;for(n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<24-n%32;return t},d=e=>{for(var t="",n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>24-n%32&255);return t},u=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n=Array(80),r=1732584193,s=-271733879,i=-1732584194,a=271733878,o=-1009589776,l=0;l<e.length;l+=16){for(var c=r,d=s,u=i,m=a,y=o,v=0;v<80;v++){n[v]=v<16?e[l+v]:g(n[v-3]^n[v-8]^n[v-14]^n[v-16],1);let t=p(p(g(r,5),h(v,s,i,a)),p(p(o,n[v]),f(v)));o=a,a=i,i=g(s,30),s=r,r=t}r=p(r,c),s=p(s,d),i=p(i,u),a=p(a,m),o=p(o,y)}return[r,s,i,a,o]},h=(e,t,n,r)=>e<20?t&n|~t&r:e<40?t^n^r:e<60?t&n|t&r|n&r:t^n^r,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n},g=(e,t)=>e<<t|e>>>32-t}(mf);var yf=nn&&nn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(uf,"__esModule",{value:!0}),uf.v5=void 0;const vf=hf,bf=yf(mf);uf.v5=vf.v35("v5",80,bf.default),Object.defineProperty(Mh,"__esModule",{value:!0});const wf=Uh,Sf=qh,Ef=Gh,If=Yh,Tf=zh,Af=lf,Cf=uf,_f=Fh;var Rf=Mh.default={parse:wf.parse,unparse:Sf.unparse,validate:Ef.validate,version:If.version,v1:Tf.v1,v4:Af.v4,v5:Cf.v5,NIL:_f.NIL,DNS:_f.DNS,URL:_f.URL,OID:_f.OID,X500:_f.X500};const Of=()=>Rf.v4().toString();let kf=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Of(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:kf}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(kf=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Pf=async()=>{var e;const t=`${null!==(e=Ye().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await xh(t);if(n)return n;const r=`ascWebSdk#${Of()}`;return await Lh(t,r),r},Df=()=>{const e=(()=>{var e,t;return(null===(e=dn.versions)||void 0===e?void 0:e.node)?dn.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:G}},Lf=1e3;var xf;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(xf||(xf={}));const Mf=e=>{let t;const n=new Map;function r(e,s,i){const a=(t,a)=>{var o;if(t||128===(null===(o=null==a?void 0:a[0])||void 0===o?void 0:o.qos))if(s<2){const t=Math.min(2**s*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${s+1}/3). Retrying in ${t}ms.`);const a=setTimeout((()=>{r(e,s+1,i)}),t);n.set(e,{timer:a,callback:i})}else{n.delete(e);const r=t?new Ke(t.message,8e5,"error"):new We(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,r),null==i||i(r)}else n.delete(e),console.log(`Subscribed to topic ${e}`),null==i||i()};t?t.subscribe(e,{qos:0},a):a(new Error("No connection to broker"),[])}return{connect:async function(r){const s=await(async e=>`mqttjs_${await Pf()}_${e}_${kf}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=wh.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:Lf,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:r.userId,password:r.accessToken,clientId:s})),t.on("connect",(()=>{t.options.reconnectPeriod=Lf,kh().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Lf),8e3)})),t.on("close",(()=>{n.forEach((({timer:e})=>clearTimeout(e))),n.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,t){return r(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var r;const s=n.get(e);if(void 0!==s){clearTimeout(s.timer),n.delete(e);const t=new Ke("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(r=s.callback)||void 0===r||r.call(s,t)}null==t||t.unsubscribe(e)}}},Uf=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Ff=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const s=Xe[e];if(!s)return;const i=Je(s);i&&r&&r.forEach((e=>{(n?nt:st)([s,"get",i(e)],e,t)}))}))},Nf=(e,t)=>{const{log:n,cache:r}=Ye(),s=[e,ee,t],i={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:s,data:i}),it([e,"get",t],!0),nt(s,i))};function Bf(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}const jf=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ye().cache)return;return(null===(n=tt(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},$f=(e,t,n="userId",r="user")=>{const s=e,i=t,a=s[i],o=Bf(s,["symbol"==typeof i?i:i+""]),l=jf(a,n,r);return Object.assign(Object.assign({},o),{[t]:l})};function qf(e){return e.map((e=>{var{isMentioned:t}=e,n=Bf(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Kf(e){return qf(e)}function Gf(e){return qf(e)}const Wf=e=>{var t,n;return null!==(n=null===(t=tt(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Hf=e=>new Date(e).getTime(),Vf=e=>{var t,n;return null!==(n=null===(t=tt(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yf=e=>{var t;const n=e.messagePreviewId?Vf(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=tt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},Qf=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,messageId:a,creatorPublicId:o,data:l,dataType:c,isDeleted:d,segment:u,createdAt:h,updatedAt:f}=t;return{messagePreviewId:a,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:d,segment:u,creatorId:o,createdAt:h,updatedAt:f,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Ff(r)};function zf(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Jf(e,t,n){nt(["subChannel","get",e],zf(t,n))}const Xf=(e,t)=>{const{log:n,cache:r}=Ye(),s=[e,ee,t];if(!r)return;n("cache/api/isInTombstone",s);const i=tt(s),{lifeSpan:a}=je("cache_then_server",18e4);if(i&&Ne(i.data,a))throw new Ge("Item not found!",400400,"error")},Zf=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=tt(n))||void 0===t?void 0:t.data,s=et(["subChannelUnreadInfo","get"]);let i=0,a=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));i=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}const o=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:i,isMentioned:a});return nt(n,o),o},ep=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Ff({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{Zf(e)}))}},tp=async()=>{const e=Ye();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Ff({userMarkers:n},{cachedAt:r}),Ut("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},np=e=>{var t,n;const r=null===(t=tt(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const s=et(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},rp=e=>!0===e&&void 0;function sp(e,t,n){var r,s;if(n)return n.hasMentioned;const i=Ye();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=tt(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Rt()._id},o=null===(s=tt(["subChannelMarker","get",Je("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return!!o&&o.hasMentioned}const ip=["broadcast","conversation","community"],ap=({channelType:e})=>ip.includes(e);function op(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:o,lastMessageTimestamp:l,messageFeedId:c,name:d}=e,u=Bf(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,s;if(n)return n.unreadCount;const i=Ye();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=tt(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Rt()._id},o=null===(s=tt(["subChannelMarker","get",Je("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return o?o.unreadCount:0}(t,c)},get hasMentioned(){return sp(t,c)},get isMentioned(){return sp(t,c)}},u),{channelId:n,creatorId:a,displayName:d,lastActivity:l,latestMessageId:o,messageCount:s,subChannelId:c,isUnreadCountSupport:ap({channelType:r})})}function lp(e,t,n){var r;const s=(e=>{var t,n,r;const s=null===(n=null===(t=et(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(r=s.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:i,childCount:a,creatorPublicId:o,mentionedUsers:l,messageFeedId:c,myReactions:d,reactionCount:u,reactions:h,referenceId:f,segment:p,messageId:g,creatorId:m}=s,y=Bf(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;f&&(v=tt(["message","get",f])),v||(v=tt(["message","get",g]));const b=Object.assign(Object.assign({},y),{messageId:g,channelId:i,channelSegment:p,childrenNumber:a,creatorId:o,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:c,uniqueId:v?v.data.uniqueId:g,referenceId:f,syncState:"synced"});return l&&(b.mentionees=l.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=Ye(),s=np(e.messageId),i=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:i});const a=t[0];a&&a.userId===r.userId&&("message.reactionAdded"!==n||i.includes(a.reactionName)||Object.assign(e,{myReactions:[...i,a.reactionName]}),"message.reactionRemoved"===n&&i.includes(a.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==a.reactionName))}))})(b,t,n),b}const cp={},dp=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Ff({messages:(r=e).messages.map((e=>lp(e,r.reactions)))});const t=n.join("");cp[t]&&clearTimeout(cp[t]),cp[t]=setTimeout((()=>{try{(async e=>{const t=Ye();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();t.cache&&Ff({contentMarkers:r,feedMarkers:s,userMarkers:i},{cachedAt:a}),Ut("local.feedMarker.fetched",{feedMarkers:s}),Ut("local.messageMarker.fetched",{contentMarkers:r}),Ut("local.userMarker.fetched",{userMarkers:i})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:s}=e,i=Bf(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const r=null!==(n=null===(t=tt(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Bf(op(e),["unreadCount","isMentioned"]);Jf(e.messageFeedId,r,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((n=>lp(n,e.reactions,t)))})};function up(e){var{subChannelId:t,mentionees:n,dataType:r,data:s}=e,i=Bf(e,["subChannelId","mentionees","dataType","data"]);return r===v.IMAGE||r===v.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},s)},i):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:s},i)}function hp(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:s,includeDeleted:i,aroundMessageId:a,limit:o,type:l}=e,c=Bf(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},c),{messageFeedId:n,isDeleted:rp(i),options:{sortBy:t,limit:o||W,around:a}});return r&&(d.includeTags=r),l&&(d.dataType=l),s&&(d.excludeTags=s),d}function fp(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const pp=["broadcast","conversation","community"],gp=({channelType:e})=>pp.includes(e),mp=async e=>{const t=e.messageFeeds.filter(gp).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Ff({messageFeeds:e.messageFeeds.map((e=>op(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ye();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:De(t,"skiplimit")}}}),{paging:s}=r,i=Bf(r,["paging"]),{userEntityMarkers:a,userFeedMarkers:o,userMarkers:l,feedMarkers:c}=i;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&ep({feedMarkers:c,userFeedMarkers:o});const d=Kf(a),u=Gf(o),h=n.cache&&Date.now();n.cache&&Ff({userEntityMarkers:d,userFeedMarkers:u,userMarkers:l},{cachedAt:h}),Ut("local.channelMarker.fetched",{userEntityMarkers:d}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:u}),Ut("local.userMarker.fetched",{userMarkers:l});const f=Le(s.next);return{data:u,cachedAt:h,prevPage:Le(s.previous),nextPage:f}})(t)}catch(e){}}Qf(e);const n=e.messageFeeds.map(op),r=e.messages.map((e=>lp(e))),s=e.users.map(fp);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:s})};const yp=async e=>{const t=Ye();t.log("channel/getSubChannel",e),Xf("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:s}}catch(t){throw ie(null==t?void 0:t.code)&&Nf("subChannel",e),t}};yp.locally=e=>{const t=Ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=tt(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const vp=async e=>{var t;let n=null===(t=tt(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await yp(e)).data),n},bp=async e=>{const t=await(async()=>Ye().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=await vp(c);"no-message-preview"!==t?(e=>{var t;const n=null===(t=tt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Hf(n.createdAt)<=Hf(e.createdAt)})(e)&&(nt(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),Jf(e.subChannelId,h,{lastActivity:i,messagePreviewId:r})):Hf(h.lastActivity)<Hf(i)&&Jf(e.subChannelId,h,{lastActivity:i})},wp=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=null===(t=tt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await vp(c);nt(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Sp=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:s,updatedAt:i,data:a,dataType:o,subChannelId:l,channelSegment:c,isDeleted:d}=e;if((e=>{var t;const n=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hf(n.createdAt)<=Hf(e.createdAt)})(e)){const u=await vp(l);nt(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:s,updatedAt:i,subChannelId:l,data:a,dataType:o,segment:c,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Ep=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await vp(c);nt(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ip=async e=>{var t,n,r,s;const{channelId:i,subChannelId:a}=e,o=null===(t=tt(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==o?void 0:o.subChannelId)===a){const e=null===(n=tt(["subChannel","get",a]))||void 0===n?void 0:n.data;nt(["messagePreviewChannel","get",i],Object.assign(Object.assign({},o),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(r=tt(["messagePreviewSubChannel","get",a]))||void 0===r?void 0:r.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=tt(["subChannel","get",a]))||void 0===s?void 0:s.data;nt(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Tp=["broadcast","conversation","community"],Ap=({type:e})=>Tp.includes(e);function Cp(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const s=null===(n=tt(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ap(e),messagePreviewId:r})}const _p=(e,t={isMessagePreviewUpdated:!0})=>{Ff({channels:e.channels.map((e=>Cp(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Rp=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ye(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})).filter((e=>{var t;const n=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hf(n.createdAt)<=Hf(e.createdAt)}));0!==n.length&&Ff({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var r,s;const i=[];for(let a=0;a<t.length;a+=1)if(Ap(t[a])){const o=["channelUnread","get",t[a].channelId],l=n.find((n=>n.channelId===t[a].channelId&&n.userId===e)),c=null===(r=tt(o))||void 0===r?void 0:r.data,d=Math.max(null!==(s=null==c?void 0:c.lastSegment)&&void 0!==s?s:0,t[a].messageCount);let u=null,h=null,f=0,p=!1;if(l){const e=l.readToSegment,t=l.lastMentionedSegment;u="number"==typeof(null==c?void 0:c.readToSegment)&&("number"!=typeof e||c.readToSegment>e)?c.readToSegment:null!=e?e:null,h="number"==typeof(null==c?void 0:c.lastMentionedSegment)&&("number"!=typeof t||c.lastMentionedSegment>t)?c.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;f=Math.max(d-n,0),p="number"==typeof h&&n<h}const g={channelId:t[a].channelId,lastSegment:d,readToSegment:u,lastMentionedSegment:h,unreadCount:f,isMentioned:p,isDeleted:t[a].isDeleted||!1};nt(o,g),i.push(g)}i.length>0&&Ut("local.channelUnread.updated",i)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ap).map((({channelInternalId:e})=>e));if(n.length>0){_p(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ye();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:s}=n,i=Kf(r),a=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:i,userMarkers:s},{cachedAt:a}),Ut("local.channelMarker.fetched",{userEntityMarkers:i}),Ut("local.userMarker.fetched",{userMarkers:s}),{data:i,cachedAt:a}})(n)}catch(e){}}}const s=e.channels.map((e=>Cp(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),i=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ye().cache)return(null===(e=tt(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),a=e.users.map(fp),o=Bf(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},o),{users:a,channels:s,channelUsers:i})},Op=async e=>{const t=Ye();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Ut("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},kp=async e=>{const t=Ye(),n=await Op(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:s}=n;ep({feedMarkers:r,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Pp=(e,t)=>{var n,r,s,i;const a=Ye();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=tt(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(i=null===(s=(e=>{var t;const n={entityId:e,userId:Rt()._id};return null===(t=tt(["channelMarker","get",Je("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==i&&i},Dp=(e,t)=>{var n,r,s,i,a;const o=Ye();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=tt(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(i=(e=>{var t;const n={entityId:e,userId:Rt()._id};return null===(t=tt(["channelMarker","get",Je("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===i?void 0:i.unreadCount)&&void 0!==a?a:0},Lp=e=>{var t;return null===(t=tt(["channelUnread","get",e]))||void 0===t?void 0:t.data},xp=e=>{const t=Ye(),n=Bf(e,["messageCount"]);return zf(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Lp(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Dp(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Lp(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Pp(n)}})},Mp=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=tt(n))||void 0===t?void 0:t.data;return r?jt(r):void 0})()}}),Up=e=>{const t=Ye();t.log("channel/getMyMembership.locally");const n=tt(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Ge("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Fp(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Fp(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>Fp(e[n],t[n])))}const Np=[];let Bp=null;const jp=e=>{if(0===Np.length){const e=Ye(),t=async e=>{const t=await Rp(e);Ff(t),Np.forEach((e=>e(t.channels[0])))};Bp=Mt(e,"onChannelCreated","channel.created",t)}return Np.push(e),()=>(e=>{const t=Np.indexOf(e);t>-1&&Np.splice(t,1),0===Np.length&&(null==Bp||Bp())})(e)},$p=[],qp=[],Kp=e=>{const t=Ye();if(0===$p.length){const e=async e=>{const t=await Rp(e);Ff(t),$p.forEach((e=>e(t.channels[0])))};qp.push(Mt(t,"onChannelUpdated","channel.updated",e)),qp.push(Mt(t,"onChannelUpdated","local.channel.updated",(e=>$p.forEach((t=>t(e.channels[0]))))))}return $p.push(e),()=>(e=>{const t=$p.indexOf(e);t>-1&&$p.splice(t,1),0===$p.length&&qp.forEach((e=>e()))})(e)},Gp=e=>{const t=et(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{nt(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Wp=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=tt(n))||void 0===t?void 0:t.data)&&it(n)},Hp=[];let Vp=null;const Yp=e=>{if(0===Hp.length){const e=Ye(),t=async t=>{const n=await Rp(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)Gp(e.channelId),Wp(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=tt(t);n&&nt(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Ff(n),Hp.forEach((e=>e(n.channels[0])))};Vp=Mt(e,"onChannelDeleted","channel.deleted",t)}return Hp.push(e),()=>(e=>{const t=Hp.indexOf(e);t>-1&&Hp.splice(t,1),0===Hp.length&&(null==Vp||Vp())})(e)},Qp=[];let zp=null;const Jp=e=>{if(0===Qp.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),Qp.forEach((e=>e(n[0],r[0])))};zp=Mt(e,"onChannelJoined","channel.joined",t)}return Qp.push(e),()=>(e=>{const t=Qp.indexOf(e);t>-1&&Qp.splice(t,1),0===Qp.length&&(null==zp||zp())})(e)},Xp=[];let Zp=null;const eg=e=>{if(0===Xp.length){const e=Ye(),t=async t=>{const{userId:n}=Ye(),{channelUsers:r}=t,s=r.some((e=>e.userId===n)),i=await Rp(t,{isMessagePreviewUpdated:s}),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,o=e.useLegacyUnreadCount;s&&i.channels.forEach((e=>{a?(Gp(e.channelId),Wp(e.channelId)):o&&it(["channelUnread","get",e.channelId])}));const{channels:l,channelUsers:c}=i;Ff(i),Xp.forEach((e=>e(l[0],c[0])))};Zp=Mt(e,"onChannelLeft","channel.left",t)}return Xp.push(e),()=>(e=>{const t=Xp.indexOf(e);t>-1&&Xp.splice(t,1),0===Xp.length&&(null==Zp||Zp())})(e)},tg=[];let ng=null;const rg=e=>{if(0===tg.length){const e=Ye(),t=async e=>{var t;st(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&tg.forEach((e=>e(n)))};ng=Mt(e,"onChannelMute","channel.setMuted",t)}return tg.push(e),()=>(e=>{const t=tg.indexOf(e);t>-1&&tg.splice(t,1),0===tg.length&&(null==ng||ng())})(e)},sg=[];let ig=null;const ag=e=>{if(0===sg.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),sg.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))};ig=Mt(e,"onChannelMemberAdded","channel.membersAdded",t)}return sg.push(e),()=>(e=>{const t=sg.indexOf(e);t>-1&&sg.splice(t,1),0===sg.length&&(null==ig||ig())})(e)},og=[];let lg=null;const cg=e=>{if(0===og.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),og.forEach((e=>e(n[0],r[0])))};lg=Mt(e,"onChannelMemberRemoved","channel.membersRemoved",t)}return og.push(e),()=>(e=>{const t=og.indexOf(e);t>-1&&og.splice(t,1),0===og.length&&(null==lg||lg())})(e)},dg=[];let ug=null;const hg=e=>{const t=Ye();return ug=Mt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Rp(e),{channels:r,channelUsers:s}=n,i=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&i&&n.channels.forEach((e=>{Gp(e.channelId),Wp(e.channelId)})),Ff(n),dg.forEach((e=>e(r[0],s.find((e=>"banned"===e.membership)))))})),dg.push(e),()=>(e=>{const t=dg.indexOf(e);t>-1&&dg.splice(t,1),0===dg.length&&(null==ug||ug())})(e)},fg=[];let pg=null;const gg=e=>{if(0===fg.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),fg.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))};pg=Mt(e,"onChannelMemberUnbanned","channel.unbanned",t)}return fg.push(e),()=>(e=>{const t=fg.indexOf(e);t>-1&&fg.splice(t,1),0===fg.length&&(null==pg||pg())})(e)},mg=[];let yg=null;const vg=e=>{if(0===mg.length){const e=Ye(),t=async e=>{const{channels:t,channelUsers:n}=e;mg.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))};yg=Mt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",t)}return mg.push(e),()=>(e=>{const t=mg.indexOf(e);t>-1&&mg.splice(t,1),0===mg.length&&(null==yg||yg())})(e)},bg=[];let wg=null;const Sg=e=>{if(0===bg.length){const e=Ye(),t=async e=>{const{channels:t,channelUsers:n}=e;bg.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))};wg=Mt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",t)}return bg.push(e),()=>(e=>{const t=bg.indexOf(e);t>-1&&bg.splice(t,1),0===bg.length&&(null==wg||wg())})(e)},Eg=e=>{const t=Ye();return Mt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Ig=e=>{const t=Ye();return Mt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Tg=[];let Ag=null;const Cg=e=>{if(0===Tg.length){const e=Ye(),t=async e=>{var t,n,r;e.userIds.forEach((t=>st(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=et(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,i=null===(r=tt(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===r?void 0:r.data;s&&i&&Tg.forEach((e=>e(s,i)))};Ag=Mt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Tg.push(e),()=>(e=>{const t=Tg.indexOf(e);t>-1&&Tg.splice(t,1),0===Tg.length&&(null==Ag||Ag())})(e)},_g=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=et(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Mp(e))))}return zf(e,{markAsRead:()=>(async e=>{const t=Ye();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:i}=n,a=Bf(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=t.cache&&Date.now(),l=Kf(s),c=Gf(i);return t.cache&&Ff(Object.assign({userMarkers:r,userEntityMarkers:l,userFeedMarkers:c},a),{cachedAt:o}),Ut("local.channelMarker.updated",{userEntityMarkers:l}),Ut("local.subChannelMarker.updated",{userFeedMarkers:c}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Rt();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:s}=Ye();s||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const i=[];let a=!1;const o=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Mp(e.data):e.data}))},l=(t,n)=>{const{data:r}=Up(e);Fp(void 0,r)||o({loading:!1,data:r})};return i.push(hg(l)),i.push(gg(l)),i.push(Cg(l)),(()=>{const t=Be((async()=>Up(e)));$e(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,i.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&i.forEach((e=>e()))}))})(),()=>{i.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Rg=e=>_g(xp((e=>{var t;const n=e.messagePreviewId?Wf(e.channelId):null,r=null===(t=tt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:r?jt(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),Og=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("channel",e)})),t}const s=await Rp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(r);const i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("local.channel.fetched",s.channels),{data:s.channels.map((e=>Rg(e))),cachedAt:i}};Og.locally=e=>{var t,n;const r=Ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const i=s.map((({data:e})=>e)),a=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:i.map((e=>Rg(e))),cachedAt:a.cachedAt}};const kg=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Pg=!1;const Dg={},Lg=async()=>{const e=Object.entries(Dg).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ye();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=n,o=Kf(r),l=Gf(s),c=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Ut("local.feedMarker.fetched",{feedMarkers:i}),Ut("local.channelMarker.fetched",{userEntityMarkers:o}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:l}),Ut("local.userMarker.fetched",{userMarkers:a}),!0})(e)},xg=()=>{Pg=!1},Mg=()=>(Pg=!0,Th((e=>{"notLoggedIn"===e&&xg()})),()=>{xg()});kg((async()=>{Pg&&await Lg()}),3e4);const Ug=async e=>{const t=Ye();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:s}};Ug.locally=e=>{var t;const n=Ye();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>tt(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Fg=async(e=!0)=>{var t;const n=null===(t=tt(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await Uf();var s;return(s=r).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Ng=async()=>{var e;const t=await Fg();if(t===(null===(e=tt(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;nt(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=et(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=et(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Og(n),0!==r.length&&await Ug(r)}},Bg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},jg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},$g={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},qg=async()=>{var t,n;const r=Ye(),{data:s}=await r.http.get("/api/v3/network-settings/video-streaming"),i=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,a=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(o=i)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&o!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&o!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(a)?(r.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:i,threshold:a}),$g):{mode:i,threshold:a};var o},Kg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Gg=async()=>{var e,t;const n=Ye(),{data:r}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=r.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},Wg=(e,t)=>{var n;const r=null===(n=tt(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Hg=e=>{const{userId:t}=Ye();return{currentUser:()=>Wg(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=tt(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Wg(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=tt(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Wg(e,t))})(t,e,n)}},Vg=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},Yg=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},Qg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},zg={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Jg=(e,t)=>{const n=Ye();n.log("client/api/setSessionState",e,t);const{sessionState:r}=n;if(r===e)return!1;if(!((e,t)=>zg[e].includes(t))(r,e))throw new Ke(`Session state cannot change from ${r} to ${e}`,8e5,"error");return n.sessionState=e,Ih().setSessionState(e,t),!0};function Xg(e){return{users:e.users.map(fp),files:e.files}}const Zg=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getToken",e);const r=Df(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},em=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getVisitorToken",e);const r=Df(),{data:s}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},tm=async()=>{var e;const t=Ye();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&Jg("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=void 0,t.isGloballyBanned=!1,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},nm=e=>{const t=Ye();Jg("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,tm()};let rm=null;const sm=e=>{rm=e},im=({user:e,userType:t})=>{Ot(e),sm(t)},am=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Xg(e);n.cache&&Ff(r),t(r.users[0])}))},om=e=>am("user.deleted",e),lm=["analytic","normal-priority"],cm=["analytic","high-priority"],dm=async e=>{const t=Ye(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class um{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=tt(lm);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await dm(t),it(lm)}catch(e){this.stop(),it(lm)}}async syncHighPriorityCapturedEvent(){try{const e=tt(cm);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await dm(t),it(cm)}catch(e){this.stop(),it(cm)}}}class hm{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(r.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const i=new Date,a={event:[]},o=tt(lm);(null==o?void 0:o.data)&&(a.event=o.data.event),a.event.length>=this._poolLimit&&a.event.shift();const l={contentId:t,contentType:n,activityType:r,timestamp:i.toISOString()};s&&(l.metadata=s),a.event.push(l),st(lm,a),this._recentViewed[e]=i}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const r=null===(n=tt(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),r&&(s.feedSnapshotPosition=r.feedSnapshotPosition,s.feedInjectionType=r.feedInjectionType,s.feedRelevanceScore=r.feedRelevanceScore,s.feedPopularityScore=r.feedPopularityScore,s.feedFreshnessScore=r.feedFreshnessScore,s.feedAffinityScore=r.feedAffinityScore,s.feedFinalScore=r.feedFinalScore,s.feedMmrPenalty=r.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const s={event:[]},i=tt(cm);if((null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),st(cm,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;nt(["story-seen","get",e.storyId],(new Date).toISOString());const a=tt(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&nt(["story-last-seen",e.targetId],e.expiresAt):nt(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Ut("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},it(lm),it(cm)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markProductAsClicked(e,t,n,r){const s={location:t,sourceType:n,sourceId:r},i="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:i,metadata:s})}markProductAsViewed(e,t,n,r){const s={location:t,sourceType:n,sourceId:r},i="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:i,metadata:s})}}class fm{constructor(){this._client=Ye(),this._eventCapturer=new hm,this._eventSyncer=new um}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}markProductAsClicked(e,t,n,r){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,r)}markProductAsViewed(e,t,n,r){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,r)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let pm;var gm=()=>(pm||(pm=new fm),pm),mm=()=>{const e=gm();return e.established(),Th((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class ym{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=et(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=tt(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Ye();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],s=null===(t=tt(r))||void 0===t?void 0:t.data;nt(r,Object.assign(Object.assign({},s),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],s=null===(n=tt(r))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),nt(r,s),Ut("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=tt(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)nt(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{nt(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let vm=null;var bm=()=>(vm||(vm=new ym),vm),wm=()=>{const e=bm();return e.startSyncReadReceipt(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Sm{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=et(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=tt(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:s}=n,i=await(async({subChannelId:e,readToSegment:t})=>{const n=Ye();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:s});if(i){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=tt(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;nt(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else i||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],s=null===(n=tt(r))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=Zf(s.channelId);Ut("local.channelUnreadInfo.updated",e),nt(r,s),Ut("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=tt(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)nt(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{nt(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let Em=null;var Im=()=>(Em||(Em=new Sm),Em),Tm=()=>{const e=Im();return e.startSyncReadReceipt(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Am=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("online",e),()=>window.removeEventListener("online",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("online",e),()=>document.removeEventListener("online",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),Cm=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("offline",e),()=>window.removeEventListener("offline",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("offline",e),()=>document.removeEventListener("offline",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),_m=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("channel",e)})),t}const s=await Rp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(r);const i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("local.channel.fetched",s.channels),{data:s.channels,cachedAt:i}};_m.locally=e=>{var t,n;const r=Ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Rm{constructor(){this.TIMER_INTERVAL_MS=J,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Am((()=>{this.isConnected=!0}))),this.connectionListener.push(Cm((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await _m(e);const s=null!==(r=null===(n=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];Ut("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await Op(e),{feedMarkers:n,userFeedMarkers:r}=t;ep({feedMarkers:n,userFeedMarkers:r}),Ut("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Om=null;var km=()=>(Om||(Om=new Rm),Om),Pm=()=>{const e=km();return e.startResolver(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Dm{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Am((()=>{this.isConnected=!0}))),this.connectionListener.push(Cm((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{roomId:n,streamId:r}=t,s=Bf(t,["roomId","streamId"]),i=r?"liveStream":"room",a=null!=r?r:n;return e[a]||(e[a]={referenceType:i,reactions:[]}),e[a].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const r=Ye();r.log("live_reaction/addReaction",e);const{data:s}=await r.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Lm;var xm=()=>(Lm||(Lm=new Dm),Lm);function Mm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:fp(n)})})),users:t.map(fp)})}class Um{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),r=Mm(t);e.cache&&Ff(r,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=et(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,r;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(r=t.updatedAt)&&void 0!==r?r:"")?1:-1})).map((e=>{var t;return null===(t=tt(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(jt)}}let Fm=null;var Nm=()=>(Fm||(Fm=new Um),Fm);function Bm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:fp(n)})})),users:t.map(fp)})}class jm{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),r=Bm(t);e.cache&&Ff(r,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=et(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,r;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(r=t.updatedAt)&&void 0!==r?r:"")?1:-1})).map((e=>{var t;return null===(t=tt(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(jt)}}let $m=null;var qm=()=>($m||($m=new jm),$m);function Km(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(fp)})}function Gm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(fp)})}function Wm(e){const{follows:t}=e,n=Bf(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Hm=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Km(e);n.cache&&Ff(r),t(r.follows[0])}))},Vm=e=>Hm("user.didBlock",e),Ym=e=>Hm("user.didUnblock",e);class Qm{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=$t();if(!e)return null;const t=Gt(e),{userId:n}=e;return t&&n?new Qm(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return Th((e=>{var t;"terminated"===e&&(null===(t=Qm.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await xh(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await Lh(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await Lh(this.key,"")}}const zm=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Jm=e=>{const t=Ye(),n=zm.map((n=>Mt(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new Ke(t.message,t.code,"fatal"):new He(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Xm=e=>{const t=Ye();return Mt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Zm=e=>{const t=Ye();return Mt(t,"client/onTokenExpired","tokenExpired",e)},ey=e=>{const t=Ye();return Mt(t,"client/onTokenTerminated","tokenTerminated",e)},ty=e=>{const t=Je("channelMarker")({userId:Rt()._id,entityId:e.channelId});it(["channelMarker","get",t],!0)},ny=e=>{const t=Ye(),n=[];return n.push(Xm((t=>{nm("globalBan"),n.forEach((e=>e())),e()})),ey((t=>{nm(),n.forEach((e=>e())),e()})),om((r=>{r.userId===t.userId&&(nm("userDeleted"),n.forEach((e=>e())),e())})),Zm((e=>{Ih().setSessionState(e),tm(),n.forEach((e=>e()))})),Yp(ty),hg(ty),Mg(),mm(),Pm(),(()=>{const e=xm();return e.startReactionsSync(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Nm();return Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=qm();return Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Vm((()=>{})),Ym((()=>{}))];return()=>e.forEach((e=>e()))})(),Th((e=>{"established"!==e&&kh().reset()})),Qm.clearOnLogout()),t.useLegacyUnreadCount?n.push(wm()):n.push(Tm()),n};let ry=[];const sy=async(e,t,n)=>{const r=Ye();let s;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await tm(),ry.forEach((e=>e())),ry=[]);const i=await Pf();try{const{users:n,userType:a}=await Zg({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||i}),options:{setAccessTokenCookie:!0}}),o=n.find((t=>t.userId===e.userId));if(null==o)throw new Ke(`${e.userId} has not been founded`,8e5,"error");if(o.isDeleted)return nm("userDeleted"),!1;if(o.isGlobalBan)return nm("globalBan"),!1;r.userId=o.userId,r.sessionHandler=t,r.loginType="userId",s=r.accessTokenExpiryWatcher(),im({user:o,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Bt()}(),await Ng(),0===ry.length&&(ry=ny(s)),!0},iy=[],ay=async e=>{const t=Ye();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const r=await Pf();let s;try{const{users:i,userType:a}=await em({params:Object.assign(Object.assign({},e),{deviceId:r}),options:{setAccessTokenCookie:!0}});[s]=i,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),im({user:s,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return await Ng(),0===iy.length&&iy.push(ey((e=>{nm(),iy.forEach((e=>e())),n()})),Zm((e=>{Ih().setSessionState(e),tm(),iy.forEach((e=>e()))}))),!0},oy=()=>{let e,t=!1;const n=Ye();n.log("initiating access token renewal");const r=async r=>{const{userId:s,displayName:i}=Rt(),a={userId:s,displayName:i,authToken:r,deviceId:await Pf()};"tokenExpired"===n.sessionState&&n.sessionHandler?await sy(a,n.sessionHandler):await Zg({params:a,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(oy())}),X)},renewWithAuthSignature:r=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:r,authSignatureExpiresAt:s})=>{const i=await Pf();"tokenExpired"===n.sessionState&&n.sessionHandler?await ay({sessionHandler:n.sessionHandler}):await em({params:{authSignature:r,authSignatureExpiresAt:s,deviceId:i},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(r)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(oy())}),X)}}};function ly(e){this.message=e}ly.prototype=new Error,ly.prototype.name="InvalidCharacterError";var cy="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new ly("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,s=0,i=0,a="";r=t.charAt(i++);~r&&(n=s%4?64*n+r:r,s++%4)?a+=String.fromCharCode(255&n>>(-2*s&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a};function dy(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(cy(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return cy(t)}}function uy(e){this.message=e}function hy(e,t){if("string"!=typeof e)throw new uy("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(dy(e.split(".")[n]))}catch(e){throw new uy("Invalid token specified: "+e.message)}}uy.prototype=new Error,uy.prototype.name="InvalidTokenError";const fy=async({token:e,userId:t})=>{const n=Ye(),{data:r}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:i,userType:a}=r,[o]=s;return t&&(null==o?void 0:o.userId)&&t!==o.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:o.userId}),n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,Ff(Xg({users:s,files:i})),sm(a),o},py=e=>{var t;const n=Ye(),r=hy(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId};let gy=[];const my=async e=>{var t,n;const r=Ye();let s,i;if(r.log("client/api/loginWithAccessToken",{apiKey:r.apiKey,sessionState:r.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Ke("Access token must be a non-empty string",8e5,"error");try{i=hy(e)}catch(e){throw new Ke("Invalid access token format",400100,"error")}const a=(null===(t=null==i?void 0:i.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==i?void 0:i.user)||void 0===n?void 0:n.userId);if(!a)throw new Ke("Access token does not contain userId",400100,"error");if(r.userId){py(e)||await tm()}try{Jg("establishing");const t={accessToken:e,issuedAt:i.iat?new Date(1e3*i.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*i.exp).toISOString()},n=await fy({token:t,userId:a});if(null==n)throw Jg("notLoggedIn"),new Ke(`User ${a} has not been found`,8e5,"error");r.userId=n.userId,r.loginType="accessToken",Ot(n),s=r.accessTokenExpiryWatcher(),Jg("established")}catch(e){if(Jg("notLoggedIn"),e instanceof Ke)throw 400312===e.code&&(r.isGloballyBanned=!0),e;throw new Ke((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await Bt()}(),await Ng(),0===gy.length&&(gy=ny(s)),!0},yy=async e=>{var t,n;const r=Ye();if(r.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Ke("Access token must be a non-empty string",8e5,"error");let s;try{s=hy(e)}catch(e){throw new Ke("Invalid access token format",400100,"error")}const i=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!i)throw new Ke("Access token does not contain userId",400100,"error");if(r.userId){py(e)||await tm()}const a={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===r.sessionState&&r.sessionHandler)await my(e);else try{await fy({token:a,userId:i})}catch(e){throw e instanceof Ke&&400312===e.code&&(r.isGloballyBanned=!0),e}},vy=async({useScheduledTask:e=!1})=>{const t=Ye();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Dt((()=>yy(n))):yy(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},by=3e5,wy=()=>{const e=setInterval((async()=>{const e=Ye(),{sessionHandler:t,accessTokenHandler:n,loginType:r}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:i}=e.token;if((e=>Date.now()>Date.parse(e)-by)(i))return Ut("tokenExpired","tokenExpired"),void("accessToken"===r&&n?await vy({useScheduledTask:!1}):"userId"===r&&t&&Dt((()=>t.sessionWillRenewAccessToken(oy()))));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),s=Date.parse(n),i=Date.now();return i>s+.8*(r-s-by)&&i<r})({expiresAt:i,issuedAt:s})&&("accessToken"===r&&n?await vy({useScheduledTask:!1}):"userId"===r&&t&&t.sessionWillRenewAccessToken(oy()))}),X);return()=>clearInterval(e)},Sy=e=>{if(Ye().useLegacyUnreadCount){bm().markRead(e.channelId,e.channelSegment)}else{Im().markRead(e.subChannelId,e.channelSegment)}},Ey=e=>{const t=Ye(),n=Rt(),r=[Mt(t,"message/onMessageCreated","message.created",(async r=>{const s=await dp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Ye(),r=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=tt(r))||void 0===t?void 0:t.data;if(!s)return;const i=s.lastSegment<e.segment?e.segment:s.lastSegment,a=i-s.readToSegment;let{lastMentionSegment:o}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(o=e.segment)}));const l=Object.assign(Object.assign({},s),{lastMentionSegment:o,lastSegment:i,isMentioned:!(s.readToSegment>=o),unreadCount:Math.max(a,0)});nt(r,l)})(e),Zf(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r,s;const i=null===(n=tt(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!i||i.lastSegment>=e.segment)return;const a=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:i.lastMentionedSegment,l=null!==(s=i.readToSegment)&&void 0!==s?s:0,c=Object.assign(Object.assign({},i),{lastSegment:a,unreadCount:Math.max(a-l,0),lastMentionedSegment:o,isMentioned:"number"==typeof o&&l<o});nt(["channelUnread","get",e.channelId],c),Ut("local.channelUnread.updated",[c])})),Ff(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&Sy(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Iy=e=>{const t=Ye(),n=[Mt(t,"message/onMessageCreated","local.message.created",(async t=>(Ff(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Ty=e=>{const t=Ye();return Mt(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await mp(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:s}=e,i={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:s};nt(["subChannelUnreadInfo","get",i.subChannelId],i)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Ff(r),e(r.messageFeeds[0])}))},Ay=e=>{const t=Ye(),n=[Mt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await mp(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=tt(n))||void 0===t?void 0:t.data;r&&nt(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),Zf(e.channelId)})),Ff(r),e(r.messageFeeds[0])})),Mt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Cy=async e=>{const t=Ye();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=n,o=Kf(r),l=Gf(s),c=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Ut("local.feedMarker.fetched",{feedMarkers:i}),Ut("local.channelMarker.fetched",{userEntityMarkers:o}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:l}),Ut("local.userMarker.fetched",{userMarkers:a}),{data:n,hasMore:n.feedMarkers.length>0}};let _y=!1,Ry=[],Oy=!1;let ky=null;let Py=[];const Dy=e=>{Py=e},Ly=async()=>{var e;if(!Oy&&0!==Py.length)try{Oy=!0,Py=[];const t=await Cy((null==ky?new Date:ky).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!ky||e.getTime()>ky.getTime())&&(ky=e),t.hasMore&&Py.push("has_more")}catch(e){}finally{Oy&&(Oy=!1)}};kg((async()=>{_y&&await Ly()}),2e3);const xy=()=>true;let My=[];var Uy;class Fy{constructor(){Uy.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?s.call(e,n):s?s.value=n:t.set(e,n)}(this,Uy,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,Uy,"f")}}let Ny;Uy=new WeakMap;var By=()=>(Ny||(Ny=new Fy),Ny);const jy={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},$y=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getBotToken");const r=Df(),{data:s}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},qy=[];function Ky(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function Gy(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Wy{constructor(e){this.channelId=e}async enable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ye(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Hy{async enable(t){var n;const r=Ye(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Gy(e.rolesFilter)))))&&void 0!==n?n:[],i={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await r.http.post("/api/v3/notification/setting",i)}async disableAllNotifications(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:r}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),i=(null!==(t=r.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:Ky(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:r.isPushNotifiable,modules:i}}}class Vy{constructor(e){this.communityId=e}async enable(t){var n;const r=Ye(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Gy(t.rolesFilter)))))&&void 0!==n?n:[],i={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await r.http.post("/api/v3/notification/setting",i)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:r}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),i=(null!==(t=r.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:Ky(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:r.isPushNotifiable,events:i}}}class Yy{user(){return new Hy}community(e){return new Vy(e)}channel(e){return new Wy(e)}}const Qy=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},zy=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Jy=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Xy=e=>{const t=Ye();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Zy=e=>{const t=Ye();return Mt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ev=e=>{const t=Ye();return Mt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,s;Ff(t);const i=et(["message","collection"]),{contentMarkers:a,feedMarkers:o}=t;if(i&&(null==i?void 0:i.length)>0&&(null==o?void 0:o.length)>0){const e=i.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===o[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(s=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>tt(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const r=["messageMarker","get",Je("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=tt(r))||void 0===t?void 0:t.data;if(!s)return;const i=a[0].feedId===s.feedId,o=a[0].readCount>s.readCount,l=(null===(n=a[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(i){const e=Object.assign(Object.assign({},s),{readCount:o?a[0].readCount:s.readCount,deliveredCount:l?a[0].deliveredCount:s.deliveredCount});nt(r,e)}}))}}e(t.contentMarkers[0])}))};function tv(e){return"object"==typeof e&&null!==e}const nv=e=>{if(!tv(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},rv=e=>{if(!tv(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var sv=Object.freeze({__proto__:null,getActiveClient:Ye,getActiveUser:Rt,setActiveUser:Ot,createClient:(e,t=hn.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:s,rteEnabled:i=!0}={})=>{var a,o,l;const c=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!un,n=ln(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);c("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(a=null==r?void 0:r.http)&&void 0!==a?a:pn("http",t),u=null!==(o=null==r?void 0:r.upload)&&void 0!==o?o:pn("upload",t),h=null!==(l=null==r?void 0:r.mqtt)&&void 0!==l?l:pn("mqtt",t),f=Ps(d),p=Ps(u);let g;i&&(g=Mf(h));const m=xt(),y={version:`${G}`,apiKey:e,log:c,cache:{data:{}},http:f,ws:undefined,mqtt:g,upload:p,emitter:m,sessionState:"notLoggedIn",accessTokenExpiryWatcher:wy,sessionHandler:undefined,hasPermission:Hg,validateUrls:Vg,validateTexts:Yg,getFeedSettings:Qg,getCoreUserSettings:jg,getSocialSettings:Bg,getChatSettings:Uf,getLiveViewerCountConfig:qg,getVisitorDeviceId:Pf,getMessagePreviewSetting:Fg,use:()=>Qe(y),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:xy,getProductCatalogueSetting:Kg,getForYouFeedSetting:Gg,prefixDeviceIdKey:s};try{const t=Ye();if(t.apiKey===e)return t;Qe(y)}catch(e){Qe(y)}return y},login:sy,loginWithAccessToken:my,logout:tm,secureLogout:async()=>{const e=Ye(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await tm()},resumeSession:async(e,t,n)=>{const r=Ye();let s;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&py(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),My.forEach((e=>e())),My=[]):(await tm(),My.forEach((e=>e())),My=[]));try{Jg("establishing");const n=await fy(e);if(null==n)throw new Ke(`${e.userId} has not been found`,8e5,"error");r.userId=n.userId,r.sessionHandler=t,s=r.accessTokenExpiryWatcher(),Ot(n)}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Bt()}(),await Ng(),0===My.length&&(My.push(Xm((e=>{nm("globalBan"),My.forEach((e=>e())),s()})),ey((e=>{nm(),My.forEach((e=>e())),s()})),om((e=>{e.userId===r.userId&&(nm("userDeleted"),My.forEach((e=>e())),s())})),Zm((e=>{Ih().setSessionState(e),tm(),My.forEach((e=>e()))})),Yp(ty),hg(ty),Mg(),mm(),Pm()),r.useLegacyUnreadCount?My.push(wm()):My.push(Tm())),!0},isConnected:()=>{var e,t;const n=Ye();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:Qg,renewal:oy,markerSync:Cy,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){By().setFileAccessType(e)},fetchLinkPreview:async e=>{const t=Ye();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getLinkPreviewMetadata:async e=>{const t=Ye(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Bg,getShareableLinkConfiguration:async()=>{var e,t;const n=Ye(),{data:r}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=r.domain)&&void 0!==e?e:"",i=null!==(t=r.patterns)&&void 0!==t?t:{};return{domain:s,patterns:i,isEnabled(e){const{key:t}=jy[e];return!!s&&!!i[t]},getPattern(e){const{key:t}=jy[e];return i[t]||null},generateLink(e,t){const{key:n,placeholder:r}=jy[e];return s&&i[n]?s+i[n].replace(`{${r}}`,t):null}}},getProductCatalogueSetting:Kg,getForYouFeedSetting:Gg,loginAsVisitor:ay,loginAsBot:async e=>{const t=Ye();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const r=await Pf();let s;try{const{users:i,userType:a}=await $y({params:{deviceId:r},options:{setAccessTokenCookie:!0}});[s]=i,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),im({user:s,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return await Ng(),0===qy.length&&qy.push(ey((e=>{nm(),qy.forEach((e=>e())),n()})),Zm((e=>{Ih().setSessionState(e),tm(),qy.forEach((e=>e()))}))),!0},getCurrentUser:$t,getCurrentUserType:()=>{if(!rm)throw new Ke("Connect client first",8e5,"fatal");return rm},setCurrentUserType:sm,setAccessTokenHandler:e=>{const t=Ye();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Uf,getLiveViewerCountConfig:qg,getCoreUserSettings:jg,notifications:()=>new Yy,enableAutoSubscriptions:e=>{const t=kh();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=kh();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>kh().subscriptions(),onConnectionError:Jm,onClientDisconnected:e=>Jm((({code:t})=>{800211===t&&e()})),onClientBanned:Xm,onSessionStateChange:Th,onNetworkActivities:e=>_s().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ye();return Mt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Rt();if(!t)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ye();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;i=r?nv(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(Xy((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),s=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};Fp(i,a)||o({loading:!1,data:a})})(e)))),(()=>{const e=Be(tp);$e(e,(({error:e,data:t,loading:n,origin:r,cachedAt:i})=>{!function(e){return null!=e&&null!=e}(t)?o({loading:n,data:void 0,origin:r,error:e}):(i===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Py,setMarkerSyncEvents:Dy,pushMarkerSyncEvent:e=>Py.push(e),markerSyncTrigger:Ly,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{_y=!1,Dy([]),Ry.forEach((e=>e())),Ry=[]},getMarkerSyncConsistentMode:xy});const iv=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Km(e);n.cache?(Ff(r),t(r.follows[0])):t(r.follows[0])}))},av=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Wm(e);n.cache?(Ff(r),t(r.follows[0])):t(r.follows[0])}))},ov=e=>iv("follow.created",e),lv=e=>iv("follow.unfollowed",e),cv=e=>iv("follow.followerDeleted",e),dv=e=>iv("follow.requested",e),uv=e=>iv("follow.requestCanceled",e),hv=e=>iv("follow.accepted",e),fv=e=>iv("follow.requestDeclined",e),pv=async e=>{var t,n;const r=Ye();r.log("follow/getFollowInfo",e);const{data:s}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),i=r.cache&&Date.now(),a="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return r.cache&&nt(["followInfo","get",e],a,{cachedAt:i}),{data:a,cachedAt:i}};pv.locally=e=>{const t=Ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=tt(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const gv=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([pv(t.from),pv(t.to)]);e(n),e(r)},n=[iv("follow.created",t),iv("follow.requested",t),iv("follow.accepted",t),iv("follow.unfollowed",t),iv("follow.requestCanceled",t),iv("follow.requestDeclined",t),iv("follow.followerDeleted",t),av("local.follow.created",t),av("local.follow.requested",t),av("local.follow.accepted",t),av("local.follow.unfollowed",t),av("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mv=e=>av("local.follow.created",e),yv=e=>av("local.follow.unfollowed",e),vv=e=>av("local.follow.requested",e),bv=e=>av("local.follow.accepted",e),wv=e=>av("local.follow.requestDeclined",e);function Sv(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ev={exports:{}};Ev.exports=function e(t,n,r){function s(a,o){if(!n[a]){if(!t[a]){if(!o&&Sv)return Sv(a);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}o=n[a]={exports:{}},t[a][0].call(o.exports,(function(e){return s(t[a][1][e]||e)}),o,o.exports,e,t,n,r)}return n[a].exports}for(var i=Sv,a=0;a<r.length;a++)s(r[a]);return s}({1:[function(e,t,n){(function(r,s,i,a,o,l,c,d,u){var h=e("crypto");function f(e,t){var n;return void 0===(n="passthrough"!==(t=m(e,t)).algorithm?h.createHash(t.algorithm):new b).write&&(n.write=n.update,n.end=n.update),v(t,n).dispatch(e),n.update||n.end(""),n.digest?n.digest("buffer"===t.encoding?void 0:t.encoding):(e=n.read(),"buffer"!==t.encoding?e.toString(t.encoding):e)}(n=t.exports=f).sha1=function(e){return f(e)},n.keys=function(e){return f(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},n.MD5=function(e){return f(e,{algorithm:"md5",encoding:"hex"})},n.keysMD5=function(e){return f(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var p=h.getHashes?h.getHashes().slice():["sha1","md5"],g=(p.push("passthrough"),["buffer","hex","binary","base64"]);function m(e,t){var n={};if(n.algorithm=(t=t||{}).algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<p.length;++r)p[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=p[r]);if(-1===p.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+p.join(", "));if(-1===g.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+g.join(", "));return n}function y(e){if("function"==typeof e)return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function v(e,t,n){function r(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return n=n||[],{dispatch:function(t){return this["_"+(null===(t=e.replacer?e.replacer(t):t)?"null":typeof t)](t)},_object:function(t){var s,a=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(a);if(o=(o=o?o[1]:"unknown:["+a+"]").toLowerCase(),0<=(a=n.indexOf(t)))return this.dispatch("[CIRCULAR:"+a+"]");if(n.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return r("buffer:"),r(t);if("object"===o||"function"===o||"asyncfunction"===o)return a=Object.keys(t),e.unorderedObjects&&(a=a.sort()),!1===e.respectType||y(t)||a.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(a=a.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+a.length+":"),s=this,a.forEach((function(n){s.dispatch(n),r(":"),e.excludeValues||s.dispatch(t[n]),r(",")}));if(!this["_"+o]){if(e.ignoreUnknown)return r("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,s){s=void 0!==s?s:!1!==e.unorderedArrays;var i=this;if(r("array:"+t.length+":"),!s||t.length<=1)return t.forEach((function(e){return i.dispatch(e)}));var a=[];return s=t.map((function(t){var r=new b,s=n.slice();return v(e,r,s).dispatch(t),a=a.concat(s.slice(n.length)),r.read().toString()})),n=n.concat(a),s.sort(),this._array(s,!1)},_date:function(e){return r("date:"+e.toJSON())},_symbol:function(e){return r("symbol:"+e.toString())},_error:function(e){return r("error:"+e.toString())},_boolean:function(e){return r("bool:"+e.toString())},_string:function(e){r("string:"+e.length+":"),r(e.toString())},_function:function(t){r("fn:"),y(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return r("number:"+e.toString())},_xml:function(e){return r("xml:"+e.toString())},_null:function(){return r("Null")},_undefined:function(){return r("Undefined")},_regexp:function(e){return r("regex:"+e.toString())},_uint8array:function(e){return r("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return r("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return r("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return r("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return r("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return r("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return r("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return r("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return r("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return r("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return r("url:"+e.toString())},_map:function(t){return r("map:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_set:function(t){return r("set:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_file:function(e){return r("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return r("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return r("domwindow")},_bigint:function(e){return r("bigint:"+e.toString())},_process:function(){return r("process")},_timer:function(){return r("timer")},_pipe:function(){return r("pipe")},_tcp:function(){return r("tcp")},_udp:function(){return r("udp")},_tty:function(){return r("tty")},_statwatcher:function(){return r("statwatcher")},_securecontext:function(){return r("securecontext")},_connection:function(){return r("connection")},_zlib:function(){return r("zlib")},_context:function(){return r("context")},_nodescript:function(){return r("nodescript")},_httpparser:function(){return r("httpparser")},_dataview:function(){return r("dataview")},_signal:function(){return r("signal")},_fsevent:function(){return r("fsevent")},_tlswrap:function(){return r("tlswrap")}}}function b(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}n.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),v(t=m(e,t),n).dispatch(e)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,n){(function(e,t,r,s,i,a,o,l,c){!function(e){var t="undefined"!=typeof Uint8Array?Uint8Array:Array,n="+".charCodeAt(0),r="/".charCodeAt(0),s="0".charCodeAt(0),i="a".charCodeAt(0),a="A".charCodeAt(0),o="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===n||e===o?62:e===r||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<a+26?e-a:e<i+26?e-i+26:void 0}e.toByteArray=function(e){var n,r;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.length,i=(s="="===e.charAt(s-2)?2:"="===e.charAt(s-1)?1:0,new t(3*e.length/4-s)),a=0<s?e.length-4:e.length,o=0;function l(e){i[o++]=e}for(n=0;n<a;n+=4,0)l((16711680&(r=c(e.charAt(n))<<18|c(e.charAt(n+1))<<12|c(e.charAt(n+2))<<6|c(e.charAt(n+3))))>>16),l((65280&r)>>8),l(255&r);return 2==s?l(255&(r=c(e.charAt(n))<<2|c(e.charAt(n+1))>>4)):1==s&&(l((r=c(e.charAt(n))<<10|c(e.charAt(n+1))<<4|c(e.charAt(n+2))>>2)>>8&255),l(255&r)),i},e.fromByteArray=function(e){var t,n,r,s,i=e.length%3,a="";function o(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)a+=o((s=n=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+o(s>>12&63)+o(s>>6&63)+o(63&s);switch(i){case 1:a=(a+=o((n=e[e.length-1])>>2))+o(n<<4&63)+"==";break;case 2:a=(a=(a+=o((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+o(n>>4&63))+o(n<<2&63)+"="}return a}}(void 0===n?this.base64js={}:n)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(e,t,n){(function(t,r,s,i,a,o,l,c,d){var u=e("base64-js"),h=e("ieee754");function s(e,t,n){if(!(this instanceof s))return new s(e,t,n);var r,i,a,o,l=typeof e;if("base64"===t&&"string"==l)for(e=(o=e).trim?o.trim():o.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==l)r=k(e);else if("string"==l)r=s.byteLength(e,t);else{if("object"!=l)throw new Error("First argument needs to be a number, array or string.");r=k(e.length)}if(s._useTypedArrays?i=s._augment(new Uint8Array(r)):((i=this).length=r,i._isBuffer=!0),s._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(P(o=e)||s.isBuffer(o)||o&&"object"==typeof o&&"number"==typeof o.length)for(a=0;a<r;a++)s.isBuffer(e)?i[a]=e.readUInt8(a):i[a]=e[a];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!n)for(a=0;a<r;a++)i[a]=0;return i}function f(e,t,n,r){return s._charsWritten=M(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function p(e,t,n,r){return s._charsWritten=M(function(e){for(var t,n,r=[],s=0;s<e.length;s++)t=(n=e.charCodeAt(s))>>8,n%=256,r.push(n),r.push(t);return r}(t),e,n,r)}function g(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;s++)r+=String.fromCharCode(e[s]);return r}function m(e,t,n,r){var s;if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!((r=e.length)<=t))return n?(s=e[t],t+1<r&&(s|=e[t+1]<<8)):(s=e[t]<<8,t+1<r&&(s|=e[t+1])),s}function y(e,t,n,r){var s;if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!((r=e.length)<=t))return n?(t+2<r&&(s=e[t+2]<<16),t+1<r&&(s|=e[t+1]<<8),s|=e[t],t+3<r&&(s+=e[t+3]<<24>>>0)):(t+1<r&&(s=e[t+1]<<16),t+2<r&&(s|=e[t+2]<<8),t+3<r&&(s|=e[t+3]),s+=e[t]<<24>>>0),s}function v(e,t,n,r){if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 32768&(r=m(e,t,n,!0))?-1*(65535-r+1):r}function b(e,t,n,r){if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 2147483648&(r=y(e,t,n,!0))?-1*(4294967295-r+1):r}function w(e,t,n,r){return r||(j("boolean"==typeof n,"missing or invalid endian"),j(t+3<e.length,"Trying to read beyond buffer length")),h.read(e,t,n,23,4)}function S(e,t,n,r){return r||(j("boolean"==typeof n,"missing or invalid endian"),j(t+7<e.length,"Trying to read beyond buffer length")),h.read(e,t,n,52,8)}function E(e,t,n,r,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+1<e.length,"trying to write beyond buffer length"),F(t,65535)),!((s=e.length)<=n))for(var i=0,a=Math.min(s-n,2);i<a;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function I(e,t,n,r,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"trying to write beyond buffer length"),F(t,4294967295)),!((s=e.length)<=n))for(var i=0,a=Math.min(s-n,4);i<a;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function T(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+1<e.length,"Trying to write beyond buffer length"),N(t,32767,-32768)),e.length<=n||E(e,0<=t?t:65535+t+1,n,r,s)}function A(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"Trying to write beyond buffer length"),N(t,2147483647,-2147483648)),e.length<=n||I(e,0<=t?t:4294967295+t+1,n,r,s)}function C(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"Trying to write beyond buffer length"),B(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||h.write(e,t,n,r,23,4)}function _(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+7<e.length,"Trying to write beyond buffer length"),B(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||h.write(e,t,n,r,52,8)}n.Buffer=s,n.SlowBuffer=s,n.INSPECT_MAX_BYTES=50,s.poolSize=8192,s._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.isBuffer=function(e){return!(null==e||!e._isBuffer)},s.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"hex":n=e.length/2;break;case"utf8":case"utf-8":n=L(e).length;break;case"ascii":case"binary":case"raw":n=e.length;break;case"base64":n=x(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;default:throw new Error("Unknown encoding")}return n},s.concat=function(e,t){if(j(P(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new s(0);if(1===e.length)return e[0];if("number"!=typeof t)for(i=t=0;i<e.length;i++)t+=e[i].length;for(var n=new s(t),r=0,i=0;i<e.length;i++){var a=e[i];a.copy(n,r),r+=a.length}return n},s.prototype.write=function(e,t,n,r){isFinite(t)?isFinite(n)||(r=n,n=void 0):(c=r,r=t,t=n,n=c),t=Number(t)||0;var i,a,o,l,c=this.length-t;switch((!n||c<(n=Number(n)))&&(n=c),r=String(r||"utf8").toLowerCase()){case"hex":i=function(e,t,n,r){n=Number(n)||0;var i=e.length-n;(!r||i<(r=Number(r)))&&(r=i),j((i=t.length)%2==0,"Invalid hex string"),i/2<r&&(r=i/2);for(var a=0;a<r;a++){var o=parseInt(t.substr(2*a,2),16);j(!isNaN(o),"Invalid hex string"),e[n+a]=o}return s._charsWritten=2*a,a}(this,e,t,n);break;case"utf8":case"utf-8":a=this,o=t,l=n,i=s._charsWritten=M(L(e),a,o,l);break;case"ascii":case"binary":i=f(this,e,t,n);break;case"base64":a=this,o=t,l=n,i=s._charsWritten=M(x(e),a,o,l);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=p(this,e,t,n);break;default:throw new Error("Unknown encoding")}return i},s.prototype.toString=function(e,t,n){var r,s,i,a,o=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):o.length)===t)return"";switch(e){case"hex":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||r<n)&&(n=r);for(var s="",i=t;i<n;i++)s+=D(e[i]);return s}(o,t,n);break;case"utf8":case"utf-8":r=function(e,t,n){var r="",s="";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=U(s)+String.fromCharCode(e[i]),s=""):s+="%"+e[i].toString(16);return r+U(s)}(o,t,n);break;case"ascii":case"binary":r=g(o,t,n);break;case"base64":s=o,a=n,r=0===(i=t)&&a===s.length?u.fromByteArray(s):u.fromByteArray(s.slice(i,a));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=function(e,t,n){for(var r=e.slice(t,n),s="",i=0;i<r.length;i+=2)s+=String.fromCharCode(r[i]+256*r[i+1]);return s}(o,t,n);break;default:throw new Error("Unknown encoding")}return r},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.prototype.copy=function(e,t,n,r){if(t=t||0,(r=r||0===r?r:this.length)!==(n=n||0)&&0!==e.length&&0!==this.length){j(n<=r,"sourceEnd < sourceStart"),j(0<=t&&t<e.length,"targetStart out of bounds"),j(0<=n&&n<this.length,"sourceStart out of bounds"),j(0<=r&&r<=this.length,"sourceEnd out of bounds"),r>this.length&&(r=this.length);var i=(r=e.length-t<r-n?e.length-t+n:r)-n;if(i<100||!s._useTypedArrays)for(var a=0;a<i;a++)e[a+t]=this[a+n];else e._set(this.subarray(n,n+i),t)}},s.prototype.slice=function(e,t){var n=this.length;if(e=O(e,n,0),t=O(t,n,n),s._useTypedArrays)return s._augment(this.subarray(e,t));for(var r=t-e,i=new s(r,void 0,!0),a=0;a<r;a++)i[a]=this[a+e];return i},s.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},s.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},s.prototype.readUInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},s.prototype.readUInt16LE=function(e,t){return m(this,e,!0,t)},s.prototype.readUInt16BE=function(e,t){return m(this,e,!1,t)},s.prototype.readUInt32LE=function(e,t){return y(this,e,!0,t)},s.prototype.readUInt32BE=function(e,t){return y(this,e,!1,t)},s.prototype.readInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){return v(this,e,!0,t)},s.prototype.readInt16BE=function(e,t){return v(this,e,!1,t)},s.prototype.readInt32LE=function(e,t){return b(this,e,!0,t)},s.prototype.readInt32BE=function(e,t){return b(this,e,!1,t)},s.prototype.readFloatLE=function(e,t){return w(this,e,!0,t)},s.prototype.readFloatBE=function(e,t){return w(this,e,!1,t)},s.prototype.readDoubleLE=function(e,t){return S(this,e,!0,t)},s.prototype.readDoubleBE=function(e,t){return S(this,e,!1,t)},s.prototype.writeUInt8=function(e,t,n){n||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"trying to write beyond buffer length"),F(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,n){E(this,e,t,!0,n)},s.prototype.writeUInt16BE=function(e,t,n){E(this,e,t,!1,n)},s.prototype.writeUInt32LE=function(e,t,n){I(this,e,t,!0,n)},s.prototype.writeUInt32BE=function(e,t,n){I(this,e,t,!1,n)},s.prototype.writeInt8=function(e,t,n){n||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"Trying to write beyond buffer length"),N(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},s.prototype.writeInt16LE=function(e,t,n){T(this,e,t,!0,n)},s.prototype.writeInt16BE=function(e,t,n){T(this,e,t,!1,n)},s.prototype.writeInt32LE=function(e,t,n){A(this,e,t,!0,n)},s.prototype.writeInt32BE=function(e,t,n){A(this,e,t,!1,n)},s.prototype.writeFloatLE=function(e,t,n){C(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){C(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){_(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){_(this,e,t,!1,n)},s.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,j("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),j(t<=n,"end < start"),n!==t&&0!==this.length){j(0<=t&&t<this.length,"start out of bounds"),j(0<=n&&n<=this.length,"end out of bounds");for(var r=t;r<n;r++)this[r]=e}},s.prototype.inspect=function(){for(var e=[],t=this.length,r=0;r<t;r++)if(e[r]=D(this[r]),r===n.INSPECT_MAX_BYTES){e[r+1]="...";break}return"<Buffer "+e.join(" ")+">"},s.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(s._useTypedArrays)return new s(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var R=s.prototype;function O(e,t,n){return"number"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function k(e){return(e=~~Math.ceil(+e))<0?0:e}function P(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function D(e){return e<16?"0"+e.toString(16):e.toString(16)}function L(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else for(var s=n,i=(55296<=r&&r<=57343&&n++,encodeURIComponent(e.slice(s,n+1)).substr(1).split("%")),a=0;a<i.length;a++)t.push(parseInt(i[a],16))}return t}function x(e){return u.toByteArray(e)}function M(e,t,n,r){for(var s=0;s<r&&!(s+n>=t.length||s>=e.length);s++)t[s+n]=e[s];return s}function U(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function F(e,t){j("number"==typeof e,"cannot write a non-number as a number"),j(0<=e,"specified a negative value for writing an unsigned value"),j(e<=t,"value is larger than maximum value for type"),j(Math.floor(e)===e,"value has a fractional component")}function N(e,t,n){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(n<=e,"value smaller than minimum allowed value"),j(Math.floor(e)===e,"value has a fractional component")}function B(e,t,n){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(n<=e,"value smaller than minimum allowed value")}function j(e,t){if(!e)throw new Error(t||"Failed assertion")}s._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=R.get,e.set=R.set,e.write=R.write,e.toString=R.toString,e.toLocaleString=R.toString,e.toJSON=R.toJSON,e.copy=R.copy,e.slice=R.slice,e.readUInt8=R.readUInt8,e.readUInt16LE=R.readUInt16LE,e.readUInt16BE=R.readUInt16BE,e.readUInt32LE=R.readUInt32LE,e.readUInt32BE=R.readUInt32BE,e.readInt8=R.readInt8,e.readInt16LE=R.readInt16LE,e.readInt16BE=R.readInt16BE,e.readInt32LE=R.readInt32LE,e.readInt32BE=R.readInt32BE,e.readFloatLE=R.readFloatLE,e.readFloatBE=R.readFloatBE,e.readDoubleLE=R.readDoubleLE,e.readDoubleBE=R.readDoubleBE,e.writeUInt8=R.writeUInt8,e.writeUInt16LE=R.writeUInt16LE,e.writeUInt16BE=R.writeUInt16BE,e.writeUInt32LE=R.writeUInt32LE,e.writeUInt32BE=R.writeUInt32BE,e.writeInt8=R.writeInt8,e.writeInt16LE=R.writeInt16LE,e.writeInt16BE=R.writeInt16BE,e.writeInt32LE=R.writeInt32LE,e.writeInt32BE=R.writeInt32BE,e.writeFloatLE=R.writeFloatLE,e.writeFloatBE=R.writeFloatBE,e.writeDoubleLE=R.writeDoubleLE,e.writeDoubleBE=R.writeDoubleBE,e.fill=R.fill,e.inspect=R.inspect,e.toArrayBuffer=R.toArrayBuffer,e}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=4,h=new s(u);h.fill(0),t.exports={hash:function(e,t,n,r){for(var i=t(function(e,t){e.length%u!=0&&(n=e.length+(u-e.length%u),e=s.concat([e,h],n));for(var n,r=[],i=t?e.readInt32BE:e.readInt32LE,a=0;a<e.length;a+=u)r.push(i.call(e,a));return r}(e=s.isBuffer(e)?e:new s(e),r),8*e.length),a=(t=r,new s(n)),o=t?a.writeInt32BE:a.writeInt32LE,l=0;l<i.length;l++)o.call(a,i[l],4*l,!0);return a}}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(e,t,n){(function(t,r,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:u,sha256:h,md5:e("./md5")},g=64,m=new s(g);function y(e,t){var n=p[e=e||"sha1"],r=[];return n||v("algorithm:",e,"is not yet supported"),{update:function(e){return s.isBuffer(e)||(e=new s(e)),r.push(e),e.length,this},digest:function(e){var i=s.concat(r);return i=t?function(e,t,n){s.isBuffer(t)||(t=new s(t)),s.isBuffer(n)||(n=new s(n)),t.length>g?t=e(t):t.length<g&&(t=s.concat([t,m],g));for(var r=new s(g),i=new s(g),a=0;a<g;a++)r[a]=54^t[a],i[a]=92^t[a];return n=e(s.concat([r,n])),e(s.concat([i,n]))}(n,t,i):n(i),r=null,e?i.toString(e):i}}}function v(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}m.fill(0),n.createHash=function(e){return y(e)},n.createHmac=y,n.randomBytes=function(e,t){if(!t||!t.call)return new s(f(e));try{t.call(this,void 0,new s(f(e)))}catch(e){t(e)}};var b,w=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],S=function(e){n[e]=function(){v("sorry,",e,"is not implemented yet")}};for(b in w)S(w[b])}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,s=-1732584194,i=271733878,a=0;a<e.length;a+=16){var o=n,l=r,c=s,d=i;n=p(n,r,s,i,e[a+0],7,-680876936),i=p(i,n,r,s,e[a+1],12,-389564586),s=p(s,i,n,r,e[a+2],17,606105819),r=p(r,s,i,n,e[a+3],22,-1044525330),n=p(n,r,s,i,e[a+4],7,-176418897),i=p(i,n,r,s,e[a+5],12,1200080426),s=p(s,i,n,r,e[a+6],17,-1473231341),r=p(r,s,i,n,e[a+7],22,-45705983),n=p(n,r,s,i,e[a+8],7,1770035416),i=p(i,n,r,s,e[a+9],12,-1958414417),s=p(s,i,n,r,e[a+10],17,-42063),r=p(r,s,i,n,e[a+11],22,-1990404162),n=p(n,r,s,i,e[a+12],7,1804603682),i=p(i,n,r,s,e[a+13],12,-40341101),s=p(s,i,n,r,e[a+14],17,-1502002290),n=g(n,r=p(r,s,i,n,e[a+15],22,1236535329),s,i,e[a+1],5,-165796510),i=g(i,n,r,s,e[a+6],9,-1069501632),s=g(s,i,n,r,e[a+11],14,643717713),r=g(r,s,i,n,e[a+0],20,-373897302),n=g(n,r,s,i,e[a+5],5,-701558691),i=g(i,n,r,s,e[a+10],9,38016083),s=g(s,i,n,r,e[a+15],14,-660478335),r=g(r,s,i,n,e[a+4],20,-405537848),n=g(n,r,s,i,e[a+9],5,568446438),i=g(i,n,r,s,e[a+14],9,-1019803690),s=g(s,i,n,r,e[a+3],14,-187363961),r=g(r,s,i,n,e[a+8],20,1163531501),n=g(n,r,s,i,e[a+13],5,-1444681467),i=g(i,n,r,s,e[a+2],9,-51403784),s=g(s,i,n,r,e[a+7],14,1735328473),n=m(n,r=g(r,s,i,n,e[a+12],20,-1926607734),s,i,e[a+5],4,-378558),i=m(i,n,r,s,e[a+8],11,-2022574463),s=m(s,i,n,r,e[a+11],16,1839030562),r=m(r,s,i,n,e[a+14],23,-35309556),n=m(n,r,s,i,e[a+1],4,-1530992060),i=m(i,n,r,s,e[a+4],11,1272893353),s=m(s,i,n,r,e[a+7],16,-155497632),r=m(r,s,i,n,e[a+10],23,-1094730640),n=m(n,r,s,i,e[a+13],4,681279174),i=m(i,n,r,s,e[a+0],11,-358537222),s=m(s,i,n,r,e[a+3],16,-722521979),r=m(r,s,i,n,e[a+6],23,76029189),n=m(n,r,s,i,e[a+9],4,-640364487),i=m(i,n,r,s,e[a+12],11,-421815835),s=m(s,i,n,r,e[a+15],16,530742520),n=y(n,r=m(r,s,i,n,e[a+2],23,-995338651),s,i,e[a+0],6,-198630844),i=y(i,n,r,s,e[a+7],10,1126891415),s=y(s,i,n,r,e[a+14],15,-1416354905),r=y(r,s,i,n,e[a+5],21,-57434055),n=y(n,r,s,i,e[a+12],6,1700485571),i=y(i,n,r,s,e[a+3],10,-1894986606),s=y(s,i,n,r,e[a+10],15,-1051523),r=y(r,s,i,n,e[a+1],21,-2054922799),n=y(n,r,s,i,e[a+8],6,1873313359),i=y(i,n,r,s,e[a+15],10,-30611744),s=y(s,i,n,r,e[a+6],15,-1560198380),r=y(r,s,i,n,e[a+13],21,1309151649),n=y(n,r,s,i,e[a+4],6,-145523070),i=y(i,n,r,s,e[a+11],10,-1120210379),s=y(s,i,n,r,e[a+2],15,718787259),r=y(r,s,i,n,e[a+9],21,-343485551),n=v(n,o),r=v(r,l),s=v(s,c),i=v(i,d)}return Array(n,r,s,i)}function f(e,t,n,r,s,i){return v((t=v(v(t,e),v(r,i)))<<s|t>>>32-s,n)}function p(e,t,n,r,s,i,a){return f(t&n|~t&r,e,t,s,i,a)}function g(e,t,n,r,s,i,a){return f(t&r|n&~r,e,t,s,i,a)}function m(e,t,n,r,s,i,a){return f(t^n^r,e,t,s,i,a)}function y(e,t,n,r,s,i,a){return f(n^(t|~r),e,t,s,i,a)}function v(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}t.exports=function(e){return u.hash(e,h,16)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,t,n){(function(e,n,r,s,i,a,o,l,c){t.exports=function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n,r,s,i=Array(80),a=1732584193,o=-271733879,l=-1732584194,c=271733878,d=-1009589776,u=0;u<e.length;u+=16){for(var h=a,g=o,m=l,y=c,v=d,b=0;b<80;b++){i[b]=b<16?e[u+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(a,5),(w=o,r=l,s=c,(n=b)<20?w&r|~w&s:!(n<40)&&n<60?w&r|w&s|r&s:w^r^s)),f(f(d,i[b]),(n=b)<20?1518500249:n<40?1859775393:n<60?-1894007588:-899497514));d=c,c=l,l=p(o,30),o=a,a=w}a=f(a,h),o=f(o,g),l=f(l,m),c=f(c,y),d=f(d,v)}return Array(a,o,l,c,d)}function f(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function p(e,t){return e<<t|e>>>32-t}t.exports=function(e){return u.hash(e,h,20,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){function u(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function h(e,t){var n,r=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),s=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),i=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var a,o,l=0;l<e.length;l+=16){for(var c=s[0],d=s[1],h=s[2],f=s[3],m=s[4],y=s[5],v=s[6],b=s[7],w=0;w<64;w++)i[w]=w<16?e[w+l]:u(u(u((o=i[w-2],p(o,17)^p(o,19)^g(o,10)),i[w-7]),(o=i[w-15],p(o,7)^p(o,18)^g(o,3))),i[w-16]),n=u(u(u(u(b,p(o=m,6)^p(o,11)^p(o,25)),m&y^~m&v),r[w]),i[w]),a=u(p(a=c,2)^p(a,13)^p(a,22),c&d^c&h^d&h),b=v,v=y,y=m,m=u(f,n),f=h,h=d,d=c,c=u(n,a);s[0]=u(c,s[0]),s[1]=u(d,s[1]),s[2]=u(h,s[2]),s[3]=u(f,s[3]),s[4]=u(m,s[4]),s[5]=u(y,s[5]),s[6]=u(v,s[6]),s[7]=u(b,s[7])}return s}var f=e("./helpers"),p=function(e,t){return e>>>t|e<<32-t},g=function(e,t){return e>>>t};t.exports=function(e){return f.hash(e,h,32,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,n){(function(e,t,r,s,i,a,o,l,c){n.read=function(e,t,n,r,s){var i,a,o=8*s-r-1,l=(1<<o)-1,c=l>>1,d=-7,u=n?s-1:0,h=n?-1:1;for(s=e[t+u],u+=h,i=s&(1<<-d)-1,s>>=-d,d+=o;0<d;i=256*i+e[t+u],u+=h,d-=8);for(a=i&(1<<-d)-1,i>>=-d,d+=r;0<d;a=256*a+e[t+u],u+=h,d-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(s?-1:1);a+=Math.pow(2,r),i-=c}return(s?-1:1)*a*Math.pow(2,i-r)},n.write=function(e,t,n,r,s,i){var a,o,l=8*i-s-1,c=(1<<l)-1,d=c>>1,u=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1;for(i=t<0||0===t&&1/t<0?1:0,t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(r=Math.pow(2,-a))<1&&(a--,r*=2),2<=(t+=1<=a+d?u/r:u*Math.pow(2,1-d))*r&&(a++,r/=2),c<=a+d?(o=0,a=c):1<=a+d?(o=(t*r-1)*Math.pow(2,s),a+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,s),a=0));8<=s;e[n+h]=255&o,h+=f,o/=256,s-=8);for(a=a<<s|o,l+=s;0<l;e[n+h]=255&a,h+=f,a/=256,l-=8);e[n+h-f]|=128*i}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(e,t,n){(function(e,n,r,s,i,a,o,l,c){var d,u,h;function f(){}(e=t.exports={}).nextTick=(u="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:h?(d=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<d.length&&d.shift()())}),!0),function(e){d.push(e),window.postMessage("process-tick","*")}):function(e){setTimeout(e,0)}),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1);var Iv,Tv=Ev.exports;class Av{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,r,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let i;"prev"===e&&(i=this.previousToken),"next"===e&&(i=this.nextToken);const a=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(s=a.paging)||void 0===s?void 0:s.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Cv extends Av{async getRequest(e,t){const{limit:n=W,userId:r}=e,s=Bf(e,["limit","userId"]),i=t?{token:t}:{limit:n},a=Ye().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:o}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:!1})});return o}}class _v{constructor(e,t){this.query=e,this.cacheKey=t}}!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Iv||(Iv={}));class Rv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.follows.map(Je("follow"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Je("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Iv.OnDeclined:case Iv.OnCanceled:case Iv.OnUnfollowed:case Iv.OnDeleted:r.data=r.data.filter((e=>e!==Je("follow")(t)));break;case Iv.OnRequested:case Iv.OnAccepted:case Iv.OnFollowed:r.data=[...new Set([Je("follow")(t),...r.data])]}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ov{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class kv{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof Ov?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof Ov)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof Ov)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(nv).map(rv);return!Fp(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Pv(e){return null!=e}const Dv=({userId:e})=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{const r=Xg(n);Ff(r);const s=tt(["follow","get",Je("follow")({from:r.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Lv extends kv{constructor(e,t){const n=Tv(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new Cv(e),n,r,t),this.query=e,this.queryStreamController=new Rv(this.query,this.cacheKey,this.notifyChange.bind(this),Km),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ov,action:Iv.OnFollowed},{fn:lv,action:Iv.OnUnfollowed},{fn:hv,action:Iv.OnAccepted},{fn:fv,action:Iv.OnDeclined},{fn:uv,action:Iv.OnCanceled},{fn:cv,action:Iv.OnDeleted},{fn:bv,action:Iv.OnAccepted},{fn:wv,action:Iv.OnDeclined},{fn:mv,action:Iv.OnFollowed},{fn:yv,action:Iv.OnUnfollowed},{fn:Dv({userId:this.query.userId}),action:Iv.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["follow","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=tt(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class xv extends Av{async getRequest(e,t){const{limit:n=W,userId:r}=e,s=Bf(e,["limit","userId"]),i=t?{token:t}:{limit:n},a=Ye().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:o}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:!1})});return o}}class Mv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.follows.map(Je("follow"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Je("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Iv.OnDeclined:case Iv.OnCanceled:case Iv.OnUnfollowed:case Iv.OnDeleted:r.data=r.data.filter((e=>e!==Je("follow")(t)));break;case Iv.OnRequested:case Iv.OnAccepted:case Iv.OnFollowed:r.data=[...new Set([Je("follow")(t),...r.data])]}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Uv=({userId:e})=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{const r=Xg(n);Ff(r);const s=tt(["follow","get",Je("follow")({from:e,to:r.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Fv extends kv{constructor(e,t){const n=Tv(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new xv(e),n,r,t),this.query=e,this.queryStreamController=new Mv(this.query,this.cacheKey,this.notifyChange.bind(this),Gm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:dv,action:Iv.OnRequested},{fn:hv,action:Iv.OnAccepted},{fn:fv,action:Iv.OnDeclined},{fn:uv,action:Iv.OnCanceled},{fn:ov,action:Iv.OnFollowed},{fn:lv,action:Iv.OnUnfollowed},{fn:cv,action:Iv.OnDeleted},{fn:vv,action:Iv.OnRequested},{fn:bv,action:Iv.OnAccepted},{fn:wv,action:Iv.OnDeclined},{fn:mv,action:Iv.OnFollowed},{fn:yv,action:Iv.OnUnfollowed},{fn:Uv({userId:this.query.userId}),action:Iv.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["follow","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=tt(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const Nv=(e,t,n,r,s,i)=>{const{forceDispatch:a,callbackDataSelector:o,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=Ye();let d;c||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],f=e=>{const{data:n}=e,r=Bf(e,["data"]);l&&!l(n,d)||t(Object.assign({data:o(n)},r)),d=nv(n)};return h.push(...s.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&Fp(d,t)||f({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=Be(r,e,!0);$e(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===z?(f({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),u=!0,h.forEach((e=>e()))):u||f({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Bv=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ye();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:i}=n,a={follows:s};t.cache&&(Ff(a,{cachedAt:r}),st(["followInfo","get",e],i[0],{cachedAt:r}));const o={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},l=Wm(o);return Ut("local.follow.unfollowed",l),n},unBlockUser:async e=>{const t=Ye();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:i}=n,a={follows:s};t.cache&&(Ff(a,{cachedAt:r}),st(["followInfo","get",e],i[0],{cachedAt:r}));const o=Wm(a);return Ut("local.follow.created",o),n},onUserDidBlock:Vm,onUserDidUnblock:Ym,follow:async e=>{const t=Ye();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const s=Wm(n);return"accepted"===n.follows[0].status?Ut("local.follow.created",s):Ut("local.follow.requested",s),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Ye();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Ye();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Ye();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.requestDeclined",r),!0},onUserFollowed:ov,onUserUnfollowed:lv,onFollowerDeleted:cv,onFollowerRequested:dv,onFollowRequestCanceled:uv,onFollowRequestAccepted:hv,onFollowRequestDeclined:fv,onFollowInfoUpdated:gv,onLocalUserFollowed:mv,onLocalUserUnfollowed:yv,onLocalFollowerRequested:vv,onLocalFollowRequestAccepted:bv,onLocalFollowRequestDeclined:wv,getFollowers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getFollowers(tmpid: ${i}) > listen`);const a=new Lv(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getFollowers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getFollowings(tmpid: ${i}) > listen`);const a=new Fv(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getFollowings(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getFollowInfo:(e,t)=>Nv(e,t,"userId",pv,[gv],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Rt();return Nv(t,e,"userId",pv,[gv],{forceDispatch:!0})}});function jv(e,t){return e.map((e=>{const n=tt(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=Rt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const $v=e=>{var t;return null!==(t=Object.keys(f).find((t=>e.needApprovalOnPostCreation===f[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===f[t].onlyAdminCanPost)))&&void 0!==t?t:p};function qv({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Bf(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:$v({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Kv=e=>{const t=qv({communities:e.communities}),n=e.users.map(fp),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=jv(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(fp),communities:s,communityUsers:r})},Gv=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(fp);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Wv=e=>{const t=qv({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=jv(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Hv=e=>{const{postSetting:t,storySetting:n}=e,r=Bf(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?f[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Vv=e=>{var t=Bf(e,["searchResult"]);const n=Kv(t);return Object.assign({},n)},Yv=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return jt(n)},cancel:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Ut("local.joinRequest.deleted",[s])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"approved"}),Ut("local.joinRequest.updated",[s])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Ut("local.joinRequest.updated",[s])),r.success})(e)}});class Qv extends Av{async getRequest(e,t){const{limit:n=20,communityId:r}=e,s=Bf(e,["limit","communityId"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},s),{options:i})});return a}}var zv;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(zv||(zv={}));class Jv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===zv.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===zv.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===zv.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Xv=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Zv=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},eb=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class tb extends kv{constructor(e,t){const n=Tv(e),r=["joinRequest","collection",n];super(new Qv(e),n,r,t),this.query=e,this.queryStreamController=new Jv(this.query,this.cacheKey,this.notifyChange.bind(this),Gv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xv,action:zv.OnLocalJoinRequestCreated},{fn:Zv,action:zv.OnLocalJoinRequestUpdated},{fn:eb,action:zv.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=this.applyFilter(s.data.map((e=>tt(["joinRequest","get",e]))).filter(Pv).map((({data:e})=>e)).map(Yv));(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}const nb=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),rb=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(nb),users:e.users.map(fp)}),sb=async e=>{const t=Ye();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=rb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:s}},ib=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp),invitations:e.invitations.map(nb)}),ab=e=>Object.assign(Object.assign({},e),{get user(){const t=tt(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get createdBy(){const t=tt(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get target(){if("community"===e.targetType){const t=tt(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(st(["invitation","get",e],{status:"approved"}),Ut("local.invitation.updated",[s])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(st(["invitation","get",e],{status:"rejected"}),Ut("local.invitation.updated",[s])),r.success})(e._id)}}),ob=async e=>{const t=Ye();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),r=ib(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.invitations[0]?ab(r.invitations[0]):void 0,cachedAt:s}};var lb;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(lb||(lb={}));class cb extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class db extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.invitations.map(Je("invitation"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Je("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===lb.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===lb.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===lb.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ub=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},hb=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},fb=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class pb extends kv{constructor(e,t){const n=Tv(e),r=["invitation","collection",n];super(new cb(e),n,r,t),this.query=e,this.queryStreamController=new db(this.query,this.cacheKey,this.notifyChange.bind(this),rb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ub,action:lb.OnLocalInvitationCreated},{fn:hb,action:lb.OnLocalInvitationUpdated},{fn:fb,action:lb.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["invitation","get",e]))).filter(Pv).map((({data:e})=>ab(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}const gb=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),mb=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=tt(["category","get",e]);if(null==t?void 0:t.data)return gb(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await sb({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getInvitations: (tmpid: ${i}) > listen`);const a=new pb(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getInvitations (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await ob({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ye();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),s=Gv(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const a="approved"===s.joinRequests[0].status?"success":"pending";if("success"===a&&n.cache){const n=null===(t=tt(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});st(["community","get",e],t)}}return Ut("v4.local.community.joined",s.joinRequests),"success"===a?{status:a}:{status:a,request:Yv(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getJoinRequests: (tmpid: ${i}) > listen`);const a=new tb(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getJoinRequests (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ye();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=Gv(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.joinRequests[0]?Yv(r.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class yb{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=tt(["story-expire",this._targetId]),this.cacheStoreSeenTime=tt(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=tt(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return tt(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=et(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:s}}=t;return n!==this._targetId||s||(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const vb=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:s,targetUpdatedAt:i,localFilter:a}=e,o=new yb(n,r,s);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:i,hasUnseen:o.getHasUnseenFlag(),syncingStoriesCount:o.syncingStoriesCount,failedStoriesCount:o.failedStoriesCount,localFilter:a,localLastExpires:o.localLastStoryExpires,localLastSeen:o.localLastStorySeenExpiresAt,localSortingDate:o.getLocalLastSortingDate()}},bb=async e=>{const t=Ye();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,s=Bf(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await Rp(n.data),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{channels:i}=r;return{data:Rg(i[0]),cachedAt:s}},wb=async e=>{const t=Ye();let n;t.log("channel/getChannel",e),Xf("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Rp(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&kp(r)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("channel",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:r}};wb.locally=e=>{var t;const n=Ye();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const Sb=Symbol("getWatcherUrls"),Eb=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=tt(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=tt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=tt(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Eb(n)})).filter(Pv):[]},getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return _g(Rg(n));const{data:r}=await wb(e.channelId);return _g(Rg(r))}if(e.userId===n.userId){const{data:t}=await bb({type:"live",postId:e.postId,videoStreamId:e.streamId});return rt(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Sb](){return e.watcherUrl}}),Ib=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=tt(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)},get childrenComment(){return e.children.map((e=>{const t=tt(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Pv).map((e=>Ib(e)))}});function Tb(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Ab(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Cb{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let _b=null;const Rb=()=>(_b||(_b=new Cb),_b),Ob={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},kb="-----BEGIN PRIVATE KEY-----";function Pb(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=String.fromCharCode(e)})),ye(n)}function Db(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Lb(e){let t=e;t=e.includes(kb)?e.substring(kb.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const n=Te(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);const s=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),r=Db(e.length),s=n.length+t.length+1+r.length+e.length,i=Db(s),a=new Uint8Array(1+i.length+s);let o=0;return a[o]=48,o+=1,a.set(i,o),o+=i.length,a.set(n,o),o+=n.length,a.set(t,o),o+=t.length,a[o]=4,o+=1,a.set(r,o),o+=r.length,a.set(e,o),a}(r);return await crypto.subtle.importKey("pkcs8",s.buffer,Ob,!1,["sign"])}async function xb({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=Rf.v4(),s=`nonceStr=${r}×tamp=${e}&data=${n}==`,i=(new TextEncoder).encode(s),a=await Lb("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----");return{signature:Pb(await crypto.subtle.sign(Ob,a,i)),nonceStr:r}}async function Mb(){const e=Rb(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),r=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),s=await xb({timestamp:n,rooms:r});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const i={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:r},a=Ye();return await a.http.post("/api/v3/user-event/room",i),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const r=n.retryCount+1;r>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:r})}})),!1}}const Ub=["live","recorded"];class Fb{constructor(e){this.storage=Rb(),this.client=Ye(),this.room=e}async createWatchSession(e){if(!Ub.includes(this.room.status))throw new Ge("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+Rf.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),r=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(r,1e3)};r()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await Mb(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const Nb=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=tt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=tt(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?jt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=tt(["room","get",e]))||void 0===t?void 0:t.data;if(n)return Nb(n)})).filter(Pv):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?jt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=tt(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return _g(Rg(n));const{data:r}=await wb(e.liveChannelId);return _g(Rg(r))}if(e.createdBy===n.userId){const{data:t}=await bb({type:"live",postId:e.referenceId,roomId:e.roomId});return rt(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>sb({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await ob({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new Fb(this)}}),Bb=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=tt(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),jb=e=>{const t=gm();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,r,s)=>{t.markProductAsClicked(e,n,r,s)},markAsViewed:(n,r,s)=>{t.markProductAsViewed(e,n,r,s)}}})},$b=e=>{var t,n,r;if(!e)return e;if("video"===e.type){const r=null===(n=null===(t=e.attributes)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.video;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==r?void 0:r.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==r?void 0:r.height)&&void 0!==e?e:0},getRotation:()=>{var e;return null!==(e=null==r?void 0:r.rotation)&&void 0!==e?e:0}})}if("image"===e.type){const t=null===(r=e.attributes)||void 0===r?void 0:r.metadata;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==t?void 0:t.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==t?void 0:t.height)&&void 0!==e?e:0}})}return e},qb=e=>zf(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=tt(["post","get",e]))||void 0===t?void 0:t.data})).filter(Pv).map(qb),analytics:{markAsViewed:()=>{gm().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{gm().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=tt(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?jb(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=tt(["comment","get",e]))||void 0===t?void 0:t.data;return n?Ib(n):null})).filter(Boolean)||[]},get creator(){if(!e.postedUserId)return;const t=tt(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?jt(t.data):void 0},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?mb(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return $b(null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,r;const s=Tb(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return $b(null===(r=tt(["file","get",s]))||void 0===r?void 0:r.data)},getVideoThumbnailInfo(){var t,n;const r=Tb(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(r)return $b(null===(n=tt(["file","get",r]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!Ab(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const r=null===(n=tt(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return r?Eb(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const r=null===(n=tt(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return r?Bb(r):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const r=null===(n=tt(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return r?Nb(r):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const r=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=r(e.data),i=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=tt(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>r(null==e?void 0:e.data))).find(Boolean);if(!i)return;const a=null===(n=tt(["event","get",i]))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign({},a),{get creator(){const e=tt(["user","get",a.userId]);if(null==e?void 0:e.data)return jt(e.data)},get targetCommunity(){var e;if(!a.originId)return;const t=null===(e=tt(["community","get",a.originId]))||void 0===e?void 0:e.data;return t?mb(t):void 0},get coverImage(){var e;if(a.coverImageFileId)return null===(e=tt(["file","get",a.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),Kb=(e,t)=>{"message"===e?Ut("local.message.updated",{messages:[t]}):"post"===e?Ut("post.updated",{posts:[t]}):"comment"===e?Ut("comment.updated",{comments:[t]}):"story"===e&&Ut("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Gb=async(e,t,n,r)=>{var s,i,a;const o=Ye();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:l}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(o.cache){const r=tt([e,"get",t]);if(!r||(null===(s=r.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(i=r.data.myReactions)&&void 0!==i?i:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(a=r.data.reactions[n])&&void 0!==a?a:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.addReaction",{comment:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("post"===e)return Ut("local.post.addReaction",{post:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("story"===e)return Ut("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("message"===e)return st(["message","get",t],c),Ut("local.message.updated",{messages:[c]}),!0}return!0};Gb.optimistically=(e,t,n)=>{var r,s,i,a,o;const l=Ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=tt([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(i=c.data.reactions[n])&&void 0!==i?i:0)+1})});return st([e,"get",t],d,{cachedAt:z}),Kb(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==o&&o};const Wb=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=tt(["messageMarker","get",Je("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Hb=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var s,i;const a=Ye();if(a.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await a.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(a.cache){const r=tt([e,"get",t]);if(!r)return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(s=r.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(i=r.data.reactions[n])&&void 0!==i?i:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.removeReaction",{comment:l,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("post"===e)return Ut("local.post.removeReaction",{post:l,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("story"===e)return Ut("local.story.reactionRemoved",{story:l,reactor:{userId:a.userId,reactionName:n,reactionId:o.removedId}}),!0;if("message"===e)return st(["message","get",t],l),Ut("local.message.updated",{messages:[l]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Vb=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp)}),Yb=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=tt(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)}}),Qb=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp)}),zb=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Qb(e);if(n.cache){Ff(r);const e=tt(["event","get",r.events[0].eventId]);t(e.data)}else t(r.events[0])}))},Jb=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Vb(e);if(n.cache){Ff(r);const e=tt(["eventResponse","get",r.eventResponses[0].userId]);t(e.data)}else t(r.eventResponses[0])}))},Xb=async e=>{const t=Ye();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),r=Vb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:Yb(r.eventResponses[0]),cachedAt:s}};var Zb;Xb.locally=e=>{const t=Ye();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=tt(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Zb||(Zb={}));class ew extends Av{async getRequest(e,t){const{limit:n=W,eventId:r}=e,s=Bf(e,["limit","eventId"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v1/events/${r}/rsvp`,{params:Object.assign(Object.assign({},s),{options:i})});return a}}class tw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.eventResponses.map(Je("eventResponse"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Je("eventResponse"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Zb.OnRSVPCreated&&(r.data=[...new Set([t.userId,...r.data])]),e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const nw=e=>zb("event.created",e),rw=e=>zb("event.updated",e),sw=e=>zb("event.deleted",e),iw=e=>zb("local.event.created",e),aw=e=>zb("local.event.updated",e),ow=e=>zb("local.event.deleted",e),lw=e=>Jb("event.rsvp.created",e),cw=e=>Jb("event.rsvp.updated",e),dw=e=>Jb("local.rsvp.created",e),uw=e=>Jb("local.rsvp.updated",e);class hw extends kv{constructor(e,t){const n=Tv(e),r=["eventResponse","collection",n];super(new ew(e),n,r,t),this.query=e,this.queryStreamController=new tw(this.query,this.cacheKey,this.notifyChange.bind(this),Vb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lw,action:Zb.OnRSVPCreated},{fn:cw,action:Zb.OnRSVPUpdated},{fn:dw,action:Zb.OnRSVPCreated},{fn:uw,action:Zb.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=s.data.map((e=>tt(["eventResponse","get",e]))).filter(Pv).map((({data:e})=>Yb(e)));(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const fw=(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getRSVPs: (tmpid: ${i}) > listen`);const a=new hw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getRSVPs (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},pw=e=>Object.assign(Object.assign({},e),{get creator(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)},get targetCommunity(){if(!e.originId)return;const t=tt(["community","get",e.originId]);return(null==t?void 0:t.data)?mb(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=tt(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=tt(["post","get",e.postId]);return(null==t?void 0:t.data)?qb(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=et(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?Nb(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/createRSVP",e,t);const{data:r}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Ut("local.rsvp.created",r);const s=Vb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:Yb(s.eventResponses[0]),cachedAt:i}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/updateRSVP",e,t);const{data:r}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Ut("local.rsvp.updated",r);const s=Vb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:Yb(s.eventResponses[0]),cachedAt:i}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Xb(e.eventId);return t},getRSVPs:(t,n)=>fw(Object.assign({eventId:e.eventId},t),n)}),gw={file:$b,ad:e=>{const t=gm(),{image9_16:n,image1_1:r}=e,s=Bf(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=tt(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const s=null===(n=tt(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:s})},get image1_1(){const e=tt(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=tt(["file","get",n]);if(e)return e.data||void 0}})},comment:Ib,post:qb,user:jt,category:gb,stream:Eb,story:e=>{const t=gm(),n=tt(["storyTarget","get",e.targetId]),r=tt(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const r=tt(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:s}=r;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=tt(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:s}=r;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==r?void 0:r.data))return mb(r.data)},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=tt(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=tt(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return vb(n.data)},get isSeen(){const t=tt(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,i=new Date(e.expiresAt).getTime();return Math.max(r,s)>=i}})},storyTarget:vb,message:e=>{const t=Bf(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Wb(e).readCount},get deliveredCount(){return Wb(e).deliveredCount},get creator(){var t;return null===(t=tt(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>Sy(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Gb("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Hb(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return jt(n)}}),channel:_g,pinnedPost:e=>{var t;const n=tt(["post","get",e.referenceId]),r=null===(t=et(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return qb(n.data)},get target(){const e=tt(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map((e=>jt(e))),get event(){const t=tt(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:mb,invitation:ab,joinRequest:Yv,channelMember:Mp,room:Nb,event:pw,eventResponse:Yb,product:jb,poll:Bb},mw=async e=>{const t=Ye();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=Xg(r),i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("user.fetched",r),{data:s.users.map((e=>gw.user(e))),cachedAt:i}};mw.locally=e=>{var t;const n=Ye();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>tt(["user","get",e]))).filter(Boolean),s=r.map((({data:e})=>gw.user(e))),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const yw=async(e,t)=>{var n;const r=Ye();r.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:i}=await r.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),a=Xg(i);return r.cache&&Ff(a),Ut("user.flagged",i),null!==(n=a.users.find((t=>t.userId===e)))&&void 0!==n?n:a.users[0]},vw=e=>am("user.updated",e),bw=e=>am("user.flagged",e),ww=e=>am("user.unflagged",e),Sw=e=>am("user.flagCleared",e),Ew=e=>am("user.fetched",e),Iw=async e=>{const t=Ye();t.log("user/getUser",e),Xf("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),s=Xg(n);return t.cache&&Ff(s,{cachedAt:r}),Ut("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ie(null==t?void 0:t.code)&&Nf("user",e),t}};Iw.locally=e=>{const t=Ye();if(t.log("user/getUser.locally",e),!t.cache)return;const n=tt(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Tw extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Aw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Cw;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Cw||(Cw={}));class _w extends kv{constructor(e,t){const n=Tv(e),r=["user","collection",n];super(new Tw(e),n,r,t),this.query=e,this.queryStreamController=new Aw(this.query,this.cacheKey,this.notifyChange.bind(this),Xg),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:vw,action:Cw.OnUserUpdated},{fn:bw,action:Cw.OnUserFlagged},{fn:ww,action:Cw.OnUserUnflagged},{fn:Sw,action:Cw.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Rw extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}var Ow;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Ow||(Ow={}));class kw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return t=>{var n,r;const s=e===Iv.OnFollowed||e===Ow.OnUnblocked,i=e===Ow.OnBlocked;if(s||i){const e=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[],a=i?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));nt(this.cacheKey,Object.assign(Object.assign({},e),{data:a}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Pw=(e,t,n)=>r=>e((e=>{var s;if(!e)return e;const i=[n,"get",`${e[t]}`],a=null===(s=tt(i))||void 0===s?void 0:s.data;return a?r(a):void 0}));class Dw extends kv{constructor(e,t){const n=Tv(e),r=["blockedUsers","collection",n];super(new Rw(e),n,r,t),this.query=e,this.queryStreamController=new kw(this.query,this.cacheKey,this.notifyChange.bind(this),Mm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:Pw(mv,"to","user"),action:Iv.OnFollowed},{fn:Pw(ov,"to","user"),action:Iv.OnFollowed},{fn:e=>Vm((t=>{var n;if(t.from!==Ye().userId)return;const r=null===(n=tt(["user","get",t.to]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnBlocked},{fn:e=>Ym((t=>{var n;if(t.from!==Ye().userId)return;const r=null===(n=tt(["user","get",t.to]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Lw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return t=>{var n,r;if(t&&(e===Ow.OnBlocked||e===Ow.OnUnblocked)){const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],a=e===Ow.OnBlocked?[...new Set([...i,t.userId])]:i.filter((e=>e!==t.userId));nt(this.cacheKey,Object.assign(Object.assign({},s),{data:a}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xw extends Av{async getRequest(e,t){const{limit:n=H}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Mw extends kv{constructor(e){const t=`blocking-users-${Ye().userId}`,n={},r=["blockingUsers","collection",t];super(new xw(n),t,r,e),this.queryStreamController=new Lw(n,this.cacheKey,this.notifyChange.bind(this),Bm),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:e=>Vm((t=>{var n;if(t.to!==Ye().userId)return;const r=null===(n=tt(["user","get",t.from]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnBlocked},{fn:e=>Ym((t=>{var n;if(t.to!==Ye().userId)return;const r=null===(n=tt(["user","get",t.from]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Uw extends Av{async getRequest(e,t){const{limit:n=W,displayName:r}=e,s=Bf(e,["limit","displayName"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:r,options:i,isDeleted:!1})});return a}}class Fw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Nw extends kv{constructor(e,t){var n;const r=Tv(e),s=["user","collection",r];super(new Uw(e),r,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Fw(this.query,this.cacheKey,this.notifyChange.bind(this),Xg),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:vw,action:Cw.OnUserUpdated},{fn:bw,action:Cw.OnUserFlagged},{fn:ww,action:Cw.OnUserUnflagged},{fn:Sw,action:Cw.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Bw=async({viewId:e,viewedType:t,limit:n,token:r})=>{const s=Ye(),i={};r?i.token=r:i.limit=n;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,o=await s.http.get(a,{params:i});return Ff(o.data),o.data};var jw;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(jw||(jw={}));var $w=Object.freeze({__proto__:null,Relationship:Bv,getUserByIds:mw,updateUser:async(e,t)=>{const n=Ye();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=Xg(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),Ut("user.updated",r),{data:s.users.find((t=>t.userId===e)),cachedAt:i}},flagUser:yw,unflagUser:async e=>{const t=Ye();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=Xg(n);return t.cache&&Ff(r),Ut("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ye().log("user/getAllBlockedUsers");const e=Nm();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ye().log("user/getAllBlockingUsers");const e=qm();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:vw,onUserDeleted:om,onUserFlagged:bw,onUserUnflagged:ww,onUserFlagCleared:Sw,getUser:(e,t)=>Nv(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?gw.user(e.data):e.data}))),"userId",Iw,[Ew,vw,om,bw,ww,Sw]),getUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveUsers(tmpid: ${i}) > listen`);const a=new _w(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getBlockedUsers(tmpid: ${i}) > listen`);const a=new Dw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getBlockedUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e())),it(l)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getBlockingUsers(tmpid: ${r}) > listen`);const s=new Mw(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getBlockingUsers(tmpid: ${r}) > dispose`),i.forEach((e=>e())),it(a)}},searchUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveSearchUsers(tmpid: ${i}) > listen`);const a=new Nw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveSearchUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveSearchUsers(tmpid: ${i}) > listen`);const a=new Nw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveSearchUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:s}=Ye(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(Y);const a=Date.now();r(`getReachUsers(tmpid: ${a}) > listen`);const{limit:o,viewId:l,viewedType:c}=e;return n=(e=!1)=>{var r,s,a;const d=null===(r=tt(i))||void 0===r?void 0:r.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=Be(Bw,{viewId:l,viewedType:c,limit:o||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});$e(h,(e=>{var r,s,a,o,l;let c=null!==(a=null===(s=null===(r=tt(i))||void 0===r?void 0:r.data)||void 0===s?void 0:s.data)&&void 0!==a?a:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};nt(i,d),(e=>{var r,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>tt(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:i,hasNextPage:!!(null===(s=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),je(V,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${a}) > dispose`),it(i)}},get AmityUserSearchMatchType(){return jw}});const qw=async e=>{const t=Ye();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Ff({files:[n]},{cachedAt:r}),{data:$b(n),cachedAt:r}};qw.locally=e=>{const t=Ye();if(t.log("file/getFile.locally",e),!t.cache)return;const n=tt(["file","get",e]);return n?{data:$b(n.data),cachedAt:n.cachedAt}:void 0};const Kw=async(e,t,n)=>{const r=Ye();r.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o.map((e=>$b(e))),cachedAt:l}},Gw=async(e,t,n)=>{const r=Ye();r.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const i=By().getFileAccessType();e.append("accessType",i);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/images",e,{headers:a,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o.map((e=>$b(e))),cachedAt:l}};var Ww=Object.freeze({__proto__:null,getFile:qw,uploadFile:async(e,t)=>{const n=Ye();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=By().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.upload.post("/api/v4/files",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ff({files:a},{cachedAt:o}),{data:a,cachedAt:o}},deleteFile:async e=>{const t=Ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),it(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Kw,uploadImage:Gw,updateAltText:async(e,t)=>{const n=Ye();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Ff({files:[r]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const r=Ye();r.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/clips",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o,cachedAt:l}},uploadAudio:async(e,t)=>{const n=Ye();n.log("file/uploadAudio",e);const r=e.getAll("file");if(0===r.length)throw new Error("The formData object must have a `file` key with audio file.");const s=r[0],i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s.name);const{data:a}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ff({files:a},{cachedAt:o}),{data:a,cachedAt:o}}});const Hw=async e=>{const t=Ye();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:s,displayName:i,sortBy:a}=n,o=Bf(n,["limit","queryToken","displayName","sortBy"]),l=s?{token:s}:r?{limit:r}:void 0,{data:c}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},o),{keyword:i,sortBy:a,options:l})}),{paging:d}=c,u=Bf(c,["paging"]),{roles:h}=u,f=t.cache&&Date.now();t.cache&&Ff(u,{cachedAt:f});const p=Le(d.next);return{data:h,cachedAt:f,prevPage:Le(d.previous),nextPage:p,paging:d}};Hw.locally=e=>{Ye().log("role/queryRoles.locally",e)};const Vw=async e=>{const t=Ye();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Ff({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Vw.locally=e=>{const t=Ye();if(t.log("role/getRole.locally",e),!t.cache)return;const n=tt(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Yw=async(e,t=!1)=>{const n=Ye();let r;n.log("message/getMessage",e),Xf("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await dp(t)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("message",e),t}const s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{messages:i}=r;return Ut("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Yw.locally=e=>{const t=Ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=tt(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Qw{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class zw{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Jw{constructor(e,t){this.postId=e,this.commentId=t}}class Xw{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Zw{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,Zw.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Qw?n=this.processResetTaskInternal(e):e instanceof zw?n=this.processCreateTaskInternal(e):e instanceof Jw&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Zw.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Xw(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.createdCommentIds.has(e.commentId)&&(!(e.createdAt<=t.latestCommentCreatedAt)&&(t.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}computeCommentCount(e){const t=this.commentChangeTracker.get(e);if(!t)return 0;const n=t.serverCommentCount+t.createdCommentIds.size-t.deletedCommentIds.size;return Math.max(0,n)}static publishUpdate(e,t){var n;const r=["post","get",e];rt(r,{localCommentCount:t});const s=null===(n=tt(r))||void 0===n?void 0:n.data;s&&Ut("local.post.updated",{posts:[s]})}}let eS;Zw.BATCH_SIZE=50;var tS=()=>(eS||(eS=new Zw),eS);const nS=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,s=Bf(e,["posts","postChildren","videoStreamings"]),i=qv({communities:s.communities}),a=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),o=jv(i,a);let l=[];const c=t.map((t=>{var n,i,a,o;const c=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,d=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,f;d.length>0&&Ab(d[0])&&(u=r,h=null===(i=d[0].data)||void 0===i?void 0:i.streamId,f=t.postId,l=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:f,postId:f}):e)):u);const p=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),g=0===p.length?(new Date).toISOString():p.map((e=>e.createdAt)).sort().at(-1);return tS().queueCommentChangeTask(new Qw(t.postId,g,null!==(a=t.commentsCount)&&void 0!==a?a:0)),Object.assign(Object.assign({},t),{childPosts:d,feedType:c,localCommentCount:null!==(o=t.localCommentCount)&&void 0!==o?o:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:l,posts:c,communities:o,communityUsers:a})},rS=e=>{var{searchResult:t,polls:n}=e,r=Bf(e,["searchResult","polls"]);const s=nS(r);return Object.assign(Object.assign({},s),{polls:n})},sS=async e=>{const t=Ye();let n;t.log("post/getPost",e),Xf("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("post",e),t}const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:i.find((t=>t.postId===e)),cachedAt:s}};sS.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=tt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const iS=async e=>{const t=Ye();let n;t.log("comment/getComment",e),Xf("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{comments:s}=n;return{data:gw.comment(s.find((t=>t.commentId===e))),cachedAt:r}};iS.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=tt(["comment","get",e]);return n?{data:gw.comment(n.data),cachedAt:n.cachedAt}:void 0};const aS=(e,t)=>{var n,r;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else if("comment"===t)i="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");i="story",s=e.stories[0].referenceId}return(null===(r=null===(n=tt([i,"get",s]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},oS=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},lS=(e,t,n,r=[])=>{const s=e.split(".")[1];let i=r;if(Ye().userId===t)if(["addReaction","reactionAdded"].includes(s))i.includes(n)||i.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);i=i.filter((e=>e!==n))}return i},cS=(e,t)=>{const n=e.split(".")[0],r=aS(t,n),s=lS(e,t.reactor.userId,t.reactor.reactionName,r);return oS(t,`${n}s`,s)},dS=(e,t)=>{var n,r;const s=e.split(".")[0];let i=aS(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(i=lS(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,i));const a=oS(t,"stories",i);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return a;const o=jv(t.communities,t.communityUsers);return Object.assign(Object.assign({},a),{communities:o})},uS=async(e,t,n)=>{var r,s,i;const a=Ye();if(a.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await a.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(a.cache){const l=tt([e,"get",t]);if(!l||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const c=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(s=l.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(i=l.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.addReaction",{comment:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0;if("post"===e)return Ut("local.post.addReaction",{post:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0;if("story"===e)return Ut("local.story.reactionAdded",{story:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0}return!0};uS.optimistically=(e,t,n)=>{var r,s,i,a,o;const l=Ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=tt([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(i=c.data.reactions[n])&&void 0!==i?i:0)+1})});return st([e,"get",t],d,{cachedAt:z}),Kb(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==o&&o};const hS=async(e,t,n)=>{var r,s;const i=Ye();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:a}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(i.cache){const o=tt([e,"get",t]);if(!o)return!0;const l=Object.assign(Object.assign({},o.data),{reactionsCount:Math.max(0,o.data.reactionsCount-1),myReactions:(null!==(r=o.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},o.data.reactions),{[n]:Math.max(0,(null!==(s=o.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.removeReaction",{comment:l,reactor:{reactionId:a.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Ut("local.post.removeReaction",{post:l,reactor:{reactionId:a.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Ut("local.story.reactionRemoved",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:a.removedId}}),!0}return!0};hS.optimistically=(e,t,n)=>{var r,s,i,a;const o=Ye();if(o.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!o.cache)return;const l=tt([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const c=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(s=l.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(i=l.data.reactions[n])&&void 0!==i?i:0)-1)})});return st([e,"get",t],c,{cachedAt:z}),Kb(e,c),!(null===(a=null==c?void 0:c.myReactions)||void 0===a?void 0:a.includes(n))};const fS=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=tt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;nt(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>rt(["post","get",e],{isDeleted:!0})))},pS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s;if(n.cache){const i=nS(r),{communities:a}=i;if(Ff(i,void 0,!1),(null==a?void 0:a[0])&&!["post.updated"].includes(e)&&Ut("community.updated",{communities:a,categories:[],communityUsers:i.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=r.posts[0];fS(r);try{Xf("post",e)}catch(e){return}return s!==n.userId&&it(["post","get",e]),t(r.posts[0])}const o=tt(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=et(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===o.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=tt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&nt(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(o.data)}else t(r.posts[0])}))},gS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{if(n.cache){const{communities:n}=r;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Ut("community.updated",{communities:n,categories:[],communityUsers:r.communityUsers,feeds:[],files:[],users:[]});const s=tt(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&fS(r),t(s.data)}else t(r.posts[0])}))},mS=e=>pS("post.created",e),yS=e=>pS("post.updated",e),vS=e=>pS("post.deleted",e),bS=e=>pS("post.approved",e),wS=e=>pS("post.declined",e),SS=e=>pS("post.flagged",e),ES=e=>pS("post.unflagged",e),IS=e=>{const t=Ye();return Mt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Bf(cS("post.addReaction",n),["reactor"]);Ff(t);const r=tt(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},TS=e=>{const t=Ye();return Mt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Bf(cS("post.removeReaction",n),["reactor"]);Ff(t);const r=tt(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},AS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=aS(e,"comment");return oS(e,"comments",t)})(r):r;Ff(n,void 0,!1);const{comments:i}=n;if(i.length>0){const n=tt(["comment","get",i[0].commentId]);if(["comment.created"].includes(e)&&i[0].parentId){const e=tt(["comment","get",i[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(i[0].commentId)||nt(["comment","get",i[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,i[0].commentId])]})))}if(["comment.deleted"].includes(e)){if(i[0].parentId){const e=tt(["comment","get",i[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(i[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==i[0].commentId))])]});nt(["comment","get",i[0].parentId],t)}}const e=null===(s=et(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}t(gw.comment(n.data))}}else t(gw.comment(r.comments[0]))}))},CS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s,i,a,o,l;if(n.cache){const n=r;Ff(n);const{comments:c}=n;if(c.length>0){const n=tt(["comment","get",c[0].commentId]);if(["local.comment.created"].includes(e)){if(c[0].parentId){const e=tt(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,c[0].commentId])]});nt(["comment","get",c[0].parentId],t),setTimeout((()=>{Ut("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(s=tt(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(i=c[0])||void 0===i?void 0:i.commentId]});nt(e,n)}}const e=null===(a=et(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(c[0].parentId){const e=tt(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==c[0].commentId))])]});nt(["comment","get",c[0].parentId],t),setTimeout((()=>{Ut("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(o=tt(e))||void 0===o?void 0:o.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=c[0])||void 0===t?void 0:t.commentId)}))});nt(e,n)}}const e=null===(l=et(["comment","query"]))||void 0===l?void 0:l.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}t(gw.comment(n.data))}}else t(gw.comment(r.comments[0]))}))},_S=e=>AS("comment.created",e),RS=e=>AS("comment.updated",e),OS=e=>AS("comment.deleted",e),kS=e=>AS("comment.flagged",e),PS=e=>AS("comment.unflagged",e),DS=e=>{const t=Ye();return Mt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Bf(cS("comment.addReaction",n),["reactor"]);Ff(t);const r=tt(["comment","get",n.comments[0].commentId]);e(gw.comment(r.data))}else e(gw.comment(n.comments[0]))}))},LS=e=>{const t=Ye();return Mt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Bf(cS("comment.removeReaction",n),["reactor"]);Ff(t);const r=tt(["comment","get",n.comments[0].commentId]);e(gw.comment(r.data))}else e(gw.comment(n.comments[0]))}))},xS=(e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Mt(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),Ff({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},MS=(e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Mt(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class US extends Av{async getRequest(e,t){const{limit:n=W,referenceType:r}=e,s=Bf(e,["limit","referenceType"]),i=t?{token:t}:{limit:n};Ye().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:a}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:i})});return a}}class FS extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Ye(),s=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=Bf(n,["reactions"]);Ff(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var r,s,i,a;const o=null!==(s=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==s?s:[];if(n)nt(this.cacheKey,{data:o.map(Je("reactor"))});else{const e=null===(i=tt(this.cacheKey))||void 0===i?void 0:i.data,t=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Je("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class NS extends kv{constructor(e,t){const n=Tv(e),r=["reaction","collection",n];super(new US(e),n,r,t),this.query=e,this.queryStreamController=new FS(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>xS(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>MS(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e)return Mt(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(r,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Mt(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e)return Mt(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),Ff({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(r,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Mt(r,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["reactor","get",e]))).filter(Boolean).map((({data:e})=>gw.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var BS=Object.freeze({__proto__:null,addReaction:uS,removeReaction:hS,onReactionAdded:(e,t,n)=>{const r=r=>{Je(e)(r)===t&&n(r)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await dp(e),s=tt(["message","get",n.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ff(n),i&&r(n.messages[0])};return Mt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?IS(r):DS(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{Je(e)(r)===t&&n(r)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await dp(e),s=tt(["message","get",n.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ff(n),i&&r(n.messages[0])};return Mt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?TS(r):LS(r)},onReactorAdded:xS,onReactorRemoved:MS,getReactions:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getReactions(tmpid: ${i}) > listen`);const a=new NS(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getReactions(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});function jS(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const $S=async()=>{var e;const t=Ye();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),r=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(it(["archivedChannel","get"]),r.forEach((e=>{e.channelId&&nt(["archivedChannel","get",e.channelId],e)}))),r.map((e=>e.channelId)).filter((e=>!!e))},qS=e=>{const t=Ye(),n=[Mt(t,"onMessageUpdated","message.updated",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])})),Mt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},KS=e=>{const t=Ye(),n=[Mt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])})),Mt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},GS=e=>{const t=Ye(),n=[Mt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await mp(t);Ff(n),e(n.messageFeeds[0])})),Mt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function WS(e,t){nt(["channel","get",e.channelId],zf(e,t))}const HS=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},VS=async(e,t=!1)=>{const n=Ye(),r=await yp(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Ze(r.data.updatedAt)});return t?setTimeout((()=>{Nf("subChannel",e)}),0):st(["subChannel","get",e],s),Ut("local.message-feed.deleted",{messageFeeds:[s]}),s},YS=e=>Mt(Ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),QS=()=>`LOCAL_${Of()}`;let zS;const JS=async(e,t)=>{const n=Ye();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,up(t)),s=await dp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{messages:a}=s;return Ut("local.message.updated",{messages:a}),{data:gw.message(a.find((t=>t.messageId===e))),cachedAt:i}};JS.optimistically=(e,t)=>{const n=Ye();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=tt(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return st(["message","get",e],s,{cachedAt:-1}),Ut("local.message.updated",{messages:[s]}),{data:gw.message(s),cachedAt:-1}};const XS=async(e,t)=>{const n=Ye();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,up(t)),s=await dp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{messages:a}=s;return Ut("local.message.updated",{messages:a}),{data:gw.message(a.find((t=>t.messageId===e))),cachedAt:i}};XS.optimistically=(e,t)=>{const n=Ye();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=tt(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return st(["message","get",e],s,{cachedAt:-1}),Ut("local.message.updated",{messages:[s]}),{data:gw.message(s),cachedAt:-1}};const ZS=async e=>{var t;const n=Ye();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=tt(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return Ut("local.message.deleted",{messages:[r]}),gw.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await dp(r);return Ut("local.message.deleted",{messages:[s.messages[0]]}),gw.message(s.messages[0])};ZS.optimistically=e=>{Ye().log("message/deleteMessage.optimistically",e);const t=tt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return st(["message","get",e],n,{cachedAt:-1}),Ut("local.message.deleted",{messages:[n]}),{data:gw.message(n),cachedAt:-1}};const eE=async e=>{const t=Ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Yw(e);return Ut("local.message.deleted",{messages:[n.data]}),gw.message(n.data)};eE.optimistically=e=>{Ye().log("message/softDeleteMessage.optimistically",e);const t=tt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return st(["message","get",e],n,{cachedAt:-1}),Ut("local.message.deleted",{messages:[n]}),{data:gw.message(n),cachedAt:-1}};const tE=async e=>{const t=Ye();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,s=Bf(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:De(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Bf(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},c),{userFeedMarkers:Gf(l)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];nt(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await mw(o));return{data:u,cachedAt:d,prevPage:Le(a.previous),nextPage:Le(a.next)}};tE.locally=e=>{var t;const n=Ye();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,s=Bf(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:o}=null!==(t=tt(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=tt(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:Le(null==a?void 0:a.paging.previous),nextPage:Le(null==a?void 0:a.paging.next)}};const nE=async e=>{const t=Ye();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,s=Bf(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:De(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Bf(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},c),{userFeedMarkers:Gf(l)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];nt(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await mw(o));return{data:u,cachedAt:d,prevPage:Le(a.previous),nextPage:Le(a.next)}};nE.locally=e=>{var t;const n=Ye();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,s=Bf(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:o}=null!==(t=tt(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=tt(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:Le(null==a?void 0:a.paging.previous),nextPage:Le(null==a?void 0:a.paging.next)}};const rE=e=>{const t=Ye();return Mt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},sE=e=>{const t=Ye();return Mt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},iE=e=>{const t=Ye();return Mt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},aE=e=>{const t=Ye();return Mt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await dp(t,"message.reactionAdded");Ff(n),e(n.messages[0])}))},oE=e=>{const t=Ye();return Mt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await dp(t,"message.reactionRemoved");Ff(n),e(n.messages[0])}))},lE=e=>{const t=Ye();return Mt(t,"message/onMessageFetched","local.message.fetched",(t=>{Ff(t),e(t.messages[0])}))},cE=e=>{const t=Ye();return Mt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;rt(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=et(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{rt(e.key,{isDeleted:!0})}))}));const s=null===(n=tt(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class dE extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.messages.map(Je("message")),query:this.query});else{const n=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,i=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...i,...e.messages.map(Je("message"))])]:[...new Set([...e.messages.map(Je("message")),...i])]}))}}reactor(e){return t=>{var n,r,s,i;if("onCreate"===e){const e=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:i}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=i?i:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=i?i:t.messageId])]),nt(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(i=tt(this.cacheKey))||void 0===i?void 0:i.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));nt(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class uE extends Av{async getRequest(e,t){const n=hp(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class hE extends kv{constructor(e,t){const n=Tv(e),r=["message","collection",n];super(new uE(e),n,r,t),this.query=e,this.queryStreamController=new dE(this.query,this.cacheKey,this.notifyChange.bind(this),dp,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ey,action:"onCreate"},{fn:Iy,action:"onCreate"},{fn:KS,action:"onDelete"},{fn:qS,action:"onUpdate"},{fn:rE,action:"onFlagged"},{fn:sE,action:"onUnflagged"},{fn:iE,action:"onFlagCleared"},{fn:aE,action:"onReactionAdded"},{fn:oE,action:"onReactionRemoved"},{fn:Pw(Zy,"contentId","message"),action:"onUpdate"},{fn:Pw(ev,"contentId","message"),action:"onUpdate"},{fn:Pw(cE,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>np(e))).filter(Boolean).map((e=>gw.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=at(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}class fE extends Av{async getRequest(e,t){const{query:n,exactMatch:r,channelId:s,messageFeedId:i,userIds:a,tags:o,types:l,sortBy:c,orderBy:d,limit:u=W}=e,h=t?{token:t}:{limit:u,sortBy:c,orderBy:d},{data:f}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:r,channelId:s,messageFeedId:i,userIds:a,tags:o,types:l,options:h}});return f}}class pE extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await dp(e),r=Ye(),s=r.cache&&Date.now();r.cache&&(Ff(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{nt(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var r,s;if(n)return void nt(this.cacheKey,{data:e.messages.map(Je("message"))});const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[],o=e.messages.map(Je("message"));nt(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...a])]:[...new Set([...a,...o])]}))}}class gE extends kv{constructor(e,t){const n=Tv(e),r=["message","search",n];super(new fE(e),n,r,t),this.queryStreamController=new pE(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>np(e))).filter(Pv).map((e=>gw.message(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var mE=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ye();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Ye();if(!r.cache)return;zS=e.referenceId||QS();const s=Object.assign({messageId:zS,uniqueId:zS},e);r.log("message/createMessage.optimistically",s);const i=tt(["subChannel","get",e.subChannelId]);if(i&&(st(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},i.data),{messageCount:i.data.messageCount+1})),i.data.channelId===i.data.subChannelId)){const e=tt(["channel","get",i.data.channelId]);(null==e?void 0:e.data)&&st(["channel","get",i.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const a=(new Date).toISOString(),o=Object.assign({creatorId:r.userId,creatorPrivateId:Rt()._id,channelSegment:(null!==(n=null==i?void 0:i.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:a,updatedAt:a,syncState:"syncing",isDeleted:!1},s);return nt(["message","get",o.messageId],o,{cachedAt:-5}),Ut("local.message.created",{messages:[o]}),o})(e),r=e.referenceId||zS||QS();zS=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},up(e)),{referenceId:r})),s=await dp(n),{messages:i}=s,a=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:a}),Ut("local.message.created",{messages:[Object.assign(Object.assign({},i[0]),{syncState:"synced"})]}),{data:gw.message(i[0]),cachedAt:a}}catch(e){throw Ut("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:JS,editMessage:XS,deleteMessage:ZS,softDeleteMessage:eE,markAsDelivered:async(e,t)=>{const n=Ye();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:i,userFeedMarkers:a}=r,o=Bf(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=n.cache&&Date.now();return n.cache&&Ff(Object.assign({userMarkers:s,userEntityMarkers:Kf(i),userFeedMarkers:Gf(a)},o),{cachedAt:l}),!0},getReadUsers:tE,getDeliveredUsers:nE,flagMessage:async(t,n)=>{const r=Ye();r.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:a}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,i);if(r.cache){const e=await dp(a);Ff(e)}return Ut("message.flagged",a),!!a},unflagMessage:async e=>{const t=Ye();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await dp(n);Ff(e)}return Ut("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ye();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ey,onMessageCreatedLocal:Iy,onMessageUpdated:qS,onMessageDeleted:KS,onMessageFlagged:rE,onMessageUnflagged:sE,onMessageFlagCleared:iE,onMessageReactionAdded:aE,onMessageReactionRemoved:oE,onMessageFetched:lE,getMessage:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.message(e.data):n}))}),"messageId",Yw,[lE,qS,KS,rE,sE,iE,aE,oE,Pw(Zy,"contentId","message"),Pw(ev,"contentId","message"),Pw(cE,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMessages(tmpid: ${i}) > listen`);const a=new hE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMessages(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const i=new gE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},convertFromRaw:lp,prepareMessagePayload:dp,convertParams:up,convertQueryParams:hp});const yE=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class vE extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Bf(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Bf(e,["limit"])))&&void 0!==n?n:{},{channelId:i,includeDeleted:a}=s,o=Bf(s,["channelId","includeDeleted"]),l=t?{token:t}:{limit:r},{data:c}=await this.http.get(`/api/v5/message-feeds/channel/${i}`,{params:Object.assign(Object.assign({},o),{isDeleted:rp(a),options:l})});return c}}class bE extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),nt(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class wE extends kv{constructor(e,t){const n=Tv(e),r=["subChannel","collection",n];super(new vE(e),n,r,t),this.query=e,this.queryStreamController=new bE(this.query,this.cacheKey,this.notifyChange.bind(this),mp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:YS,action:"onCreate"},{fn:Ty,action:"onCreate"},{fn:Ay,action:"onDelete"},{fn:e=>GS((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ye();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=Vf(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Hf(t.updatedAt)>Hf(e.subChannelUpdatedAt)&&nt(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{this.isRelatedCollection(t.subChannelId)&&(await bp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{this.isRelatedCollection(t.subChannelId)&&(await bp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Jy((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>tt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Pw(zy,"feedId","subChannel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{var n;const r=Ye();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(wp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=Ye(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await yp(t.subChannelId):await wp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw(yE,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yf))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=at(e,"isDeleted",!1)),t.sort(Tt),t}isRelatedCollection(e){var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const SE={},EE=async e=>{const t=await(async e=>{const t=yp.locally(e);if(t)return t.data.channelId;const{data:n}=await yp(e);return n.channelId})(e),n=Vt({channelId:t,subChannelId:e});SE[e]=Zt(n)};var IE=Object.freeze({__proto__:null,getSubChannelByIds:Ug,createSubChannel:async e=>{const t=Ye();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ye();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await mp(r.data),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),Ut("message-feed.updated",r.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:VS,hardDeleteSubChannel:async e=>{Ye().log("channel/hardDeleteSubChannel",e);return await VS(e,!0)},softDeleteSubChannel:async e=>{Ye().log("channel/softDeleteSubChannel",e);return await VS(e,!1)},onSubChannelCreated:Ty,onSubChannelUpdated:GS,onSubChannelDeleted:Ay,getSubChannel:(e,t)=>{const n=Ye();let r;return Nv(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yf(e.data)}),s=Bf(n,["origin"]);return Fp(r,s)?void 0:(r=s,t(n))}),"subChannelId",yp,[YS,t=>GS((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ip(r),r.subChannelId===e&&t(r))})),Ay,Pw(zy,"feedId","subChannel"),t=>Jy((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(r=tt(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&t(s)})),Pw((t=>Ey((async n=>{n.subChannelId===e&&(await bp(n),t(n))}))),"subChannelId","subChannel"),Pw((t=>Iy((async n=>{n.subChannelId===e&&(await bp(n),t(n))}))),"subChannelId","subChannel"),Pw((t=>qS((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(wp(r),t(r))}))),"subChannelId","subChannel"),Pw((t=>KS((async r=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&r.subChannelId===e&&("message-preview-include-deleted"===s&&await wp(r),"message-preview-not-include-deleted"===s&&await yp(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Pw(yE,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:s}=Ye(),i=Date.now();r(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(Y);const a=new wE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getSubChannels(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markReadEngineOnLoginHandler:Mg,startMessageReceiptSync:async e=>(await EE(e),!0),stopMessageReceiptSync:e=>(SE[e]&&SE[e](),!0)});const TE=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},AE=e=>{const t=Ye();return Mt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class CE extends Av{async getRequest(e,t){const{limit:n=W,displayName:r,membership:s}=e,i=Bf(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:r,filter:s,options:a})});return o}}class _E extends Ov{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class RE extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.channels.map(Je("channel"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Je("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof _E)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(Je("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Je("channel")):[Je("channel")(t)];r.data=r.data.filter((t=>!e.includes(t)))}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const OE=e=>{const t=Ye();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){km().resolve(e.channelId,"userMessageFeedMarker")}},kE=e=>{const t=Ye();return Mt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},PE=e=>{const t=Ye();return Mt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class DE extends kv{constructor(e,t){const n=Tv(e),r=["channel","collection",n],s=DE.getPaginationController(e);super(s,n,r,t),this.query=e,this.queryStreamController=new RE(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ye();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(e)}catch(e){console.error("Error while preparing unread count info",e)}return Rp(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;let a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Rg))&&void 0!==s?s:[];this.paginationController instanceof CE&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof CE?()=>this.loadPage({direction:"next"}):void 0,data:a,hasNextPage:this.paginationController instanceof CE&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;switch(n=at(n,"isDeleted",this.query.isDeleted),n=ot(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=ct(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(bt);break;case"lastCreated":n=n.sort(St);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(yt);break;default:n=n.sort(Tt)}return n}shouldAbort(e){var t,n;const r=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new _E(e):new CE(e)}getSubscriptions(){const e=[{fn:Pw((e=>Ey((t=>{var n,r;const s=km();(null===(n=tt(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const i=null===(r=tt(["channel","get",t.channelId]))||void 0===r?void 0:r.data;i?(WS(i,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Yp,action:"onDelete"},{fn:Kp,action:"onUpdate"},{fn:rg,action:"onMute"},{fn:e=>Jp((t=>{OE(t),e(t)})),action:"onJoin"},{fn:e=>eg(((t,n)=>{var r,s;const{userId:i}=Ye();if("member"===this.query.membership&&i===n.userId){const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;nt(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:ag,action:"onMemberAdded"},{fn:cg,action:"onMemberRemoved"},{fn:e=>Eg((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ig((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pw(Qy,"entityId","channel"),action:"onUpdate"},{fn:Pw(HS,"entityId","channel"),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{"no-message-preview"!==await DE.getMessagePreviewSetting()&&(await Ep(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=await DE.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ep(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await wb(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Ay((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Wf(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await wb(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>GS((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;(null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ip(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw(Ty,"channelId","channel"),action:"onUpdate"},{fn:kE,action:"onResolveChannel"},{fn:e=>PE((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=tt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pw(TE,"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Av?[...e,{fn:e=>jp((t=>{OE(t),e(t)})),action:"onCreate"}]:e}}const LE=()=>{var e;const t=Ye();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=et(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class xE extends Av{async getRequest(e,t){var n,r;const s=null!==(n=e.limit)&&void 0!==n?n:W,i=t?Number.parseInt(t,10):0;0===i&&await $S();const a=(null!==(r=et(["archivedChannel","get"]))&&void 0!==r?r:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),o=i*s,l=o+s,c=a.slice(o,l),d=l<a.length;return c.length>0&&await Og(c.map((e=>e.channelId))),{archives:c,paging:{next:d?String(i+1):void 0,previous:void 0}}}}class ME extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var r,s;const i=e.archives.map((e=>e.channelId));if(n)return void nt(this.cacheKey,{data:i,params:{}});const a=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,o=null!==(s=null==a?void 0:a.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},a),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if("onArchived"===e){const e=r.data.filter((e=>!t.includes(e)));r.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(r.data=r.data.filter((e=>!t.includes(e)))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class UE extends kv{constructor(e,t){const n=Tv(e),r=["archivedChannel","collection",n];super(new xE(e),n,r,t),this.queryStreamController=new ME(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>Eg((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Ig((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Kp((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Yp((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Rg))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class FE extends Av{async getRequest(e,t){const{query:n,exactMatch:r,isMemberOnly:s,types:i,tags:a,sortBy:o,orderBy:l,limit:c=H}=e,d=t?{token:t}:{limit:Math.min(100,Math.max(1,c))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:r,isMemberOnly:s,types:i,tags:a,sortBy:o,orderBy:l,options:d}});return u}}class NE extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Rp(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)return void nt(this.cacheKey,{data:e.channels.map(Je("channel"))});const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[],o=e.channels.map(Je("channel"));nt(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...a])]:[...new Set([...a,...o])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const BE=()=>Ye().getMessagePreviewSetting(!1);class jE extends kv{constructor(e,t){const n=Tv(e),r=["channel","search",n];super(new FE(e),n,r,t),this.queryStreamController=new NE(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter(Boolean).map((e=>Rg(e.data))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}shouldAbort(e){var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Pw((e=>Ey((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Yp,action:"onDelete"},{fn:Kp,action:"onUpdate"},{fn:rg,action:"onMute"},{fn:e=>Eg((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ig((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pw(Qy,"entityId","channel"),action:"onUpdate"},{fn:Pw(HS,"entityId","channel"),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{var n;if("no-message-preview"===await BE())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{var n;if("no-message-preview"===await BE())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{"no-message-preview"!==await BE()&&(await Ep(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=await BE();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ep(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await wb(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Ay((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Wf(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await wb(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>GS((async t=>{var n;if("no-message-preview"===await BE())return;(null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ip(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>PE((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=tt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pw(TE,"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class $E extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r}=e,s=Bf(e,["limit","includeDeleted"]),i=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:o}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:a})});return o}}class qE extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Je("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Je("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=Je("channelUsers")({channelId:this.query.channelId,userId:t.userId}),i=this.query.memberships,a=!i||i.includes(t.membership);"none"!==t.membership&&a?r.data.includes(s)||(r.data=[s,...r.data]):r.data=r.data.filter((e=>e!==s)),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class KE extends kv{constructor(e,t){const n=Tv(e),r=["channelUsers","collection",n];super(new $E(e),n,r,t),this.query=e,this.queryStreamController=new qE(this.query,this.cacheKey,this.notifyChange.bind(this),Rp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Jp,action:"onJoin"},{fn:eg,action:"onLeft"},{fn:ag,action:"onMemberAdded"},{fn:cg,action:"onMemberRemoved"},{fn:hg,action:"onChannelMemberBanned"},{fn:gg,action:"onChannelMemberUnbanned"},{fn:vg,action:"onChannelMemberRoleAdded"},{fn:Sg,action:"onChannelMemberRoleRemoved"},{fn:Cg,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{var r,s;const i=Xg(n);if(0===i.users.length)return;const a=i.users[0];Ff(i);const o=Je("channelUsers")({channelId:e,userId:a.userId}),l=null===(r=tt(["channelUsers","get",o]))||void 0===r?void 0:r.data;st(["channelUsers","get",o],Object.assign(Object.assign({},l),{user:a}));const c=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;c&&t(c,l)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(gw.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=lt(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?St:bt),t}}const GE=(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new KE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}};var WE=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Ut("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Rp(r);n.cache&&Ff(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ye();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Ut("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Rp(r);n.cache&&Ff(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=lt(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?St:bt),n},getMembers:GE,searchMembers:(e,t,n)=>GE(e,t)});var HE=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Ye();r.log("channel/addRole",e,t,n);const{data:s}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),i=await Rp(s);r.cache&&Ff(i),Ut("local.channel-moderator.role-added",i);const{channelUsers:a}=i;return!!a.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Ye();r.log("channel/removeRole",e,t,n);const{data:s}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),i=await Rp(s);r.cache&&Ff(i),Ut("local.channel-moderator.role-removed",i);const{channelUsers:a}=i;return!!a.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ye();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Rp(r),{channelUsers:i}=s,a=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:a}),Ut("channel.banned",r),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const n=Ye();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Rp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i}),Ut("channel.unbanned",r);const{channelUsers:a}=s;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:i}},muteMembers:async(e,t,n=-1)=>{var r;const s=Ye();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:i}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:a}=i,o=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return Ut("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:o,actor:null!==(r=s.userId)&&void 0!==r?r:""}),a},unmuteMembers:async(e,t)=>{var n;const r=Ye();r.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:i}=s;return Ut("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=r.userId)&&void 0!==n?n:""}),i}}),VE=Object.freeze({__proto__:null,Membership:WE,Moderation:HE,getChannelByIds:Og,createChannel:bb,updateChannel:async(e,t)=>{const n=Ye();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Rp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{channels:a}=s;return{data:xp(a.find((t=>t.channelId===e))),cachedAt:i}},deleteChannel:async e=>{const t=Ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await wb(e);return xp(n.data)},joinChannel:async e=>{const t=Ye();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await Rp(n);t.cache&&Ff(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ye();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await Rp(n);t.cache&&Ff(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ye();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Ke("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=r;return s},unmuteChannel:async e=>{const t=Ye();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},archiveChannel:async e=>{const t=Ye();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&nt(["archivedChannel","get",Je("archivedChannel")(n)],n),Ut("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ye();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const r=null===(t=tt(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=r?r:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&it(["archivedChannel","get",e],!0),Ut("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:$S,onChannelCreated:jp,onChannelUpdated:Kp,onChannelDeleted:Yp,onChannelJoined:Jp,onChannelLeft:eg,onChannelSetMuted:rg,onChannelMemberAdded:ag,onChannelMemberRemoved:cg,onChannelMemberBanned:hg,onChannelMemberUnbanned:gg,onChannelMemberRoleAdded:vg,onChannelMemberRoleRemoved:Sg,onChannelArchived:Eg,onChannelUnarchived:Ig,getChannel:(e,t)=>{const n=Ye();let r;return Nv(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Rg(e.data)}),s=Bf(n,["origin"]);return Fp(r,s)?void 0:(r=s,t(n))}),"channelId",wb,[Kp,Yp,Jp,eg,ag,cg,hg,gg,rg,Pw(Qy,"entityId","channel"),Pw(HS,"entityId","channel"),Pw((t=>Ey((async r=>{await(async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sp(r),r.channelId!==e)return;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;i&&(WS(i,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Pw((t=>Iy((async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sp(r),r.channelId!==e)return;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;i&&(WS(i,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Pw((t=>qS((async r=>{var s;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Ep(r),t(r))}))),"channelId","channel"),Pw((t=>KS((async r=>{var s;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==r.messageId)return;const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(it(["messagePreviewChannel","get",e]),await wb(r.channelId)):await Ep(r),t(r))}))),"channelId","channel"),Pw((e=>Ay((async t=>{var r,s;const{channelId:i,subChannelId:a}=t,o=null===(r=tt(["messagePreviewChannel","get",i]))||void 0===r?void 0:r.data;if(!o||o.subChannelId!==a)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await wb(i);(null===(s=tt(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Pw((t=>GS((async r=>{var s,i;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ip(r);const a=null===(s=tt(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!a||a.subChannelId!==r.subChannelId)return;(null===(i=tt(["channel","get",e]))||void 0===i?void 0:i.data)&&t(r)}))),"channelId","channel"),Pw(Ty,"channelId","channel"),Pw(TE,"channelId","channel"),Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getChannels(tmpid: ${a}) > listen`);const o=new DE(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getChannels(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Rt();if(!t)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ye();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;i=r?nv(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(AE((e=>{const{data:t}=LE();Fp(i,t)||o({loading:!1,data:t})}))),(()=>{const e=Be((async()=>LE()));$e(e,(({error:e,data:t,loading:n,origin:r,cachedAt:i})=>{i===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const i=new UE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const i=new jE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Tp,isUnreadCountSupport:Ap,convertFromRaw:Cp,preUpdateChannelCache:_p,prepareChannelPayload:Rp});const YE=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));nt(["communityUsers","collection",e],n)}))},QE=async(e,t)=>{const n=Ye();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),i=Kv(s),a=n.cache&&Date.now();return n.cache&&(Ff(i,{cachedAt:a}),YE(i.communities,i.communityUsers)),{data:i.communities.map((e=>gw.community(e))),cachedAt:a}};QE.locally=e=>{const t=Ye();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>tt(["community","get",e]))).filter(Boolean),r=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:r,cachedAt:s.cachedAt}};const zE=async e=>{const t=Ye();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Kv(n),s=t.cache&&Date.now();t.cache&&(Ff(r,{cachedAt:s}),YE(r.communities,r.communityUsers));const{communities:i}=r;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};zE.locally=e=>{const t=Ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=tt(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const JE=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Kv(e);if(n.cache){Ff(r);const e=tt(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},XE=e=>JE("community.created",e),ZE=e=>JE("community.updated",e),eI=e=>JE("community.deleted",e);class tI extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=Bf(e,["limit"]),i=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:rp(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:i})});return a}}class nI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var rI,sI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(rI||(rI={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(sI||(sI={}));class iI extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,excludingRoles:s}=e,i=Bf(e,["limit","includeDeleted","excludingRoles"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:l}=await this.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a,isDeleted:o})});return l}}class aI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{var t;const n=Je("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)r.data=r.data.filter((e=>e!==n));else if(!r.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}r.data=[n,...r.data]}})),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function oI(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function lI(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!oI(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!oI(e,t,"ADD_COMMUNITY_USER")))}const cI=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{const s=Kv(r),{communities:i,communityUsers:a}=s,o=jv(i,a);if(s.communities=o,n.cache){Ff(s,void 0,!1);const n=tt(["community","get",s.communities[0].communityId]),r=lI(e,s).map((e=>{const t=tt(["communityUsers","get",Je("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pv);t(n.data,r)}else t(s.communities[0],lI(e,s))}))},dI=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{const s=Kv(r),{communities:i,communityUsers:a}=s,o=jv(i,a);if(s.communities=o,n.cache){Ff(s,void 0,!1);const n=tt(["community","get",s.communities[0].communityId]),r=lI(e,s).map((e=>{const t=tt(["communityUsers","get",Je("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pv);t(n.data,r)}else t(s.communities[0],lI(e,s))}))},uI=e=>cI("community.userBanned",e),hI=e=>cI("community.userChanged",e),fI=e=>cI("community.userUnbanned",e),pI=e=>cI("community.roleAdded",e),gI=e=>cI("community.roleRemoved",e),mI=e=>dI("local.community.userAdded",e),yI=e=>dI("local.community.userRemoved",e),vI=e=>cI("community.joined",e),bI=e=>cI("community.left",e),wI=e=>dI("local.community.joined",e),SI=e=>dI("local.community.left",e),EI=e=>{const t=Ye(),n=[Mt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},II=e=>{const t=Ye();return Mt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},TI=e=>{const t=Ye();return Mt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},AI=e=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{var r,s;const i=Xg(n);if(0===i.users.length)return;const a=i.users[0];Ff(i);const o=Je("communityUsers")({communityId:e,userId:a.userId}),l=null===(r=tt(["communityUsers","get",o]))||void 0===r?void 0:r.data;nt(["communityUsers","get",o],Object.assign(Object.assign({},l),{user:a}));const c=null===(s=tt(["community","get",e]))||void 0===s?void 0:s.data;t(c,[Object.assign(Object.assign({},l),{user:a})])}))};class CI extends kv{constructor(e,t){const n=Tv(e),r=["communityUsers","collection",n];super(new iI(e),n,r,t),this.query=e,this.queryStreamController=new aI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vI,action:sI.OnCommunityJoined},{fn:wI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:SI,action:sI.OnCommunityLeft},{fn:uI,action:sI.OnCommunityUserBanned},{fn:hI,action:sI.OnCommunityUserChanged},{fn:pI,action:sI.OnCommunityUserRoleAdded},{fn:gI,action:sI.OnCommunityUserRoleRemoved},{fn:TI,action:sI.OnCommunityUserRoleAdded},{fn:II,action:sI.OnCommunityUserRoleRemoved},{fn:fI,action:sI.OnCommunityUserUnbanned},{fn:mI,action:sI.OnCommunityUserAdded},{fn:yI,action:sI.onCommunityUserRemoved},{fn:AI(this.query.communityId),action:sI.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["communityUsers","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class _I extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,excludingRoles:s}=e,i=Bf(e,["limit","includeDeleted","excludingRoles"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:l}=await this.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a,isDeleted:o})});return l}}class RI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Je("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var OI;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(OI||(OI={}));class kI extends kv{constructor(e,t){const n=Tv(e),r=["communityUsers","collection",n];super(new _I(e),n,r,t),this.query=e,this.queryStreamController=new RI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vI,action:OI.OnCommunityJoined},{fn:wI,action:OI.OnCommunityJoined},{fn:bI,action:OI.OnCommunityLeft},{fn:SI,action:OI.OnCommunityLeft},{fn:uI,action:OI.OnCommunityUserBanned},{fn:hI,action:OI.OnCommunityUserChanged},{fn:II,action:OI.OnCommunityUserRoleRemoved},{fn:gI,action:OI.OnCommunityUserRoleRemoved},{fn:fI,action:OI.OnCommunityUserUnbanned},{fn:AI(this.query.communityId),action:OI.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["communityUsers","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=ft(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var PI=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Ut("local.community.userAdded",r);const s=$f(r,"communityUsers");n.cache&&Ff(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Ut("local.community.userRemoved",r);const s=$f(r,"communityUsers");n.cache&&Ff(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let r=lt(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(r=r.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const s=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===s?St:bt),r},getMembers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new CI(e,(e=>{t(e)})),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new kI(e,(e=>{t(e)})),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},onCommunityUserAdded:e=>cI("community.userAdded",e),onCommunityUserRemoved:e=>cI("community.userRemoved",e),onCommunityUserBanned:uI,onCommunityUserChanged:hI,onCommunityUserUnbanned:fI,onCommunityUserRoleAdded:pI,onCommunityUserRoleRemoved:gI,onLocalCommunityUserAdded:mI,onLocalCommunityUserRemoved:yI,onCommunityJoined:vI,onCommunityLeft:bI,onLocalCommunityJoined:wI,onLocalCommunityLeft:SI,onLocalCommunityJoin:EI});class DI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new tI(e),n,r,t),this.query=e,this.queryStreamController=new nI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:rI.OnCommunityDeleted},{fn:ZE,action:rI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:rI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=ut(n,this.query.membership,t)),n}}class LI extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=Bf(e,["limit"]),i=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:rp(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:i})});return a}}class xI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var MI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(MI||(MI={}));class UI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new LI(e),n,r,t),this.query=e,this.queryStreamController=new xI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:XE,action:MI.OnCommunityCreated},{fn:eI,action:MI.OnCommunityDeleted},{fn:ZE,action:MI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:MI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=ut(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?bt:St)();return n=n.sort(r),n}}class FI extends Av{async getRequest(e,t){const{limit:n=W,includeDiscoverablePrivateCommunity:r}=e,s=Bf(e,["limit","includeDiscoverablePrivateCommunity"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:i,includeDiscoverablePrivateCommunity:null==r||r})});return a}}class NI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var BI;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(BI||(BI={}));class jI extends kv{constructor(e,t){const n=Tv(e),r=["trendingCommunity","collection",n];super(new FI(e),n,r,t),this.query=e,this.queryStreamController=new NI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:BI.OnCommunityDeleted},{fn:ZE,action:BI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:BI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class $I extends Av{async getRequest(e,t){const{limit:n=W,includeDiscoverablePrivateCommunity:r}=e,s=Bf(e,["limit","includeDiscoverablePrivateCommunity"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:i,includeDiscoverablePrivateCommunity:null==r||r})});return a}}class qI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var KI;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(KI||(KI={}));class GI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new $I(e),n,r,t),this.query=e,this.queryStreamController=new qI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:KI.OnCommunityDeleted},{fn:ZE,action:KI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:KI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class WI extends Av{async getRequest(e,t){var n;const{limit:r=W,communityMembershipStatus:s}=e,i=Bf(e,["limit","communityMembershipStatus"]),a={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:r}),{data:l}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},i),{filter:null!=s?s:"all",options:o,includeDiscoverablePrivateCommunity:null===(n=i.includeDiscoverablePrivateCommunity)||void 0===n||n})});return l}}function HI(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class VI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:HI(e)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...HI(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var YI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(YI||(YI={}));class QI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new WI(e),n,r,t),this.query=e,this.queryStreamController=new VI(this.query,this.cacheKey,this.notifyChange.bind(this),Vv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:XE,action:YI.OnCommunityCreated},{fn:eI,action:YI.OnCommunityDeleted},{fn:ZE,action:YI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:YI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=ut(n,this.query.communityMembershipStatus,t)),n}}class zI extends Av{async getRequest(e,t){const{limit:n=W,communityIds:r}=e,s=Bf(e,["limit","communityIds"]),i=t?{token:t}:{limit:n},a=r.map((e=>encodeURIComponent(e))),{data:o}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:i,communityIds:a})});return o}}var JI;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(JI||(JI={}));class XI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===JI.OnLocalJoinRequestUpdated){if(!r.data.find((e=>s.includes(e))))return}e===JI.OnLocalJoinRequestCreated&&(r.data=[...new Set([...s,...r.data])]),e===JI.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!s.includes(e)))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ZI extends kv{constructor(e,t){const n=Tv(e),r=["joinRequestList","collection",n];super(new zI(e),n,r,t),this.query=e,this.queryStreamController=new XI(this.query,this.cacheKey,this.notifyChange.bind(this),Gv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xv,action:JI.OnLocalJoinRequestCreated},{fn:Zv,action:JI.OnLocalJoinRequestUpdated},{fn:eb,action:JI.OnLocalJoinRequestUpdated},{fn:EI,action:JI.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=this.applyFilter(s.data.map((e=>tt(["joinRequest","get",e]))).filter(Pv).map((({data:e})=>e)).map(Yv));(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}var eT;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(eT||(eT={}));var tT=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Ye();r.log("community/moderation/addRoles",e,t,n);const{data:s}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),i=Wv(s);r.cache&&Ff(i),Ut("local.community.roleAdded",i);const{communityUsers:a}=i;return!!a.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Ye();r.log("community/moderation/removeRoles",e,t,n);const{data:s}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),i=Wv(s);r.cache&&Ff(i),Ut("local.community.roleRemoved",i);const{communityUsers:a}=i;return!!a.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ye();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=$f(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ye();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=$f(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}}}),nT=Object.freeze({__proto__:null,Moderation:tT,Membership:PI,getCommunityByIds:QE,createCommunity:async e=>{const t=Ye();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Hv(e));Ut("community.created",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&(Ff(r,{cachedAt:s}),YE(r.communities,r.communityUsers));const{communities:i}=r;return{data:gw.community(i[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ye();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Hv(t));Ut("community.updated",r);const s=Kv(r),i=n.cache&&Date.now();n.cache&&(Ff(s,{cachedAt:i}),YE(s.communities,s.communityUsers));const{communities:a}=s;return{data:gw.community(a.find((t=>t.communityId===e))),cachedAt:i}},deleteCommunity:async e=>{const t=Ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await zE(e);return Ut("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),gw.community(n.data)},joinCommunity:async e=>{const t=Ye();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Ut("local.community.joined",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ye();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Ut("local.community.left",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:XE,onCommunityUpdated:ZE,onCommunityDeleted:eI,searchCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchCommunities(tmpid: ${i}) > listen`);const a=new DI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunities(tmpid: ${i}) > listen`);const a=new UI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunity:(e,t)=>Nv(e,t,"communityId",zE,[ZE,eI,vI,bI,wI,SI,uI,fI,hI,Pw(EI,"targetId","community")],{callbackDataSelector:e=>e?gw.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getTrendingCommunities(tmpid: ${a}) > listen`);const o=new jI(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>it(c))),()=>{r(`getTrendingCommunities(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getRecommendedCommunities(tmpid: ${a}) > listen`);const o=new GI(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>it(c))),()=>{r(`getRecommendedCommunities(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`semanticSearchCommunities(tmpid: ${i}) > listen`);const a=new QI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`semanticSearchCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getJoinRequestList: (tmpid: ${i}) > listen`);const a=new ZI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getJoinRequestList (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return eT}});const rT=async e=>{const t=Ye();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{categories:s}=n;return{data:gw.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:r}};rT.locally=e=>{const t=Ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=tt(["category","get",e]);return n?{data:gw.category(n.data),cachedAt:n.cachedAt}:void 0};const sT=async e=>{const t=Ye();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:s,includeDeleted:i}=n,a=Bf(n,["page","limit","includeDeleted"]),o=r?{token:r}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:rp(i),options:o})}),{paging:c}=l,d=Bf(l,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Ff(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:i,options:o})];nt(e,{categories:null==u?void 0:u.map(Je("category")),paging:c})}return{data:null!=u?u:[],cachedAt:h,paging:c}};sT.locally=e=>{var t,n;const r=Ye();if(r.log("category/queryCategories.locally",e),!r.cache)return;const s=null!=e?e:{},{page:i,limit:a=10}=s,o=Bf(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["category","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=tt(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>tt(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:f}:void 0};var iT=Object.freeze({__proto__:null,getCategory:rT,getCategories:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCategories(tmpid: ${i}) > listen`);const{limit:a}=e,o=Bf(e,["limit"]),l=null!=a?a:W,{policy:c=V}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,s;const i=null===(r=tt(u))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!n&&a.length>0&&!(null==i?void 0:i.params.page))return;const d=Be(sT,Object.assign(Object.assign({},o),{limit:n?l:void 0,page:n||null==i?void 0:i.params.page}));$e(d,(({data:n,error:r,loading:s,paging:i})=>{const o={loading:s,error:r,params:{page:null==i?void 0:i.next},data:a};n&&(o.data=[...new Set([...a,...n.map(Je("category"))])]),nt(u,o),(n=>{var r,s;let i=null!==(r=n.data.map((e=>tt(["category","get",e]))).filter(Boolean).map((({data:e})=>gw.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(i=at(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(bt);break;case"lastCreated":i=i.sort(St);break;default:i=i.sort(vt)}t({onNextPage:h,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(o)}),je(c))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const aT=async e=>{const t=Ye();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:s}=n,i=Bf(n,["queryToken","dataTypes"]),a=(()=>{if(r)return{token:r}})(),{data:o}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},i),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:a})}),{paging:l}=o,c=Bf(o,["paging"]),d=$f(c,"communityUsers"),{posts:u}=d,{communities:h}=Kv(d),f=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},i),{options:a})];nt(e,{posts:u.map(Je("post")),paging:l})}return{data:u.map(gw.post),cachedAt:f,paging:l}};aT.locally=e=>{var t;const n=Ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const r=Bf(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},r)],{data:i,cachedAt:a}=null!==(t=tt(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.posts.length))return;const o=i.posts.map((e=>tt(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(gw.post),{paging:l}=i;return o.length===i.posts.length?{data:o,cachedAt:a,paging:l}:void 0};class oT extends Av{async getRequest(e,t){const{limit:n}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:s})});return i}}var lT;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(lT||(lT={}));class cT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===lT.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const dT=async e=>{const t=Ye();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.comments.map((e=>gw.comment(e))),cachedAt:s}};dT.locally=e=>{var t;const n=Ye();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>tt(["comment","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map((e=>gw.comment(e))),cachedAt:i.cachedAt}};const uT=e=>{const t=Ye();if(!t.cache)return;const n=Of();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const r=(new Date).toISOString(),s={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:r,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:r,updatedAt:r,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing"};return nt(["comment","get",s.commentId],s,{cachedAt:-5}),Ut("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},hT=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},fT=async e=>{const t=Ye();t.log("story/getStoryByStoryId",e);const n=tt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Xf("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=hT(n.data)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("story",e),t}const s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.stories[0],cachedAt:s}};fT.locally=e=>{const t=Ye();t.log("story/getStorybyStoryId",e);const n=tt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Xf("story",e)}const r=t.cache&&Date.now(),s=tt(["story","get",e]);if(s)return{data:s.data,cachedAt:r}};const pT=async(e,t=!1)=>{var n,r,s;const i=Ye(),a=null===(n=tt(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==a?void 0:a.syncState)){const t=Object.assign(Object.assign({},a),{isDeleted:!0});return it(["comment","get",e]),Ut("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const o=await iS(e);await i.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const l=Object.assign(Object.assign({},o.data),{isDeleted:!0});if(t?Dt((()=>Nf("comment",e))):st(["comment","get",e],{isDeleted:!0}),"story"===o.data.referenceType){const e=await fT(o.data.referenceId);Ut("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(r=tt(["post","get",o.data.referenceId]))||void 0===r?void 0:r.data;if(t){const n=tS();n.queueCommentChangeTask(new Jw(t.postId,e)),!l.parentId&&(null===(s=l.children)||void 0===s?void 0:s.length)>0&&l.children.forEach((e=>{n.queueCommentChangeTask(new Jw(t.postId,e))}))}}return Ut("local.comment.deleted",{comments:[l],commentChildren:[],files:[],users:[],communityUsers:[]}),l},gT=async e=>{const t=Ye();let n;t.log("comment/getComment",e),Xf("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:r}};gT.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=tt(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mT=e=>CS("local.comment.deleted",e),yT=e=>{const t=Ye();return Mt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(st(["comment","get",n.commentId],n),e(Ib(n))):e(n)}))},vT=e=>{const t=Ye();return Mt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(st(["comment","get",n.commentId],n),e(Ib(n))):e(n)}))};class bT extends Av{async getRequest(e,t){var n;const{pageSize:r,limit:s,includeDeleted:i}=e,a=Bf(e,["pageSize","limit","includeDeleted"]),o=null!==(n=null!=r?r:s)&&void 0!==n?n:W,l={type:a.sortBy||e.limit||e.pageSize?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{pageSize:o,limit:o}),{data:d}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},a),{isDeleted:rp(i),options:c})});return d}}var wT;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(wT||(wT={}));class ST extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.comments.map(Je("comment"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Je("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===wT.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ET=e=>CS("local.comment.created",e);class IT extends kv{constructor(e,t){const n=Tv(e),r=["comments","collection",n];super(new bT(e),n,r,t),this.query=e,this.queryStreamController=new ST(this.query,this.cacheKey,this.notifyChange.bind(this),jS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE([{fn:ET,action:wT.OnCommentCreated},{fn:mT,action:wT.OnCommentDeleted},{fn:_S,action:wT.OnCommentCreated},{fn:RS,action:wT.OnCommentUpdated},{fn:OS,action:wT.OnCommentDeleted},{fn:kS,action:wT.OnCommentFlagged},{fn:PS,action:wT.OnCommentUnflagged},{fn:DS,action:wT.OnCommentReactionAdded},{fn:LS,action:wT.OnCommentReactionRemoved},{fn:yT,action:wT.OnCommentReactionAdded},{fn:vT,action:wT.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Vm(t),Ym(t))}return e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["comment","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.comment);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===r.length&&r.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=mt(t)),"firstCreated"===this.query.sortBy)t=t.sort(bt);else t=t.sort(St);return t}}var TT=Object.freeze({__proto__:null,getCommentByIds:dT,createComment:async e=>{const t=Ye();t.log("comment/createComment",e);const n=uT(e),r=null==n?void 0:n.commentId;try{const{data:n}=await t.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:r})),{comments:s}=n;if(0===s.length)throw new Error("Comment not created");const i=t.cache&&Date.now();if(t.cache&&Ff(n,{cachedAt:i}),["post","content"].includes(e.referenceType))tS().queueCommentChangeTask(new zw(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=tt(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=tt(["story","get",t.data]);(null==e?void 0:e.data)&&Ut("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return Ut("local.comment.created",{comments:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:gw.comment(s[0]),cachedAt:i}}catch(e){throw n&&Ut("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ye();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s}),Ut("comment.updated",r);const{comments:i}=r;return{data:gw.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:pT,softDeleteComment:async e=>{Ye().log("comment/softDeleteComment",e);return pT(e)},hardDeleteComment:async e=>{Ye().log("comment/hardDeleteComment",e);return pT(e,!0)},flagComment:async(t,n)=>{const r=Ye();r.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:a}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,i);return r.cache&&Ff(a),Ut("comment.flagged",a),!!a},unflagComment:async e=>{const t=Ye();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Ff(n),Ut("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:_S,onCommentUpdated:RS,onCommentDeleted:OS,onCommentFlagged:kS,onCommentUnflagged:PS,onCommentReactionAdded:DS,onCommentReactionRemoved:LS,getComment:(e,t)=>Nv(e,t,"commentId",gT,[mT,OS,kS,DS,LS,PS,RS,yT,vT]),getComments:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getComments(tmpid: ${i}) > listen`);const a=new IT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getComments(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});const AT=e=>gS("local.post.deleted",e),CT=e=>{const t=Ye();return Mt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(st(["post","get",n.postId],n),e(n)):e(n)}))},_T=e=>{const t=Ye();return Mt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(st(["post","get",n.postId],n),e(n)):e(n)}))},RT=e=>gS("local.post.updated",e),OT=e=>[_S,OS,ET,mT].map((t=>({fn:Pw((n=>((e,t,n)=>t((async t=>{var r;const s=null===(r=tt(n))||void 0===r?void 0:r.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:lT.OnPostUpdated}))),kT=e=>[{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},...OT(e)];class PT extends kv{constructor(e,t){const n=Tv(e),r=["customRankingGlobalFeed","collection",n];super(new oT(e),n,r,t),this.query=e,this.queryStreamController=new cT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class DT extends Av{async getRequest(e,t){const{limit:n,dataTypes:r}=e,s=Bf(e,["limit","dataTypes"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:i})});return a}}class LT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===lT.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xT extends kv{constructor(e,t){const n=Tv(e),r=["globalFeed","collection",n];super(new DT(e),n,r,t),this.query=e,this.queryStreamController=new LT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class MT extends Av{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:s,includeDeleted:i,matchingOnlyParentPost:a,limit:o=W,untilAt:l}=e,c=Bf(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),d=t?{token:t}:{limit:o},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:d,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:r,isDeleted:rp(i),matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length)})});return u}}class UT extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved||e===lT.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(e===lT.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}if(e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const FT=async e=>{const t=Ye();let n;t.log("post/getPost",e),Xf("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("post",e),t}const r=$f(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:i.find((t=>t.postId===e)),cachedAt:s}};FT.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=tt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class NT extends kv{constructor(e,t){const n=Tv(e),r=["userFeed","collection",n];super(new MT(e),n,r,t),this.query=e,this.queryStreamController=new UT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},{fn:Pw((e=>_S((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[],o=this.applyFilter(a).map(gw.post);if(!this.shouldNotify(o)&&"event"===e)return;const l=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:l,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=at(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Ct(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class BT extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,communityId:s,untilAt:i}=e,a=Bf(e,["limit","includeDeleted","communityId","untilAt"]),o=t?{token:t}:{limit:n},{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},a),{targetId:s,targetType:"community",isDeleted:rp(r),matchingOnlyParentPost:!0,options:o})});return l}}class jT extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(e===lT.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const $T=({cacheKey:e,resolveId:t})=>[_S,OS,ET,mT].map((n=>({fn:Pw((r=>((e,t,n,r)=>t((async t=>{var s;const i=null===(s=tt(n))||void 0===s?void 0:s.data;i&&i.data.includes(r?r(t.referenceId):t.referenceId)&&e(t)})))(r,n,e,t)),"referenceId","post"),action:lT.OnPostUpdated}))),qT=e=>[{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},...$T({cacheKey:e})],KT=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Je("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Pv))&&void 0!==n?n:[]};class GT extends kv{constructor(e,t){const n=Tv(e),r=["communityFeed","collection",n];super(new BT(e),n,r,t),this.query=e,this.queryStreamController=new jT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(qT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);if(!this.shouldNotify(a)&&"event"===e)return;const o=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:o,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.tags&&(t=t.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=At(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Ct(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(bt);break;case"firstUpdated":t=t.sort(Et);break;case"lastUpdated":t=t.sort(It);break;default:t=t.sort(St)}return t}}class WT extends Ge{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class HT extends Av{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Qm.current()}async getRequest(e,t){var n,r,s,i,a;const o=void 0===t;let l=null;if(o&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,l=await this.cursor.get(),l&&Qm.isExpired(l.expiredAt)&&(await this.cursor.clear(),l=null)),o&&(null==l?void 0:l.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(r=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==r?r:"");return!Number.isNaN(t)&&t!==l.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const c=o&&l?l.cursor:t,d=await this.fetch(c);if(d.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=d.paging)||void 0===s?void 0:s.next)await this.persistCursor(d);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(a=null===(i=d.paging)||void 0===i?void 0:i.expiredAt)&&void 0!==a?a:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return d}async fetch(e){const t={limit:H};e&&(t.token=e);try{const{data:e}=await this.http.get(Z,{params:{options:t}});return e}catch(t){if(t instanceof Ge&&400300===t.code)throw new WT;if(t instanceof Ge&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(Z,{params:{options:{limit:H}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const r=null===(t=e.paging)||void 0===t?void 0:t.next,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!r||!s)return;const i=Date.parse(s);Number.isNaN(i)||await this.cursor.set({cursor:r,expiredAt:i})}}class VT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.parentPostId&&!r.data.includes(t.parentPostId)||(e!==lT.OnPostDeleted&&e!==lT.OnPostDeclined||(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const YT=["forYouFeed","collection"];class QT extends kv{constructor(e){const t=`for-you-feed-${Ye().userId}`,n={};super(new HT(n),t,YT,e),this.queryStreamController=new VT(n,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var zT=Object.freeze({__proto__:null,queryGlobalFeed:aT,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${i}) > listen`);const a=new PT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getGlobalFeed(tmpid: ${i}) > listen`);const a=new xT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getGlobalFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getUserFeed(tmpid: ${i}) > listen`);const a=new NT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getUserFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunityFeed(tmpid: ${i}) > listen`);const a=new GT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunityFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getForYouFeed(tmpid: ${r}) > listen`);const s=new QT(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getForYouFeed(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},AmityForYouFeedDisabledError:WT});const JT=async e=>{const t=Ye();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("post",e)})),t}const s=$f(r,"communityUsers"),i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),{data:s.posts.map(gw.post),cachedAt:i}};JT.locally=e=>{var t;const n=Ye();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>tt(["post","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map(gw.post),cachedAt:i.cachedAt}};const XT=async(e,t=!1)=>{var n;const r=Ye(),s=await sS(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await zE(s.data.targetId),t=(null!==(n=et(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Ut("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{Nf("post",e)}),0):st(["post","get",e],{isDeleted:!0}),Ut("local.post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),gw.post(i)};class ZT extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,matchingOnlyParentPost:s,untilAt:i}=e,a=Bf(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:o}=a,l={type:a.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{limit:n}),{data:d}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},a),{isDeleted:rp(r),matchingOnlyParentPost:null!=s?s:!(null==o?void 0:o.length),options:c})});return d}}class eA extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class tA extends kv{constructor(e,t){const n=Tv(e),r=["posts","collection",n];super(new ZT(e),n,r,t),this.query=e,this.queryStreamController=new eA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE(qT(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Vm(t),Ym(t))}return e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);if(!this.shouldNotify(a)&&"event"===e)return;const o=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:o,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=dt(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Ct(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=gt(n)),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class nA extends Av{async getRequest(e,t){const n=Bf(e,["limit"]),{communityId:r,placement:s}=n,i=Bf(n,["communityId","placement"]),a=s?`/api/v1/pinned-posts/communities/${r}/${s}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(a,{params:Object.assign({},i)});return o}}class rA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(fp):[]});Ff(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.pins.map(Je("pin"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Je("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sA extends kv{constructor(e,t){const n=Tv(e),r=["pinnedPosts","collection",n];super(new nA(e),n,r,t),this.query=e,this.queryStreamController=new rA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE($T({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;let a=(null!==(s=i.data.map((e=>tt(["pin","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.pinnedPost);a=this.applyFilter(a),(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>St({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class iA extends Av{async getRequest(e,t){const n=Bf(e,["limit"]),{data:r}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return r}}class aA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(fp)});Ff(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.pins.map(Je("pin"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Je("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oA extends kv{constructor(e,t){const n=Tv(e),r=["pinnedPosts","collection",n];super(new iA(e),n,r,t),this.query=e,this.queryStreamController=new aA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:AT,action:lT.OnPostDeleted},{fn:vS,action:lT.OnPostDeleted},...$T({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["pin","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.pinnedPost);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}}class lA extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:a}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:i})});return a}}function cA(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function dA(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class uA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:cA(e)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...cA(e)])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hA extends kv{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=Tv(n),s=["posts","collection",r];super(new lA(n),r,s,t),this.query=n,this.queryStreamController=new uA(this.query,this.cacheKey,this.notifyChange.bind(this),rS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yS,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:Pw((e=>_S((async t=>{const n=tt(this.cacheKey);dA(null==n?void 0:n.data).includes(t.referenceId)||(await sS(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{const n=tt(this.cacheKey);dA(null==n?void 0:n.data).includes(t.referenceId)||(await sS(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=ht(t,this.query.dataTypes)),t}}class fA extends Av{async getRequest(e,t){const{limit:n=W,matchingOnlyParentPost:r,hashtags:s,dataTypes:i,targetType:a="all"}=e,o=Bf(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),l={type:o.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},o),{hashtags:s,dataTypes:i,targetType:a,matchingOnlyParentPost:null!=r?r:!(null==i?void 0:i.length),options:c})});return d}}class pA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gA extends kv{constructor(e,t){const n=Tv(e),r=["posts","collection",n];super(new fA(e),n,r,t),this.query=e,this.queryStreamController=new pA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},{fn:Pw((e=>_S((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class mA extends Ov{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class yA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:KT(e.rooms,e.posts)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...KT(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&nt(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const vA=e=>{const t=Ye();return Mt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Ff(t),e(t.rooms[0])}))},bA=e=>{const t=Ye();return Mt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Ff(t),e(t.rooms[0])}))},wA=e=>{const t=Ye();return Mt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Ff(t),e(t.rooms[0])}))},SA=e=>{const t=Ye();return Mt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Ff(t),e(t.rooms[0])}))},EA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},IA=async e=>{const t=Ye();let n;t.log("room/getRoomById",e),Xf("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("room",e),t}const r=t.cache&&Date.now();return t.cache&&Ff(n,{cachedAt:r}),{data:n.rooms[0],cachedAt:r}};IA.locally=e=>{const t=Ye();t.log("room/getRoomById.locally",e),Xf("room",e);const n=t.cache&&Date.now(),r=tt(["room","get",e]);if(r)return{data:r.data,cachedAt:n}};const TA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const r=ib(t);await IA(null===(n=r.invitations)||void 0===n?void 0:n[0].targetId),Ff(r),e(r.invitations[0])}))},AA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},CA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},_A=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},RA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:r,users:s}=t;Ff({rooms:r,users:s});const i=t.eventActor.userInternalId;e({room:Nb(r[0]),actorInternalId:i,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===i)))||void 0===n?void 0:n.userId})}))},OA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},kA=e=>{const t=Ye();return Mt(t,"room/onRoomTerminated","room.terminated",(t=>{Ff(t),e(t.rooms[0])}))},PA=e=>{const t=Ye();return Mt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Ff(t),e(t.rooms[0])}))},DA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:r,users:s}=t;Ff({rooms:r,users:s});const i=t.eventActor.userInternalId;e({room:Nb(r[0]),actorInternalId:i,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===i)))||void 0===n?void 0:n.userId})}))},LA=e=>{const t=Ye();return Mt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Ff(t),e(t.rooms[0])}))},xA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Ff(t),e(t.rooms[0])}))};var MA;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(MA||(MA={}));const UA=e=>t=>e((e=>{t(e.room)}));class FA extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r}=e,s=Bf(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0},a=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:o}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:rp(r),options:a})});return o}}class NA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.rooms.map(Je("room"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Je("room"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===MA.OnRoomDeleted&&(r.data=r.data.filter((e=>e!==t._id))),e===MA.OnRoomCreated&&(r.data=[...new Set([t._id,...r.data])]),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class BA extends kv{constructor(e,t){const n=Tv(e),r=["rooms","collection",n];super(new FA(e),n,r,t),this.query=e,this.queryStreamController=new NA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vA,action:MA.OnRoomStartBroadcasting},{fn:wA,action:MA.OnRoomEndBroadcasting},{fn:SA,action:MA.OnRoomUpdated},{fn:bA,action:MA.OnRoomUpdated},{fn:kA,action:MA.OnRoomUpdated},{fn:UA(_A),action:MA.OnRoomUpdated},{fn:UA(RA),action:MA.OnRoomUpdated},{fn:UA(DA),action:MA.OnRoomUpdated},{fn:xA,action:MA.OnRoomUpdated},{fn:UA(OA),action:MA.OnRoomUpdated},{fn:Pw(TA,"targetId","room"),action:MA.OnRoomUpdated},{fn:PA,action:MA.OnRoomDidUpdate},{fn:LA,action:MA.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["room","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(Nb);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=at(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(bt);else t=t.sort(St);return t}}var jA=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ye();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Ut("local.room.created",n);const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{rooms:s}=n;return{data:Nb(s[0]),cachedAt:r}},updateRoom:async(e,t)=>{const n=Ye();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:r}=await n.http.put(`/api/v1/rooms/${e}`,t);Ut("local.room.updated",r);const s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{rooms:i}=r;return{data:Nb(i[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ye();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Ut("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ye();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Ut("local.room.stopped",n);const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{rooms:s}=n;return{data:s[0],cachedAt:r}},getBroadcasterData:async e=>{const t=Ye();t.log("room/getBroadcasterData",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Ye();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=Ye();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Ut("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ye();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Ut("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:Fb,WatchSessionStorage:Cb,getWatchSessionStorage:Rb,syncWatchSessions:Mb,updateCohostPermission:async(e,t,n)=>{const r=Ye();r.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await r.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});Ut("local.room.didUpdate",s);const i=r.cache&&Date.now();r.cache&&Ff(s,{cachedAt:i});const{rooms:a}=s;return{data:Nb(a[0]),cachedAt:i}},onRoomStartBroadcasting:vA,onRoomWaitingReconnect:bA,onRoomEndBroadcasting:wA,onRoomRecordedAvailable:SA,onRoomCoHostInvited:EA,onRoomCoHostInviteAccepted:TA,onRoomCoHostInviteRejected:AA,onRoomCoHostInviteCanceled:CA,onRoomParticipantJoined:_A,onRoomParticipantLeft:RA,onRoomParticipantStageLeft:e=>{const t=Ye();return Mt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:OA,onRoomTerminated:kA,onRoomDidUpdate:PA,onRoomCreated:e=>{const t=Ye();return Mt(t,"room/onRoomCreated","local.room.created",(t=>{Ff(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ye();return Mt(t,"room/onRoomUpdated","local.room.updated",(t=>{Ff(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ye();return Mt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Ff(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ye();return Mt(t,"room/onRoomStopped","local.room.stopped",(t=>{Ff(t),e(t.rooms[0])}))},onRoomParticipantRemoved:DA,onRoomLeft:e=>{const t=Ye();return Mt(t,"room/onRoomLeft","local.room.left",(t=>{Ff(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:LA,getRoom:(e,t)=>Nv(e,t,"_id",IA,[wA,vA,bA,kA,SA,UA(_A),UA(RA),UA(DA),xA,UA(OA),Pw(TA,"targetId","room"),PA,LA],{callbackDataSelector:e=>e?gw.room(e):e}),getRooms:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getRooms(tmpid: ${i}) > listen`);const a=new BA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getRooms(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});class $A extends kv{constructor(e){const t={limit:100},n=Tv(t),r=["liveRoomPosts","collection",n];super(new mA(t),n,r,e),this.query=t,this.queryStreamController=new yA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wA,action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){return e}}class qA extends Ov{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:r}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return r}}class KA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:KT(e.rooms,e.posts)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...KT(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&nt(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class GA extends kv{constructor(e,t){const n=Tv(e),r=["communityLiveRoomPosts","collection",n];super(new qA(e),n,r,t),this.query=e,this.queryStreamController=new KA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wA,action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){return e}}var WA=Object.freeze({__proto__:null,getPostByIds:JT,createPost:async e=>{const t=Ye();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=nS(a),l=t.cache&&Date.now();t.cache&&Ff(o,{cachedAt:l});const{posts:c}=o;return{data:gw.post(c[0]),cachedAt:l}},editPost:async(e,t)=>{const n=Ye();n.log("user/editPost",t);const{attachments:r}=t,s=r&&r.length>0&&t.attachmentProductTags?r.map((e=>{var n;const r=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return r?Object.assign(Object.assign({},e),{productTags:r}):e})):r,{data:i}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),a=$f(i,"communityUsers"),o=n.cache&&Date.now();n.cache&&Ff(a,{cachedAt:o}),Ut("local.post.updated",a);const{posts:l}=a;return{data:gw.post(l.find((t=>t.postId===e))),cachedAt:o}},deletePost:XT,softDeletePost:async e=>{Ye().log("post/softDeletePost",e);const t=await XT(e,!1);return gw.post(t)},hardDeletePost:async e=>{Ye().log("post/hardDeletePost",e);const t=await XT(e,!0);return gw.post(t)},approvePost:async e=>{const t=Ye();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Ut("post.approved",n),"community"===n.posts[0].targetType&&Ut("community.updated",n);const r=$f(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:gw.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ye();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Ut("community.updated",n),Ut("post.declined",n);const r=$f(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:gw.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const r=Ye();r.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:a}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,i);return r.cache&&Ff($f(a,"communityUsers")),Ut("post.flagged",a),!!a},unflagPost:async e=>{const t=Ye();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Ff($f(n,"communityUsers")),Ut("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ye();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Ye();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=$f(a,"communityUsers"),l=t.cache&&Date.now();t.cache&&Ff(o,{cachedAt:l});const{posts:c}=o;return{data:gw.post(c[0]),cachedAt:l}},createAudioPost:async e=>{const t=Ye();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&r?n.map((e=>{const t=null==r?void 0:r.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=nS(a),l=t.cache&&Date.now();return t.cache&&Ff(o,{cachedAt:l}),{data:qb(null==o?void 0:o.posts[0]),cachedAt:l}},createMixedMediaPost:async e=>{var t;const n=Ye();n.log("post/createMixedMediaPost",e);const{attachments:r,attachmentProductTags:s}=e,i=Bf(e,["attachments","attachmentProductTags"]),a=r&&r.length>0&&e.attachmentProductTags?r.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):r,{data:o}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},i),{attachments:a}));Ut("post.created",o);const l=nS(o),c=n.cache&&Date.now();return n.cache&&Ff(l,{cachedAt:c}),{data:qb(null===(t=null==l?void 0:l.posts)||void 0===t?void 0:t[0]),cachedAt:c}},createRoomPost:async e=>{const t=Ye();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Ut("post.created",n);const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:gw.post(i[0]),cachedAt:s}},createEventPost:async e=>{const t=Ye();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Ut("post.created",n);const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:gw.post(i[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ye();n.log("post/pinProduct",e);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=nS(r),i=n.cache&&Date.now();return n.cache&&Ff(r,{cachedAt:i}),Ut("local.post.updated",r),{data:qb(null==s?void 0:s.posts[0]),cachedAt:i}},unpinProduct:async e=>{const t=Ye();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),r=nS(n),s=t.cache&&Date.now();return t.cache&&Ff(n,{cachedAt:s}),Ut("local.post.updated",n),{data:qb(null==r?void 0:r.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ye();n.log("post/updateProductTags",e);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=nS(r),i=n.cache&&Date.now();return n.cache&&Ff(r,{cachedAt:i}),Ut("local.post.updated",r),{data:qb(null==s?void 0:s.posts[0]),cachedAt:i}},onPostCreated:mS,onPostUpdated:yS,onPostDeleted:vS,onPostApproved:bS,onPostDeclined:wS,onPostFlagged:SS,onPostUnflagged:ES,onPostReactionAdded:IS,onPostReactionRemoved:TS,getPost:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.post(e.data):n}))}),"postId",sS,[bS,wS,CT,_T,t=>vS((n=>{var r;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=tt(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),nt(["post","get",e.postId],e),s=e)}t(s)})),SS,e=>IS((t=>{e(t)})),e=>TS((t=>{e(t)})),ES,yS,RT,AT,Pw((t=>_S((async n=>{n.referenceId===e&&(await sS(e),t(n))}))),"referenceId","post"),Pw((t=>OS((async n=>{n.referenceId===e&&(await sS(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getPosts(tmpid: ${i}) > listen`);const a=new tA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getPinnedPosts(tmpid: ${i}) > listen`);const a=new sA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getPinnedPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getGlobalPinnedPosts(tmpid: ${i}) > listen`);const a=new oA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getGlobalPinnedPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`semanticSearchPosts(tmpid: ${i}) > listen`);const a=new hA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`semanticSearchPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchPostsByHashtag(tmpid: ${i}) > listen`);const a=new gA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchPostsByHashtag(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getLiveRoomPosts(tmpid: ${r}) > listen`);const s=new $A(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getLiveRoomPosts(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunityLiveRoomPosts(tmpid: ${i}) > listen`);const a=new GA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunityLiveRoomPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});const HA=async e=>{const t=Ye();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}};HA.locally=e=>{const t=Ye();if(t.log("stream/getStream",e),!t.cache)return;const n=tt(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const VA=e=>{const t=Ye();return Mt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Ff(t),e(t.videoStreamings[0])}))},YA=e=>{const t=Ye();return Mt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Ff(t),e(t.videoStreamings[0])}))},QA=e=>{const t=Ye();return Mt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Ff(t),e(t.videoStreamings[0])}))},zA=e=>{const t=Ye();return Mt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Ff(t),e(t.videoStreamings[0])}))},JA=e=>{const t=Ye();return Mt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Ff(t),e(t.videoStreamings[0])}))},XA=e=>{const t=Ye();return Mt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>HA(e))));const s=null===(n=tt(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},ZA=(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.stream(e.data):n}))}),"streamId",HA,[QA,VA,YA,zA,JA,cE]);ZA.locally=e=>{const t=Ye();if(t.log("stream/getStreamById",e),!t.cache)return;const n=tt(["stream","get",e]);return n?{data:gw.stream(n.data),cachedAt:n.cachedAt}:void 0};class eC extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},r),{options:s})});return Object.assign(Object.assign({},i.results),{paging:i.paging})}}class tC extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Ff(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.videoStreamings.map(Je("stream")),query:this.query});else{const n=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,i=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...i,...e.videoStreamings.map(Je("stream"))])]:[...new Set([...e.videoStreamings.map(Je("stream")),...i])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class nC extends kv{constructor(e,t){const n=Tv(e),r=["streams","collection",n],s=new eC(e);super(s,n,r,t),this.applyFilter=e=>{let t=at(e,"isDeleted",this.query.isDeleted);return t=t.sort("lastCreated"===this.query.sortBy?St:bt),t},this.query=e,this.queryStreamController=new tC(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>tt(["stream","get",e]))).filter(Boolean).map((e=>gw.stream(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:()=>this.loadPage({initial:!1,direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QA,action:"onStreamRecorded"},{fn:VA,action:"onStreamStarted"},{fn:YA,action:"onStreamStopped"},{fn:zA,action:"onStreamFlagged"},{fn:JA,action:"onStreamTerminated"},{fn:cE,action:"onStreamViewerBanned"},{fn:XA,action:"onStreamViewerUnbanned"}])}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var rC=Object.freeze({__proto__:null,createStream:async e=>{const t=Ye();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:gw.stream(s[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{videoStreamings:i}=r;return{data:gw.stream(i.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ye();t.log("stream/deleteStream",e);const n=await HA(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=r,i=Object.assign(Object.assign({},n.data),{isDeleted:!0});return st(["stream","get",e],i),s},disposeStream:async e=>{const t=Ye();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{videoStreamings:i}=r;return{data:gw.stream(i.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:VA,onStreamStopped:YA,onStreamRecorded:QA,onStreamFlagged:zA,onStreamTerminated:JA,onStreamViewerBanned:cE,onStreamViewerUnbanned:XA,getStreamById:ZA,getStreams:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getStreams(tmpid: ${a}) > listen`);const o=new nC(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getStreams(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});const sC=async()=>{const e=Ye();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return nt(["get","presenceSetting"],t),t};class iC{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await iC.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await sC()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const r=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(r/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,r)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=Ye();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const aC=new Map,oC=e=>{let t=aC.get(e);return t||(t=new iC(e),aC.set(e,t)),t};var lC=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,r;const s=Ye();s.log("room/getWatchingUsers",{roomId:e});const{data:i}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),a=null!==(t=null==i?void 0:i.viewers.map((e=>e.userId)))&&void 0!==t?t:[],o=[];for(let e=0;e<a.length;e+=100)o.push(a.slice(e,e+100));const l=await Promise.all(o.map((e=>mw(e)))),c=[];return l.forEach((e=>{e.data&&c.push(...e.data)})),{data:c,cachedAt:null!==(r=null===(n=l[0])||void 0===n?void 0:n.cachedAt)&&void 0!==r?r:Date.now()}},getRoomUserCount:async e=>{const t=Ye();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return nt(["get","watchingCount",e],n),n},startHeartbeat:e=>{oC(e).start()},stopHeartbeat:e=>{oC(e).stop(),(e=>{const t=aC.get(e);t&&(t.destroy(),aC.delete(e))})(e)}});const cC=async e=>{const t=Ye();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{polls:s}=n,i=s.find((t=>t.pollId===e));return{data:Bb(i),cachedAt:r}};cC.locally=e=>{const t=Ye();if(t.log("poll/getPoll",e),!t.cache)return;const n=tt(["poll","get",e]);return n?{data:Bb(n.data),cachedAt:n.cachedAt}:void 0};const dC=e=>{const t=Ye();return Mt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Ff(n),e(n.polls[0])}))},uC=e=>{const t=Ye();return Mt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Ff(n),e(n.polls[0])}))};var hC=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ye();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{polls:s}=n;return{data:Bb(s[0]),cachedAt:r}},closePoll:async e=>{const t=Ye();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r}),Ut("poll.updated",n);const{polls:s}=n,i=s.find((t=>t.pollId===e));return{data:Bb(i),cachedAt:r}},deletePoll:async e=>{const t=Ye();t.log("poll/deletePoll",e);const n=await cC(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=r,i=Object.assign(Object.assign({},n.data),{isDeleted:!0});return st(["poll","get",e],i),Ut("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const n=Ye();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{polls:i}=r,a=i.find((t=>t.pollId===e));return Ut("poll.updated",r),{data:Bb(a),cachedAt:s}},unvotePoll:async e=>{const t=Ye();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r}),Ut("poll.updated",n)},onPollUpdated:dC,onPollDeleted:uC,getPoll:(e,t)=>Nv(e,t,"pollId",cC,[dC,uC])});function fC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pC={exports:{}};!function(e,t){var n,r,s,i,a;n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return n.alwaysNormalize?(i.path=a.normalizePath(i.path),a.buildURLFromParts(i)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var c={scheme:o.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=o.netLoc,"/"!==i.path[0]))if(i.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+i.path;c.path=a.normalizePath(u)}else c.path=o.path,i.params||(c.params=o.params,i.query||(c.query=o.query));return null===c.path&&(c.path=n.alwaysNormalize?a.normalizePath(i.path):i.path),a.buildURLFromParts(c)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(pC);var gC=pC.exports;function mC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function yC(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mC(Object(n),!0).forEach((function(t){vC(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mC(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function vC(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bC(){return bC=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bC.apply(this,arguments)}const wC=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let SC=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e}({}),EC=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),IC=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({});const TC=function(){},AC={trace:TC,debug:TC,log:TC,warn:TC,info:TC,error:TC};let CC=AC;function _C(e,...t){t.forEach((function(t){CC[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):TC}(t)}))}const RC=CC,OC=/^(\d+)x(\d+)$/,kC=/(.+?)=(".*?"|.*?)(?:,|$)/g;class PC{constructor(e){"string"==typeof e&&(e=PC.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&("X-"===t.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(2*e,2*e+2),16);return n}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=OC.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const n={};for(kC.lastIndex=0;null!==(t=kC.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));n[t[1].trim()]=e}return n}}function DC(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class LC{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const n=t.attr;for(const t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){RC.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=bC(new PC({}),n,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);wC(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(wC(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&wC(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class xC{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var MC="audio",UC="video",FC="audiovideo";class NC{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[MC]:null,[UC]:null,[FC]:null},this.baseurl=e}setByteRange(e,t){const n=e.split("@",2),r=[];1===n.length?r[0]=t?t.byteRangeEndOffset:0:r[0]=parseInt(n[1]),r[1]=parseInt(n[0])+r[0],this._byteRange=r}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=gC.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class BC extends NC{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new xC,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!wC(this.programDateTime))return null;const e=wC(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,n,r,s,i=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,n),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[MC]=null,e[UC]=null,e[FC]=null}}class jC extends NC{constructor(e,t,n,r,s){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new xC,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const i=e.enumeratedString("BYTERANGE");i&&this.setByteRange(i,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class $C{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t,this.advanced=this.endSN>e.endSN||t>0||0===t&&n>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&wC(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function qC(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function KC(e){const t=e.split(":");let n=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),n=qC(s)):n=function(e){const t=GC(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}(s)}}return n}function GC(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var WC={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},HC="org.w3.clearkey",VC="com.apple.streamingkeydelivery",YC="com.microsoft.playready",QC="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function zC(e){switch(e){case VC:return WC.FAIRPLAY;case YC:return WC.PLAYREADY;case QC:return WC.WIDEVINE;case HC:return WC.CLEARKEY}}var JC="edef8ba979d64acea3c827dcd51d21ed";function XC(e){switch(e){case WC.FAIRPLAY:return VC;case WC.PLAYREADY:return YC;case WC.WIDEVINE:return QC;case WC.CLEARKEY:return HC}}function ZC(e){const{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[WC.FAIRPLAY,WC.WIDEVINE,WC.PLAYREADY,WC.CLEARKEY].filter((e=>!!t[e])):[];return!r[WC.WIDEVINE]&&n&&r.push(WC.WIDEVINE),r}const e_="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function t_(e,t,n){return Uint8Array.prototype.slice?e.slice(t,n):new Uint8Array(Array.prototype.slice.call(e,t,n))}const n_=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,r_=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,s_=(e,t)=>{const n=t;let r=0;for(;n_(e,t);){r+=10;r+=i_(e,t+6),r_(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)},i_=(e,t)=>{let n=0;return n=(127&e[t])<<21,n|=(127&e[t+1])<<14,n|=(127&e[t+2])<<7,n|=127&e[t+3],n},a_=(e,t)=>n_(e,t)&&i_(e,t+6)+10<=e.length-t,o_=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,l_=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=i_(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}},c_=e=>{let t=0;const n=[];for(;n_(e,t);){const r=i_(e,t+6);t+=10;const s=t+r;for(;t+8<s;){const r=l_(e.subarray(t)),s=d_(r);s&&n.push(s),t+=r.size+10}r_(e,t)&&(t+=10)}return n},d_=e=>"PRIV"===e.type?u_(e):"W"===e.type[0]?f_(e):h_(e),u_=e=>{if(e.size<2)return;const t=g_(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}},h_=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const n=g_(e.data.subarray(t),!0);t+=n.length+1;const r=g_(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=g_(e.data.subarray(1));return{key:e.type,data:t}},f_=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const n=g_(e.data.subarray(t),!0);t+=n.length+1;const r=g_(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=g_(e.data);return{key:e.type,data:t}},p_=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),n=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}},g_=(e,t=!1)=>{const n=y_();if(n){const r=n.decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let s,i,a,o="",l=0;for(;l<r;){if(s=e[l++],0===s&&t)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],o+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&a)<<0)}}return o};let m_;function y_(){return m_||void 0===self.TextDecoder||(m_=new self.TextDecoder("utf-8")),m_}const v_=function(e){let t="";for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r="0"+r),t+=r}return t},b_=Math.pow(2,32)-1,w_=[].push,S_={video:1,audio:2,id3:3,text:4};function E_(e){return String.fromCharCode.apply(null,e)}function I_(e,t){const n=e[t]<<8|e[t+1];return n<0?65536+n:n}function T_(e,t){const n=A_(e,t);return n<0?4294967296+n:n}function A_(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function C_(e,t,n){e[t]=n>>24,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=255&n}function __(e,t){const n=[];if(!t.length)return n;const r=e.byteLength;for(let s=0;s<r;){const i=T_(e,s),a=i>1?s+i:r;if(E_(e.subarray(s+4,s+8))===t[0])if(1===t.length)n.push(e.subarray(s+8,a));else{const r=__(e.subarray(s+8,a),t.slice(1));r.length&&w_.apply(n,r)}s=a}return n}function R_(e){const t=[],n=e[0];let r=8;const s=T_(e,r);r+=4;r+=0===n?8:16,r+=2;let i=e.length+0;const a=I_(e,r);r+=2;for(let n=0;n<a;n++){let n=r;const a=T_(e,n);n+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return RC.warn("SIDX has hierarchical references (not supported)"),null;const l=T_(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+o-1}}),i+=o,n+=4,r=n}return{earliestPresentationTime:0,timescale:s,version:n,referencesCount:a,references:t}}function O_(e){const t=[],n=__(e,["moov","trak"]);for(let e=0;e<n.length;e++){const r=n[e],s=__(r,["tkhd"])[0];if(s){let e=s[0],n=0===e?12:20;const i=T_(s,n),a=__(r,["mdia","mdhd"])[0];if(a){e=a[0],n=0===e?12:20;const s=T_(a,n),o=__(r,["mdia","hdlr"])[0];if(o){const e=E_(o.subarray(8,12)),n={soun:MC,vide:UC}[e];if(n){const e=__(r,["mdia","minf","stbl","stsd"])[0];let a;e&&(a=E_(e.subarray(12,16))),t[i]={timescale:s,type:n},t[n]={timescale:s,id:i,codec:a}}}}}}return __(e,["moov","mvex","trex"]).forEach((e=>{const n=T_(e,4),r=t[n];r&&(r.default={duration:T_(e,12),flags:T_(e,20)})})),t}function k_(e){const t=__(e,["schm"])[0];if(t){const n=E_(t.subarray(4,8));if("cbcs"===n||"cenc"===n)return __(e,["schi","tenc"])[0]}return RC.error("[eme] missing 'schm' box"),null}function P_(e){const t=T_(e,0);let n=8;1&t&&(n+=4),4&t&&(n+=4);let r=0;const s=T_(e,4);for(let i=0;i<s;i++){if(256&t){r+=T_(e,n),n+=4}512&t&&(n+=4),1024&t&&(n+=4),2048&t&&(n+=4)}return r}function D_(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function L_(e,t){const n=[],r=t.samples,s=t.timescale,i=t.id;let a=!1;return __(r,["moof"]).map((o=>{const l=o.byteOffset-8;__(o,["traf"]).map((o=>{const c=__(o,["tfdt"]).map((e=>{const t=e[0];let n=T_(e,4);return 1===t&&(n*=Math.pow(2,32),n+=T_(e,8)),n/s}))[0];return void 0!==c&&(e=c),__(o,["tfhd"]).map((c=>{const d=T_(c,4),u=16777215&T_(c,0);let h=0;const f=0!=(16&u);let p=0;const g=0!=(32&u);let m=8;d===i&&(0!=(1&u)&&(m+=8),0!=(2&u)&&(m+=4),0!=(8&u)&&(h=T_(c,m),m+=4),f&&(p=T_(c,m),m+=4),g&&(m+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),n=t<0?e:e.substring(0,t);return"hvc1"===n||"hev1"===n||"dvh1"===n||"dvhe"===n}(t.codec)),__(o,["trun"]).map((i=>{const o=i[0],c=16777215&T_(i,0),d=0!=(1&c);let u=0;const f=0!=(4&c),g=0!=(256&c);let m=0;const y=0!=(512&c);let v=0;const b=0!=(1024&c),w=0!=(2048&c);let S=0;const E=T_(i,4);let I=8;d&&(u=T_(i,I),I+=4),f&&(I+=4);let T=u+l;for(let l=0;l<E;l++){if(g?(m=T_(i,I),I+=4):m=h,y?(v=T_(i,I),I+=4):v=p,b&&(I+=4),w&&(S=0===o?T_(i,I):A_(i,I),I+=4),t.type===UC){let t=0;for(;t<v;){const i=T_(r,T);if(T+=4,x_(a,r[T])){M_(r.subarray(T,T+i),a?2:1,e+S/s,n)}T+=i,t+=i+4}}e+=m/s}})))}))}))})),n}function x_(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function M_(e,t,n,r){const s=U_(e);let i=0;i+=t;let a=0,o=0,l=!1,c=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);const e=s.length-i;if(!l&&4===a&&i<s.length){l=!0;if(181===s[i++]){const e=I_(s,i);if(i+=2,49===e){const e=T_(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],o=31&t,l=64&t,c=l?2+3*o:0,d=new Uint8Array(c);if(l){d[0]=t;for(let e=1;e<c;e++)d[e]=s[i++]}r.push({type:e,payloadType:a,pts:n,bytes:d})}}}}}else if(5===a&&o<e){if(l=!0,o>16){const e=[];for(let t=0;t<16;t++){const n=s[i++].toString(16);e.push(1==n.length?"0"+n:n),3!==t&&5!==t&&7!==t&&9!==t||e.push("-")}const t=o-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];r.push({payloadType:a,pts:n,uuid:e.join(""),userData:g_(l),userDataBytes:l})}}else if(o<e)i+=o;else if(o>e)break}}function U_(e){const t=e.byteLength,n=[];let r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(n.push(r+2),r+=2):r++;if(0===n.length)return e;const s=t-n.length,i=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===n[0]&&(a++,n.shift()),i[r]=e[a];return i}function F_(e,t,n){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,s,i;if(t){r=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){const n=t[e];if(16!==n.byteLength)throw new RangeError("Invalid key");s.set(n,16*e)}}else r=0,s=new Uint8Array;r>0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return n&&n.byteLength>0&&new DataView(a.buffer).setUint32(0,n.byteLength,!1),function(e,...t){const n=t.length;let r=8,s=n;for(;s--;)r+=t[s].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=255&r,i.set(e,4),s=0,r=8;s<n;s++)i.set(t[s],r),r+=t[s].byteLength;return i}([112,115,115,104],new Uint8Array([r,0,0,0]),e,i,s,a,n||new Uint8Array)}let N_={};class B_{static clearKeyUriToKeyIdMap(){N_={}}constructor(e,t,n,r=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case VC:case QC:case YC:case HC:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||RC.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}(e);return new B_(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=KC(this.uri);if(t)switch(this.keyFormat){case QC:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case YC:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=F_(e,null,t);const n=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(n)),s=r.substring(r.indexOf("<"),r.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=qC(e).subarray(0,16);!function(e){const t=function(e,t,n){const r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=N_[this.uri];if(!e){const t=Object.keys(N_).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),N_[this.uri]=e}this.keyId=e}return this}}const j_=/\{\$([a-zA-Z0-9-_]+)\}/g;function $_(e){return j_.test(e)}function q_(e,t,n){if(null!==e.variableList||e.hasVariableRefs)for(let r=n.length;r--;){const s=n[r],i=t[s];i&&(t[s]=K_(e,i))}}function K_(e,t){if(null!==e.variableList||e.hasVariableRefs){const n=e.variableList;return t.replace(j_,(t=>{const r=t.substring(2,t.length-1),s=null==n?void 0:n[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function G_(e,t,n){let r,s,i=e.variableList;if(i||(e.variableList=i={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(n).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${n}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in i?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=s||""}function W_(e,t,n){const r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function H_(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const V_={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},Y_=H_();function Q_(e,t){var n;return null!=(n=null==Y_?void 0:Y_.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&n}const z_=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,J_=/#EXT-X-MEDIA:(.*)/g,X_=/^#EXT(?:INF|-X-TARGETDURATION):/m,Z_=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),eR=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class tR{static findGroup(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(r.id===t)return r}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}static resolve(e,t){return gC.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return X_.test(e)}static parseMasterPlaylist(e,t){const n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:$_(e)},r=[];let s;for(z_.lastIndex=0;null!=(s=z_.exec(e));)if(s[1]){var i;const e=new PC(s[1]);q_(n,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=K_(n,s[2]),o={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:tR.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),sR((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=tR.convertAVC1ToAVCOTI(o.videoCodec)),null!=(i=o.unknownCodecs)&&i.length||r.push(o),n.levels.push(o)}else if(s[3]){const e=s[3],r=s[4];switch(e){case"SESSION-DATA":{const e=new PC(r);q_(n,e,["DATA-ID","LANGUAGE","VALUE","URI"]);const t=e["DATA-ID"];t&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[t]=e);break}case"SESSION-KEY":{const e=nR(r,t,n);e.encrypted&&e.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(e)):RC.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const e=new PC(r);q_(n,e,["NAME","VALUE","QUERYPARAM"]),G_(n,e,t)}break;case"CONTENT-STEERING":{const e=new PC(r);q_(n,e,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:tR.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":n.startTimeOffset=rR(r)}}const a=r.length>0&&r.length<n.levels.length;return n.levels=a?r:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,n){let r;const s={},i=n.levels,a={AUDIO:i.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:i.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(J_.lastIndex=0;null!==(r=J_.exec(e));){const e=new PC(r[1]),i=e.TYPE;if(i){const r=a[i],l=s[i]||[];s[i]=l,q_(n,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",instreamId:e["INSTREAM-ID"],name:e.NAME||e.LANGUAGE||"",type:i,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:e.LANGUAGE,url:e.URI?tR.resolve(e.URI,t):""};if(null!=r&&r.length){const e=tR.findGroup(r,c.groupId)||r[0];iR(c,e,"audioCodec"),iR(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,n,r,s,i){const a=new $C(t),o=a.fragments;let l,c,d,u=null,h=0,f=0,p=0,g=0,m=null,y=new BC(r,t),v=-1,b=!1;for(Z_.lastIndex=0,a.m3u8=e,a.hasVariableRefs=$_(e);null!==(l=Z_.exec(e));){b&&(b=!1,y=new BC(r,t),y.start=p,y.sn=h,y.cc=g,y.level=n,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));const e=l[1];if(e){y.duration=parseFloat(e);const t=(" "+l[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(wC(y.duration)){y.start=p,d&&lR(y,d,a),y.sn=h,y.level=n,y.cc=g,y.urlId=s,o.push(y);const e=(" "+l[3]).slice(1);y.relurl=K_(a,e),aR(y,m),m=y,p+=y.duration,h++,f=0,b=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);m?y.setByteRange(e,m):y.setByteRange(e)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(eR),!l){RC.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<l.length&&void 0===l[c];c++);const e=(" "+l[c]).slice(1),s=(" "+l[c+1]).slice(1),p=l[c+2]?(" "+l[c+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(s);break;case"SKIP":{const e=new PC(s);q_(a,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(wC(t)){a.skippedSegments=t;for(let e=t;e--;)o.unshift(null);h+=t}const n=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(a.recentlyRemovedDateranges=n.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||p)&&y.tagList.push(p?[s,p]:[s]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{const e=new PC(s);q_(a,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),q_(a,e,e.clientAttrs);const t=new LC(e,a.dateRanges[e.ID]);t.isValid||a.skippedSegments?a.dateRanges[t.id]=t:RC.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new PC(s);q_(a,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?W_(a,e,i):G_(a,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=nR(s,t,a);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={}),d[e.keyFormat]&&(d=bC({},d)),d[e.keyFormat]=e}else RC.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=rR(s);break;case"MAP":{const e=new PC(s);if(q_(a,e,["BYTERANGE","URI"]),y.duration){const s=new BC(r,t);oR(s,e,n,d),u=s,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else oR(y,e,n,d),u=y,b=!0;break}case"SERVER-CONTROL":{const e=new PC(s);a.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new PC(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const n=f>0?e[e.length-1]:void 0,r=f++,i=new PC(s);q_(a,i,["BYTERANGE","URI"]);const o=new jC(i,y,t,r,n);e.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new PC(s);q_(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new PC(s);q_(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:RC.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(o.pop(),p-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(aR(y,m),y.cc=g,a.fragmentHint=y,d&&lR(y,d,a));const w=o.length,S=o[0],E=o[w-1];if(p+=a.skippedSegments*a.targetduration,p>0&&w&&E){a.averagetargetduration=p/w;const e=E.sn;a.endSN="initSegment"!==e?e:0,a.live||(E.endList=!0),S&&(a.startCC=S.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=g,v>0&&function(e,t){let n=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=n.programDateTime-1e3*t.duration,n=t}}(o,v),a}}function nR(e,t,n){var r,s;const i=new PC(e);q_(n,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=i.METHOD)?r:"",o=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,d=null!=(s=i.KEYFORMAT)?s:"identity";o&&i.IV&&!l&&RC.error(`Invalid IV: ${i.IV}`);const u=o?tR.resolve(o,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new B_(a,u,d,h,l)}function rR(e){const t=new PC(e).decimalFloatingPoint("TIME-OFFSET");return wC(t)?t:null}function sR(e,t){["video","audio","text"].forEach((n=>{const r=e.filter((e=>function(e,t){const n=V_[t];return!!n&&!0===n[e.slice(0,4)]}(e,n)));if(r.length){const s=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${n}Codec`]=s.length>0?s[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}function iR(e,t,n){const r=t[n];r&&(e[n]=r)}function aR(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),wC(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function oR(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function lR(e,t,n){e.levelkeys=t;const{encryptedFragments:r}=n;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}var cR="manifest",dR="level",uR="audioTrack",hR="subtitleTrack",fR="main",pR="audio",gR="subtitle";function mR(e){const{type:t}=e;switch(t){case uR:return pR;case hR:return gR;default:return fR}}function yR(e,t){let n=e.url;return void 0!==n&&0!==n.indexOf("data:")||(n=t.url),n}class vR{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(SC.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(SC.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,n=t.pLoader,r=t.loader,s=new(n||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:cR,url:n,deliveryDirectives:null})}onLevelLoading(e,t){const{id:n,level:r,url:s,deliveryDirectives:i}=t;this.load({id:n,level:r,responseType:"text",type:dR,url:s,deliveryDirectives:i})}onAudioTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:i}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:uR,url:s,deliveryDirectives:i})}onSubtitleTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:i}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:hR,url:s,deliveryDirectives:i})}load(e){var t;const n=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url)return void RC.trace("[playlist-loader]: playlist request ongoing");RC.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===cR?n.manifestLoadPolicy.default:bC({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===dR&&null!==e.level?t=this.hls.levels[e.level].details:e.type===uR&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===hR&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,n=t.targetduration;if(e&&n){const t=1e3*Math.max(3*e,.8*n);r=bC({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},o={onSuccess:(e,t,n,r)=>{const s=this.getInternalLoader(n);this.resetInternalLoader(n.type);const i=e.data;0===i.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),tR.isMediaPlaylist(i)?this.handleTrackOrLevelPlaylist(e,t,n,r||null,s):this.handleMasterPlaylist(e,t,n,r)):this.handleManifestParsingError(e,n,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,n,r){const s=this.hls,i=e.data,a=yR(e,n),o=tR.parseMasterPlaylist(i,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,n,o.playlistParsingError,r,t);const{contentSteering:l,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=tR.parseMasterPlaylistMedia(i,a,o);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(RC.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new PC({}),bitrate:0,url:""}))}s.trigger(SC.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,n,r,s){const i=this.hls,{id:a,level:o,type:l}=n,c=yR(e,n),d=wC(a)?a:0,u=wC(o)?o:d,h=mR(n),f=tR.parseLevelPlaylist(e.data,c,u,h,d,this.variableList);if(l===cR){const e={attrs:new PC({}),bitrate:0,details:f,name:"",url:c};i.trigger(SC.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:c,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,s)}handleManifestParsingError(e,t,n,r,s){this.hls.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.MANIFEST_PARSING_ERROR,fatal:t.type===cR,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,n=!1,r,s){let i=`A network ${n?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===dR?i+=`: ${e.level} id: ${e.id}`:e.type!==uR&&e.type!==hR||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(i);RC.warn(`[playlist-loader]: ${i}`);let o=IC.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case cR:o=n?IC.MANIFEST_LOAD_TIMEOUT:IC.MANIFEST_LOAD_ERROR,l=!0;break;case dR:o=n?IC.LEVEL_LOAD_TIMEOUT:IC.LEVEL_LOAD_ERROR,l=!1;break;case uR:o=n?IC.AUDIO_TRACK_LOAD_TIMEOUT:IC.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case hR:o=n?IC.SUBTITLE_TRACK_LOAD_TIMEOUT:IC.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const d={type:EC.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:s};if(r){const n=(null==t?void 0:t.url)||e.url;d.response=yC({url:n,data:void 0},r)}this.hls.trigger(SC.ERROR,d)}handlePlaylistLoaded(e,t,n,r,s,i){const a=this.hls,{type:o,level:l,id:c,groupId:d,deliveryDirectives:u}=r,h=yR(t,r),f=mR(r),p="number"==typeof r.level&&f===fR?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:e,reason:e.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:n})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const g=e.playlistParsingError;if(g)a.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:g,reason:g.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:n});else switch(e.live&&i&&(i.getCacheAge&&(e.ageHeader=i.getCacheAge()||0),i.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case cR:case dR:a.trigger(SC.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:n,networkDetails:s,deliveryDirectives:u});break;case uR:a.trigger(SC.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:u});break;case hR:a.trigger(SC.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:u})}}}function bR(e,t){let n;try{n=new Event("addtrack")}catch(e){n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=e,t.dispatchEvent(n)}function wR(e,t){const n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(n){RC.debug(`[texttrack-utils]: ${n}`);try{const n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){RC.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===n&&(e.mode=n)}function SR(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function ER(e,t,n,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,n){const r=[],s=function(e,t){if(t<e[0].startTime)return 0;const n=e.length-1;if(t>e[n].endTime)return-1;let r=0,s=n;for(;r<=s;){const i=Math.floor((s+r)/2);if(t<e[i].startTime)s=i-1;else{if(!(t>e[i].startTime&&r<n))return i;r=i+1}}return e[r].startTime-t<t-e[s].startTime?r:s}(e,t);if(s>-1)for(let i=s,a=e.length;i<a;i++){const s=e[i];if(s.startTime>=t&&s.endTime<=n)r.push(s);else if(s.startTime>n)return r}return r}(e.cues,t,n);for(let t=0;t<s.length;t++)r&&!r(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}var IR="org.id3",TR="com.apple.quicktime.HLS",AR="https://aomedia.org/emsg/ID3";function CR(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const _R=(()=>{const e=CR();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function RR(e,t){return e.getTime()/1e3-t}class OR{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(SR(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const n=e[t];if("metadata"===n.kind&&"id3"===n.label)return bR(n,this.media),n}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:r}}}=this;if(!n&&!r)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const i=CR();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===AR&&!n||!r)continue;const a=c_(s[e].data);if(a){const n=s[e].pts;let r=n+s[e].duration;r>_R&&(r=_R);r-n<=0&&(r=n+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!o_(s)){this.updateId3CueEnds(n,t);const e=new i(n,r,"");e.value=s,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var n;const r=null==(n=this.id3Track)?void 0:n.cues;if(r)for(let n=r.length;n--;){const s=r[n];s.type===t&&s.startTime<e&&s.endTime===_R&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=i;if(s&&(a||o)){let e;e="audio"===r?e=>e.type===IR&&o:"video"===r?e=>e.type===AR&&a:e=>e.type===IR&&o||e.type===AR&&a,ER(s,t,n,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:n,id3Track:r}=this,{dateRanges:s}=t,i=Object.keys(s);if(r){const e=Object.keys(n).filter((e=>!i.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(n[s].cues).forEach((e=>{r.removeCue(n[s].cues[e])})),delete n[s]}}const a=t.fragments[t.fragments.length-1];if(0===i.length||!wC(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=CR();for(let e=0;e<i.length;e++){const t=i[e],r=s[t],a=n[t],u=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1;const f=RR(r.startDate,o);let p=_R;const g=r.endDate;if(g)p=RR(g,o),h=!0;else if(r.endOnNext&&!h){const e=i.reduce(((e,t)=>{const n=s[t];return n.class===r.class&&n.id!==t&&n.startDate>r.startDate&&e.push(n),e}),[]).sort(((e,t)=>e.startDate.getTime()-t.startDate.getTime()))[0];e&&(p=RR(e.startDate,o),h=!0)}const m=Object.keys(r.attr);for(let e=0;e<m.length;e++){const n=m[e];if("ID"===(d=n)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;let s=u[n];if(s)h&&!a.durationKnown&&(s.endTime=p);else{let e=r.attr[n];s=new l(f,p,""),DC(n)&&(c=e,e=Uint8Array.from(c.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),s.value={key:n,data:e},s.type=TR,s.id=t,this.id3Track.addCue(s),u[n]=s}}n[t]={cues:u,dateRange:r,durationKnown:h}}var c,d}}class kR{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:i,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&n||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:i*r);const c=r;return l+Math.min(1*this.stallCount,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,n=this.levelDetails;if(null===e||null===t||null===n)return null;const r=n.edge,s=e-t-this.edgeStalled,i=r-n.totalduration,a=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(i,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(SC.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(SC.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var n;t.details===IC.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(n=this.levelDetails)&&n.live&&RC.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const n=this.computeLatency();if(null===n)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s)return;const i=this.targetLatency;if(null===i)return;const a=n-i,o=a<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&o&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),n=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,n))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const PR=["NONE","TYPE-0","TYPE-1",null];var DR="",LR="YES",xR="v2";class MR{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class UR{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>e)).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return null==(e=this.audioGroupIds)?void 0:e[this.urlId]}get textGroupId(){var e;return null==(e=this.textGroupIds)?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function FR(e,t){const n=t.startPTS;if(wC(n)){let r,s=0;t.sn>e.sn?(s=n-e.start,r=e):(s=e.start-n,r=t),r.duration!==s&&(r.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function NR(e,t,n,r,s,i){r-n<=0&&(RC.warn("Fragment should have a positive duration",t),r=n+t.duration,i=s+t.duration);let a=n,o=r;const l=t.startPTS,c=t.endPTS;if(wC(l)){const e=Math.abs(l-n);wC(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(n,l),n=Math.min(n,l),s=Math.min(s,t.startDTS),o=Math.min(r,c),r=Math.max(r,c),i=Math.max(i,t.endDTS)}const d=n-t.start;0!==t.start&&(t.start=n),t.duration=r-t.start,t.startPTS=n,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=i;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let h;const f=u-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)FR(p[h],p[h-1]);for(h=f;h<p.length-1;h++)FR(p[h],p[h+1]);return e.fragmentHint&&FR(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function BR(e,t){let n=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){n=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,i=0;if(function(e,t,n){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,i=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=i;e++){const s=l[a+e];let i=o[e];r&&!i&&e<r&&(i=t.fragments[e]=s),s&&i&&n(s,i)}}(e,t,((e,r)=>{e.relurl&&(i=e.cc-r.cc),wC(e.startPTS)&&wC(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,r.urlId=e.urlId,e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)})),n){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){RC.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,n){const r=bC({},e);n&&n.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const n=new LC(t[e].attr,r[e]);n.isValid?r[e]=n:RC.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(i){RC.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=i}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,n){if(e&&t){let r=0;for(let s=0,i=e.length;s<=i;s++){const i=e[s],a=t[s+r];i&&a&&i.index===a.index&&i.fragment.sn===a.fragment.sn?n(i,a):r--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?NR(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):jR(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function jR(e,t){const n=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;n<0||n>=r.length||$R(t,r[n].start)}function $R(e,t){if(t){const n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function qR(e,t,n){var r;return null!=e&&e.details?KR(null==(r=e.details)?void 0:r.partList,t,n):null}function KR(e,t,n){if(e)for(let r=e.length;r--;){const s=e[r];if(s.index===n&&s.fragment.sn===t)return s}return null}function GR(e){switch(e.details){case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_TIMEOUT:case IC.LEVEL_LOAD_TIMEOUT:case IC.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function WR(e,t){const n=GR(t);return e.default[(n?"timeout":"error")+"Retry"]}function HR(e,t){const n="linear"===e.backoff?1:Math.pow(2,t);return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function VR(e){return yC(yC({},e),{errorRetry:null,timeoutRetry:null})}function YR(e,t,n,r){return!!e&&t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(r)||!!n)}const QR=function(e,t){let n=0,r=e.length-1,s=null,i=null;for(;n<=r;){s=(n+r)/2|0,i=e[s];const a=t(i);if(a>0)n=s+1;else{if(!(a<0))return i;r=s-1}}return null};function zR(e,t,n=0,r=0){let s=null;if(e?s=t[e.sn-t[0].sn+1]||null:0===n&&0===t[0].start&&(s=t[0]),s&&0===JR(n,r,s))return s;const i=QR(t,JR.bind(null,n,r));return!i||i===e&&s?s:i}function JR(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function XR(e,t,n){const r=1e3*Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return(n.endProgramDateTime||0)-r>e}var ZR=0,eO=2,tO=5,nO=0,rO=1,sO=2;function iO(e,t,n){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const r=e.details;if(t.details===IC.FRAG_GAP&&r&&t.frag){const e=t.frag.start,n=zR(null,r.fragments,e);if(n&&!n.gap)return!0}if(n&&e.errors.length<n.errors.length){const n=e.errors[e.errors.length-1];if(r&&n.frag&&t.frag&&Math.abs(n.frag.start-t.frag.start)>3*r.targetduration)return!0}return!1}class aO{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=RC.log.bind(RC,`${t}:`),this.warn=RC.warn.bind(RC,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const n=null==t?void 0:t.renditionReports;if(n){let r=-1;for(let s=0;s<n.length;s++){const i=n[s];let a;try{a=new self.URL(i.URI,t.url).href}catch(e){RC.warn(`Could not construct new URL for Rendition Report: ${e}`),a=i.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=n[r],s=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let i=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);i>=0&&e>t.partTarget&&(i+=1)}return new MR(s,i>=0?i:void 0,DR)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,n){const{details:r,stats:s}=t,i=self.performance.now(),a=s.loading.first?Math.max(0,i-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=n&&n.live){if(r.reloaded(n),n&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:"MISSED"}`),n&&r.fragments.length>0&&BR(n,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,i=r.endSN,c=r.lastPartIndex,d=s===i,u=e?0:c;-1!==c?(o=d?i+1:s,l=d?u:c+1):o=i+1;const h=r.age,f=h+r.ageHeader;let p=Math.min(f-r.partTarget,1.5*r.targetduration);if(p>0){if(n&&p>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${p} with playlist age: ${r.age}`),p=0;else{const e=Math.floor(p/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(p%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${p} skip sn ${e} to part ${l}`)}r.tuneInGoal=p}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!d)return void this.loadPlaylist(a)}else r.canBlockReload&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));const c=this.hls.mainForwardBufferInfo,d=c?c.end-c.len:0,u=function(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&n*s>t){const e=1e3*r[r.length-1].duration;e<n&&(n=e)}}else n/=2;return Math.round(n)}(r,1e3*(r.edge-d));r.updated&&i>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=u);let h=this.requestScheduled-i;h=Math.max(0,h),this.log(`reload live playlist ${e} in ${Math.round(h)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),h)}else this.clearTimer()}getDeliveryDirectives(e,t,n,r){let s=function(e,t){const{canSkipUntil:n,canSkipDateRanges:r,endSN:s}=e;return n&&(void 0!==t?t-s:0)<n?r?xR:LR:DR}(e,n);return null!=t&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,s=DR),new MR(n,r,s)}checkRetry(e){const t=e.details,n=GR(e),r=e.errorAction,{action:s,retryCount:i=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===tO||!r.resolved&&s===eO);if(o){var l;if(this.requestScheduled=-1,i>=a.maxNumRetry)return!1;if(n&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=HR(a,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}let oO;class lO extends aO{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const n=[],r={};let s;t.levels.forEach((e=>{var t;const i=e.attrs;-1!==(null==(t=e.audioCodec)?void 0:t.indexOf("mp4a.40.34"))&&(oO||(oO=/chrome|firefox/i.test(navigator.userAgent)),oO&&(e.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:d,SUBTITLES:u}=i,h=`${`${c||"."}-`}${e.bitrate}-${d}-${l}-${o}`;s=r[h],s?s.addFallback(e):(s=new UR(e),r[h]=s,n.push(s)),cO(s,"audio",a),cO(s,"text",u)})),this.filterAndSortMediaOptions(n,t)}filterAndSortMediaOptions(e,t){let n=[],r=[],s=!1,i=!1,a=!1,o=e.filter((({audioCodec:e,videoCodec:t,width:n,height:r,unknownCodecs:o})=>(s||(s=!(!n||!r)),i||(i=!!t),a||(a=!!e),!(null!=o&&o.length)&&(!e||Q_(e,"audio"))&&(!t||Q_(t,"video")))));if((s||i)&&a&&(o=o.filter((({videoCodec:e,width:t,height:n})=>!!e||!(!t||!n)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||Q_(e.audioCodec,"audio"))),dO(n)),t.subtitles&&(r=t.subtitles,dO(r));const l=o.slice(0);o.sort(((e,t)=>e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"]?(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1:e.bitrate!==t.bitrate?e.bitrate-t.bitrate:e.attrs["FRAME-RATE"]!==t.attrs["FRAME-RATE"]?e.attrs.decimalFloatingPoint("FRAME-RATE")-t.attrs.decimalFloatingPoint("FRAME-RATE"):e.attrs.SCORE!==t.attrs.SCORE?e.attrs.decimalFloatingPoint("SCORE")-t.attrs.decimalFloatingPoint("SCORE"):s&&e.height!==t.height?e.height-t.height:0));let c=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){c=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${c.bitrate}`);break}const d=a&&!i,u={levels:o,audioTracks:n,subtitleTracks:r,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:i,altAudio:!d&&n.some((e=>!!e.url))};this.hls.trigger(SC.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const n=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}const n=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,i=t[e],a=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,n===e&&i.details&&r&&s===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${n}${s?" with Pathway "+s:""}`);const o=bC({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete o._attrs,delete o._urlId,this.hls.trigger(SC.LEVEL_SWITCHING,o);const l=i.details;if(!l||l.live){const e=this.switchParams(i.uri,null==r?void 0:r.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===dR&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===fR){const e=this._levels[t.level];void 0!==e&&(e.loadError=0)}}onLevelLoaded(e,t){var n;const{level:r,details:s}=t,i=this._levels[r];var a;if(!i)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===i.fragmentError&&(i.loadError=0),this.playlistLoaded(r,t,i.details)):null!=(n=t.deliveryDirectives)&&n.skip&&(s.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const n=this.currentLevel;if(!n)return;const r=this.hls.audioTracks[t.id].groupId;if(n.audioGroupIds&&n.audioGroupId!==r){let e=-1;for(let t=0;t<n.audioGroupIds.length;t++)if(n.audioGroupIds[t]===r){e=t;break}-1!==e&&e!==n.urlId&&(n.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){const r=n.urlId;let s=n.uri;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const i=n.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${i?" Pathway "+i:""} URI ${r+1}/${n.url.length} ${s}`),this.clearTimer(),this.hls.trigger(SC.LEVEL_LOADING,{url:s,level:t,id:r,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){const n=(e,n)=>n!==t,r=this._levels.filter(((r,s)=>s!==e||(r.url.length>1&&void 0!==t?(r.url=r.url.filter(n),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(n)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(n)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1))));this.hls.trigger(SC.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){t.forEach(((e,t)=>{const{details:n}=e;null!=n&&n.fragments&&n.fragments.forEach((e=>{e.level=t}))})),this._levels=t}}function cO(e,t,n){n&&("audio"===t?(e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds[e.url.length-1]=n):"text"===t&&(e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds[e.url.length-1]=n))}function dO(e){const t={};e.forEach((e=>{const n=e.groupId||"";e.id=t[n]=t[n]||0,t[n]++}))}var uO="NOT_LOADED",hO="APPENDING",fO="PARTIAL",pO="OK";class gO{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.BUFFER_APPENDED,this.onBufferAppended,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.BUFFER_APPENDED,this.onBufferAppended,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const n=this.activePartLists[t];if(n)for(let t=n.length;t--;){const r=n[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:n}=this,r=Object.keys(n);for(let s=r.length;s--;){const i=n[r[s]];if((null==i?void 0:i.body.type)===t&&i.buffered){const t=i.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const i=this.fragments[r];if(!i)return;if(s>=i.body.sn)return;if(!i.buffered&&!i.loaded)return void(i.body.type===n&&this.removeFragment(i.body));const a=i.range[e];a&&a.time.some((e=>{const n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(i.body),n}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:n,part:r}=e;if(!t||"initSegment"===n.sn)return;const s=yO(n),i=this.fragments[s];if(!i||i.buffered&&n.gap)return;const a=!n.relurl;Object.keys(t).forEach((e=>{const s=n.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;i.range[e]=this.getBufferedTimes(n,r,l,o)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),mO(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}removeParts(e,t){const n=this.activePartLists[t];n&&(this.activePartLists[t]=n.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const n=yO(e);let r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,n,r){const s={time:[],partial:n},i=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||i;for(let e=0;e<r.length;e++){const t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(l>=t&&o<=n){s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(i<n&&a>t)s.partial=!0,s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(a,r.end(e))});else if(a<=t)break}return s}getPartialFragment(e){let t,n,r,s=null,i=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const c=o[l];c&&mO(c)&&(n=c.body.start-a,r=c.body.end+a,e>=n&&e<=r&&(t=Math.min(e-n,r-e),i<=t&&(s=c.body,i=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||mO(t))}getState(e){const t=yO(e),n=this.fragments[t];return n?n.buffered?mO(n)?fO:pO:hO:uO}isTimeBuffered(e,t,n){let r,s;for(let i=0;i<n.length;i++){if(r=n.start(i)-this.bufferPadding,s=n.end(i)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:n,part:r}=t;if("initSegment"===n.sn||n.bitrateTest)return;const s=r?null:t,i=yO(n);this.fragments[i]={body:n,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:n,part:r,timeRanges:s}=t;if("initSegment"===n.sn)return;const i=n.type;if(r){let e=this.activePartLists[i];e||(this.activePartLists[i]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,i,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=yO(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,n,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;const o=a.body;o.type!==n||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=yO(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const t=e.sn;this.activePartLists[e.type]=n.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function mO(e){var t,n,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(n=e.range.audio)?void 0:n.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function yO(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const vO=Math.pow(2,17);class bO{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const n=e.url;if(!n)return Promise.reject(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(n?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,i=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(SO(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new i(r),c=wO(e),d=VR(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:vO};e.stats=l.stats,l.load(c,u,{onSuccess:(t,n,r,s)=>{this.resetLoader(e,l);let i=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(i.slice(0,16)),i=i.slice(16)),a({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,r,s,i)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:yC({url:n,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:i}))},onAbort:(t,n,r)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(n,r,s,i)=>{t&&t({frag:e,part:null,payload:s,networkDetails:i})}})}))}loadPart(e,t,n){this.abort();const r=this.config,s=r.fLoader,i=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(SO(e,t));const l=this.loader=e.loader=s?new s(r):new i(r),c=wO(e,t),d=VR(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:vO};t.stats=l.stats,l.load(c,u,{onSuccess:(r,s,i,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:r.data,networkDetails:o};n(c),a(c)},onError:(n,r,s,i)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:yC({url:c.url,data:void 0},n),error:new Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:s,stats:i}))},onAbort:(n,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:n}))},onTimeout:(n,r,s)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:n}))}})}))}updateStatsFromPart(e,t){const n=e.stats,r=t.stats,s=r.total;if(n.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),i=Math.min(Math.round(n.loaded/s),r),a=(r-i)*Math.round(n.loaded/i);n.total=n.loaded+a}else n.total=Math.max(n.loaded,n.total);const i=n.loading,a=r.loading;i.start?i.first+=a.first-a.start:(i.start=a.start,i.first=a.first),i.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function wO(e,t=null){const n=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},s=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(wC(s)&&wC(i)){var a;let t=s,n=i;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=i-s;e%16&&(n=i+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=n}return r}function SO(e,t){const n=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:EC.MEDIA_ERROR,details:IC.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new EO(r)}class EO extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class IO{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[t].loader;if(n){if(e&&e!==n.context.frag.type)return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=IC.KEY_LOAD_ERROR,n,r,s){return new EO({type:EC.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:n,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:n,cc:r}=e;for(let e=0;e<t.length;e++){const s=t[e];if(r<=s.cc&&("initSegment"===n||"initSegment"===s.sn||n<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var n,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const n=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,n))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let a=this.keyUriToKeyInfo[i];if(null!=(n=a)&&n.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[i]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(n);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,n)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(n)}loadKeyHTTP(e,t){const n=this.config,r=new(0,n.loader)(n);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,i)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=n.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{const{frag:a,keyInfo:o,url:l}=n;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(a,IC.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,n,r,s)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,yC({url:a.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,c)}))}resetLoader(e){const{frag:t,keyInfo:n,url:r}=e,s=n.loader;t.keyLoader===s&&(t.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}const TO={length:0,start:()=>0,end:()=>0};class AO{static isBuffered(e,t){try{if(e){const n=AO.getBuffered(e);for(let e=0;e<n.length;e++)if(t>=n.start(e)&&t<=n.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,n){try{if(e){const r=AO.getBuffered(e),s=[];let i;for(i=0;i<r.length;i++)s.push({start:r.start(i),end:r.end(i)});return this.bufferedInfo(s,t,n)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.sort((function(e,t){const n=e.start-t.start;return n||t.end-e.end}));let r=[];if(n)for(let t=0;t<e.length;t++){const s=r.length;if(s){const i=r[s-1].end;e[t].start-i<n?e[t].end>i&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,i=0,a=t,o=t;for(let e=0;e<r.length;e++){const l=r[e].start,c=r[e].end;if(t+n>=l&&t<c)a=l,o=c,i=o-t;else if(t+n<l){s=l;break}}return{len:i,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return RC.log("failed to get media.buffered",e),TO}}}class CO{constructor(e,t,n,r=0,s=-1,i=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=s,this.partial=i}}function _O(e,t){let n=null;for(let r=0,s=e.length;r<s;r++){const s=e[r];if(s&&s.cc===t){n=s;break}}return n}function RO(e,t){if(e){const n=e.start+t;e.start=e.startPTS=n,e.endPTS=n+e.duration}}function OO(e,t){const n=t.fragments;for(let t=0,r=n.length;t<r;t++)RO(n[t],e);t.fragmentHint&&RO(t.fragmentHint,e),t.alignedSliding=!0}function kO(e,t,n){t&&(!function(e,t,n){if(function(e,t,n){return!(!t.details||!(n.endCC>n.startCC||e&&e.cc<n.startCC))}(e,n,t)){const e=function(e,t,n=0){const r=e.fragments,s=t.fragments;if(!s.length||!r.length)return void RC.log("No fragments to align");const i=_O(r,s[0].cc);if(i&&(!i||i.startPTS))return i;RC.log("No frag in previous level to align on")}(n.details,t);e&&wC(e.start)&&(RC.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),OO(e.start,t))}}(e,n,t),!n.alignedSliding&&t.details&&function(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;const n=t.fragments[0].programDateTime,r=e.fragments[0].programDateTime,s=(r-n)/1e3+t.fragments[0].start;s&&wC(s)&&(RC.log(`Adjusting PTS using programDateTime delta ${r-n}ms, sliding:${s.toFixed(3)} ${e.url} `),OO(s,e))}(n,t.details),n.alignedSliding||!t.details||n.skippedSegments||jR(t.details,n))}function PO(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const n=e.fragments,r=t.fragments;if(!n.length||!r.length)return;const s=r[Math.round(r.length/2)-1],i=_O(n,s.cc)||n[Math.round(n.length/2)-1],a=s.programDateTime,o=i.programDateTime;if(null===a||null===o)return;OO((o-a)/1e3-(i.start-s.start),e)}class DO{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class LO{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class xO{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(4*e);return n}initTable(){const e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],s=n[1],i=n[2],a=n[3],o=this.invSubMix,l=o[0],c=o[1],d=o[2],u=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let n=p^p<<1^p<<2^p<<3^p<<4;n=n>>>8^255&n^99,e[f]=n,t[n]=f;const o=h[f],g=h[o],m=h[g];let y=257*h[n]^16843008*n;r[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,i[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*g^257*o^16843008*f,l[n]=y<<24|y>>>8,c[n]=y<<16|y>>>16,d[n]=y<<8|y>>>24,u[n]=y,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const i=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),d=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(a=0;a<i;a++)a<s?y=l[a]=t[a]:(v=y,a%s==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=u[a/s|0]<<24):s>6&&a%s==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-s]^v)>>>0);for(o=0;o<i;o++)a=i-o,v=3&o?l[a]:l[a-4],c[o]=o<4||a<=4?v:f[d[v>>>24]]^p[d[v>>>16&255]]^g[d[v>>>8&255]]^m[d[255&v]],c[o]=c[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,n){const r=this.keySize+6,s=this.invKeySchedule,i=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],c=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(n);let h=u[0],f=u[1],p=u[2],g=u[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,S,E,I,T,A,C,_,R,O,k,P;const D=this.networkToHostOrderSwap;for(;t<m.length;){for(C=D(m[t]),_=D(m[t+1]),R=D(m[t+2]),O=D(m[t+3]),E=C^s[0],I=O^s[1],T=R^s[2],A=_^s[3],k=4,P=1;P<r;P++)v=o[E>>>24]^l[I>>16&255]^c[T>>8&255]^d[255&A]^s[k],b=o[I>>>24]^l[T>>16&255]^c[A>>8&255]^d[255&E]^s[k+1],w=o[T>>>24]^l[A>>16&255]^c[E>>8&255]^d[255&I]^s[k+2],S=o[A>>>24]^l[E>>16&255]^c[I>>8&255]^d[255&T]^s[k+3],E=v,I=b,T=w,A=S,k+=4;v=i[E>>>24]<<24^i[I>>16&255]<<16^i[T>>8&255]<<8^i[255&A]^s[k],b=i[I>>>24]<<24^i[T>>16&255]<<16^i[A>>8&255]<<8^i[255&E]^s[k+1],w=i[T>>>24]<<24^i[A>>16&255]<<16^i[E>>8&255]<<8^i[255&I]^s[k+2],S=i[A>>>24]<<24^i[E>>16&255]<<16^i[I>>8&255]<<8^i[255&T]^s[k+3],y[t]=D(v^h),y[t+1]=D(S^f),y[t+2]=D(w^p),y[t+3]=D(b^g),h=C,f=_,p=R,g=O,t+=4}return y.buffer}}class MO{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?t_(e,0,t-n):e}(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,n){return this.useSoftware?new Promise(((r,s)=>{this.softwareDecrypt(new Uint8Array(e),t,n);const i=this.flush();i?r(i.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,n)}softwareDecrypt(e,t,n){const{currentIV:r,currentResult:s,remainderData:i}=this;this.logOnce("JS AES decrypt"),i&&(e=D_(i,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;r&&(n=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new xO),o.expandKey(t);const l=s;return this.currentResult=o.decrypt(a.buffer,0,n),this.currentIV=t_(a,-16).buffer,l||null}webCryptoDecrypt(e,t,n){const r=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new LO(r,t)),this.fastAesKey.expandKey().then((t=>{if(!r)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new DO(r,new Uint8Array(n)).decrypt(e.buffer,t)})).catch((r=>(RC.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,n))))}onWebCryptoError(e,t,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const n=e.length-e.length%16;return n!==e.length&&(t=t_(e,0,n),this.remainderData=t_(e,n)),t}logOnce(e){this.logEnabled&&(RC.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const UO=function(e){let t="";const n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},FO="STOPPED",NO="IDLE",BO="KEY_LOADING",jO="FRAG_LOADING",$O="FRAG_LOADING_WAITING_RETRY",qO="WAITING_TRACK",KO="PARSING",GO="PARSED",WO="ENDED",HO="ERROR",VO="WAITING_INIT_PTS",YO="WAITING_LEVEL";class QO extends class{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}{constructor(e,t,n,r,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=FO,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=r,this.log=RC.log.bind(RC,`${r}:`),this.warn=RC.warn.bind(RC,`${r}:`),this.hls=e,this.fragmentLoader=new bO(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new MO(e.config),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=FO}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const n=t.partList;if(null!=n&&n.length){const e=n[n.length-1];return AO.isBuffered(this.media,e.start+e.duration/2)}const r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levels[this.levelLastLoaded])?void 0:e.details}onMediaAttached(e,t){const n=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),n.addEventListener("seeking",this.onvseeking),n.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===FO&&this.startLoad(r.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:n,mediaBuffer:r,state:s}=this,i=n?n.currentTime:0,a=AO.bufferInfo(r||n,i,e.maxBufferHole);if(this.log(`media seeking to ${wC(i)?i.toFixed(3):i}, state: ${s}`),this.state===WO)this.resetLoadingState();else if(t){const n=e.maxFragLookUpTolerance,r=t.start-n,s=t.start+t.duration+n;if(!a.len||s<a.start||r>a.end){const e=i>s;(i<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}n&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,this.playlistType,!0),this.lastCurrentTime=i),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=i),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=FO,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const n=this.state;this.fragContextChanged(e)?(n===jO||!this.fragCurrent&&n===KO)&&(this.fragmentTracker.removeFragment(e),this.state=NO):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(SC.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==FO&&this.state!==HO&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:n}=this;if(n.getState(e)===hO){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&n.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===fO&&n.removeFragment(e))}flushMainBuffer(e,t,n=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:n};this.hls.trigger(SC.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:n}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){const i=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw n.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return n.trigger(SC.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:i,tdecrypt:s}}),t.payload=r,t}))}return t})).then((n=>{const{fragCurrent:r,hls:s,levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=NO,t.fragmentError=0,e.data=new Uint8Array(n.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),n.frag===r&&s.trigger(SC.FRAG_BUFFERED,{stats:a,frag:r,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==FO&&this.state!==HO&&(this.warn(t),this.resetFragmentLoading(e))}))}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var n,r,s,i;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===fR?"level":"track"} ${e.level} (frag:[${(null!=(n=e.startPTS)?n:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?UO(AO.getBuffered(a)):"(detached)"})`),this.state=NO,a&&(!this.loadedmetadata&&e.type==fR&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(i=this.fragPrevious)?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:n,part:r,partsLoaded:s}=e,i=!s||0===s.length||s.some((e=>!e)),a=new CO(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!i);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var s;const i=null==t?void 0:t.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&i.encryptedFragments.length&&this.keyLoader.loadClear(e,i.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${i.startSN}-${i.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=BO,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(SC.KEY_LOADED,e),this.state===BO&&(this.state=NO),e})),this.hls.trigger(SC.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=i.partList;if(s&&r){n>e.end&&i.fragmentHint&&(e=i.fragmentHint);const o=this.getNextPart(s,e,n);if(o>-1){const l=s[o];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=jO,c=a?a.then((n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(SC.FRAG_LOADING,{frag:e,part:l,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(s,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${i?"of ["+i.startSN+"-"+i.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),wC(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=jO;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?r:void 0),a]).then((([e])=>(!o&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(SC.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,n,r){return new Promise(((s,i)=>{var a;const o=[],l=null==(a=n.details)?void 0:a.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const i=r.part;this.hls.trigger(SC.FRAG_LOADED,r);const a=qR(n,e.sn,t.index+1)||KR(l,e.sn,t.index+1);if(!a)return s({frag:e,part:i,partsLoaded:o});c(a)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===IC.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(SC.ERROR,t)}else this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==KO)return void(this.fragCurrent||this.state===FO||this.state===HO||(this.state=NO));const{frag:n,part:r,level:s}=t,i=self.performance.now();n.stats.parsing.end=i,r&&(r.stats.parsing.end=i),this.updateLevelTiming(n,r,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:n}=this,{level:r,sn:s,part:i}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=i>-1?qR(a,s,i):null,l=o?o.fragment:function(e,t,n){if(null==e||!e.details)return null;const r=e.details;let s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t?s:t<r.startSN&&n&&n.sn===t?n:null)}(a,s,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,n,r,s){var i;if(!e||this.state!==KO)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=D_(a,o)),null==(i=l)||!i.length)return;const c={type:e.type,frag:t,part:n,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(SC.BUFFER_APPENDING,c),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!AO.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const n=t.currentTime,r=AO.bufferInfo(t,n,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-i,r.end-i),n+i);e.start-a>i&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const n=this.getLoadPosition();return wC(n)?this.getFwdBufferInfoAtPos(e,n,t):null}getFwdBufferInfoAtPos(e,t,n){const{config:{maxBufferHole:r}}=this,s=AO.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const i=this.fragmentTracker.getBufferedFrag(t,n);if(i&&s.nextStart<i.end)return AO.bufferInfo(e,t,Math.max(s.nextStart,r))}return s}getMaxBufferLength(e){const{config:t}=this;let n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,n=e||t.maxBufferLength;return t.maxMaxBufferLength>=n&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=fR){const n=this.fragmentTracker.getAppendedFrag(e,fR);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const n=t.fragments,r=n.length;if(!r)return null;const{config:s}=this,i=n[0].start;let a;if(t.live){const i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(t,n),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=i&&(a=n[0]);if(!a){const n=s.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,n,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const n=this.fragmentTracker.getState(e);return(n===pO||n===fO&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,s){const i=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,i&&e&&!e.gap&&n.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r);if(null!==t&&n.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,n){let r=-1,s=!1,i=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(i=i&&!o.independent,r>-1&&n<o.start)break;const l=o.loaded;l?r=-1:(s||o.independent||i)&&o.fragment===t&&(r=a),s=l}return r}loadedEndOfParts(e,t){const n=e[e.length-1];return n&&t>n.start&&n.loaded}getInitialLiveFragment(e,t){const n=this.fragPrevious;let r=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),r=function(e,t,n){if(null===t||!Array.isArray(e)||!e.length||!wC(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;n=n||0;for(let r=0;r<e.length;++r){const s=e[r];if(XR(t,n,s))return s}return null}(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=n.sn+1;if(s>=e.startSN&&s<=e.endSN){const i=t[s-e.startSN];n.cc===i.cc&&(r=i,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return QR(e,(e=>e.cc<t?1:e.cc>t?-1:0))}(t,n.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){const{config:r}=this;let{fragPrevious:s}=this,{fragments:i,endSN:a}=n;const{fragmentHint:o}=n,l=r.maxFragLookUpTolerance,c=n.partList,d=!!(r.lowLatencyMode&&null!=c&&c.length&&o);let u;if(d&&o&&!this.bitrateTest&&(i=i.concat(o),a=o.sn),e<t){u=zR(s,i,e,e>t-l?0:l)}else u=i[i.length-1];if(u){const e=u.sn-n.startSN,t=this.fragmentTracker.getState(u);if((t===pO||t===fO&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||c[0].fragment.sn>u.sn)){if(s&&u.level===s.level){const t=i[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==pO?t:null}}}return u}synchronizeToLiveEdge(e){const{config:t,media:n}=this;if(!n)return;const r=this.hls.liveSyncPosition,s=n.currentTime,i=e.fragments[0].start,a=e.edge,o=s>=i-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&n.duration>r&&(s<r||!o)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&n.readyState<4||s<a-i)&&(this.loadedmetadata||(this.nextLoadPosition=r),n.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),n.currentTime=r))}}alignPlaylists(e,t){const{levels:n,levelLastLoaded:r,fragPrevious:s}=this,i=null!==r?n[r]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const o=e.fragments[0].start,l=!t,c=e.alignedSliding&&wC(o);if(l||!c&&!o){kO(s,i,e);const n=e.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${a}`),n}return o}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let n=this.startPosition;if(n<t&&(n=-1),-1===n||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,s=r?this.startTimeOffset:e.startTimeOffset;null!==s&&wC(s)?(n=t+s,s<0&&(n+=e.totalduration),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Start time offset ${s} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${n}`),this.startPosition=n):e.live?n=this.hls.liveSyncPosition||t:this.startPosition=n=0,this.lastCurrentTime=n}this.nextLoadPosition=n}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===$O)||(this.state=NO)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;var r;if(this.fragContextChanged(n))return void this.warn(`Frag load error must match current frag to retry ${n.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===IC.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const i=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=i||{};if(i&&a===tO&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:n.level);const r=HR(l,o);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),i.resolved=!0,this.retryDate=self.performance.now()+r,this.state=$O}else l&&i?(this.resetFragmentErrors(e),o<l.maxNumRetry?s||(i.resolved=!0):RC.warn(`${t.details} reached or exceeded max retry (${o})`)):(null==i?void 0:i.action)===eO?this.state=YO:this.state=HO;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===KO||this.state===GO){const t=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,t),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===pR&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==FO&&(this.state=NO)}afterBufferFlushed(e,t,n){if(!e)return;const r=AO.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===WO&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=NO}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(t=this.levelLastLoaded)?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){var s;const i=n.details;if(!i)return void this.warn("level.details undefined");if(Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=r?0:NR(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(SC.LEVEL_PTS_UPDATED,{details:i,level:n,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1))n.fragmentError=0;else if(null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===n.fragmentError&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=GO,this.hls.trigger(SC.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){var t,n,r;"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(t=null!=(n=this.levelLastLoaded)?n:null==(r=this.fragCurrent)?void 0:r.level)?t:0),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function zO(){return self.SourceBuffer||self.WebKitSourceBuffer}function JO(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class XO{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&(e=D_(this.cachedData,e),this.cachedData=null);let n,r=s_(e,0),s=r?r.length:0;const i=this._audioTrack,a=this._id3Track,o=r?(e=>{const t=c_(e);for(let e=0;e<t.length;e++){const n=t[e];if(o_(n))return p_(n)}})(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&wC(o))&&(this.basePTS=ZO(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:IR,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(i,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,n=s):s=l}else a_(e,s)?(r=s_(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:IR,duration:Number.POSITIVE_INFINITY}),s+=r.length,n=s):s++;if(s===l&&n!==l){const t=t_(e,n);this.cachedData?this.cachedData=D_(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:JO(),id3Track:a,textTrack:JO()}}demuxSampleAes(e,t,n){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:JO(),id3Track:this._id3Track,textTrack:JO()}}destroy(){}}const ZO=(e,t,n)=>{if(wC(e))return 90*e;return 9e4*t+(n?9e4*n.baseTime/n.timescale:0)};function ek(e,t){return 255===e[t]&&240==(246&e[t+1])}function tk(e,t){return 1&e[t+1]?7:9}function nk(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function rk(e,t){return t+1<e.length&&ek(e,t)}function sk(e,t){if(rk(e,t)){const n=tk(e,t);if(t+n>=e.length)return!1;const r=nk(e,t);if(r<=n)return!1;const s=t+r;return s===e.length||rk(e,s)}return!1}function ik(e,t,n,r,s){if(!e.samplerate){const i=function(e,t,n,r){let s,i,a,o;const l=navigator.userAgent.toLowerCase(),c=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[n+2])>>>6);const u=(60&t[n+2])>>>2;if(!(u>d.length-1))return a=(1&t[n+2])<<2,a|=(192&t[n+3])>>>6,RC.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),i=u-3):(s=2,o=new Array(2),i=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),i=u):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?i=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),i=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&i)>>1,o[2]=(1&i)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${u}`})}(t,n,r,s);if(!i)return;e.config=i.config,e.samplerate=i.samplerate,e.channelCount=i.channelCount,e.codec=i.codec,e.manifestCodec=i.manifestCodec,RC.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function ak(e){return 9216e4/e}function ok(e,t,n,r,s){const i=r+s*ak(e.samplerate),a=function(e,t){const n=tk(e,t);if(t+n<=e.length){const r=nk(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}(t,n);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,c=Math.max(0,n+l-t.length);c?(o=new Uint8Array(l-s),o.set(t.subarray(n+s,t.length),0)):o=t.subarray(n+s,n+l);const d={unit:o,pts:i};return c||e.samples.push(d),{sample:d,length:l,missing:c}}const l=t.length-n;o=new Uint8Array(l),o.set(t.subarray(n,t.length),0);return{sample:{unit:o,pts:i},length:l,missing:-1}}const lk=/\/emsg[-/]ID3/i;let ck=null;const dk=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],uk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hk=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fk=[0,1,1,4];function pk(e,t,n,r,s){if(n+24>t.length)return;const i=gk(t,n);if(i&&n+i.frameLength<=t.length){const a=r+s*(9e4*i.samplesPerFrame/i.sampleRate),o={unit:t.subarray(n,n+i.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(o),{sample:o,length:i.frameLength,missing:0}}}function gk(e,t){const n=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,i=e[t+2]>>2&3;if(1!==n&&0!==s&&15!==s&&3!==i){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*dk[14*(3===n?3-r:3===r?3:4)+s-1],c=uk[3*(3===n?0:2===n?1:2)+i],d=3===o?1:2,u=hk[n][r],h=fk[r],f=8*u*h,p=Math.floor(u*l/c+a)*h;if(null===ck){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ck=e?parseInt(e[1]):0}return!!ck&&ck<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:d,frameLength:p,samplesPerFrame:f}}}function mk(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function yk(e,t){return t+1<e.length&&mk(e,t)}function vk(e,t){if(t+1<e.length&&mk(e,t)){const n=4,r=gk(e,t);let s=n;null!=r&&r.frameLength&&(s=r.frameLength);const i=t+s;return i===e.length||yk(e,i)}return!1}class bk{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(n,n+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const n=this.word>>>32-t;if(e>32&&RC.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,n=8,r=8;for(let s=0;s<e;s++)0!==r&&(t=this.readEG(),r=(n+t+256)%256),n=0===r?n:r}readSPS(){let e,t,n,r=0,s=0,i=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();const g=o();if(l(5),u(3),o(),f(),100===g||110===g||122===g||244===g||44===g||83===g||86===g||118===g||128===g){const e=c();if(3===e&&u(1),f(),f(),u(1),d())for(t=3!==e?8:12,n=0;n<t;n++)d()&&p(n<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(u(1),h(),h(),e=c(),n=0;n<e;n++)h();f(),u(1);const y=c(),v=c(),b=l(1);0===b&&u(1),u(1),d()&&(r=c(),s=c(),i=c(),a=c());let w=[1,1];if(d()&&d()){switch(o()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+a),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class wk{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new MO(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,n){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),i=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(i).then((s=>{const i=new Uint8Array(s);r.set(i,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}))}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length)return void n();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,n=new Int8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){const n=new Uint8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,s){const i=U_(s.data),a=this.getAvcEncryptedData(i);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(i,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}))}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,n=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(n>=s.length);n++){const i=s[n];if(!(i.data.length<=48||1!==i.type&&5!==i.type||(this.decryptAvcSample(e,t,n,r,i),this.decrypter.isSync())))return}}}}const Sk=188;class Ek{constructor(e,t,n){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=n}static probe(e){const t=Ek.syncOffset(e);return t>0&&RC.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let n=Math.min(940,e.length-Sk)+1,r=0;for(;r<n;){let s=!1,i=-1,a=0;for(let o=r;o<t;o+=Sk){if(71!==e[o]){if(a)return-1;break}if(a++,-1===i&&(i=o,0!==i&&(n=Math.min(i+18612,e.length-Sk)+1)),s||(s=0===Tk(e,o)),s&&a>1&&(0===i&&a>2||o+Sk>n))return i}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:S_[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,n,r){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Ek.createTrack("video"),this._audioTrack=Ek.createTrack("audio",r),this._id3Track=Ek.createTrack("id3"),this._txtTrack=Ek.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=n,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,n=!1,r=!1){let s;n||(this.sampleAes=null);const i=this._avcTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let c=i.pid,d=i.pesData,u=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=D_(this.remainderData,e)).length,this.remainderData=null),v<Sk&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};const b=Math.max(0,Ek.syncOffset(e));v-=(v-b)%Sk,v<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let w=0;for(let t=b;t<v;t+=Sk)if(71===e[t]){const r=!!(64&e[t+1]),v=Tk(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+Sk)continue}else w=t+4;switch(v){case c:r&&(d&&(s=_k(d))&&this.parseAVCPES(i,l,s,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(w,t+Sk)),d.size+=t+Sk-w);break;case u:if(r){if(f&&(s=_k(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+Sk)),f.size+=t+Sk-w);break;case h:r&&(p&&(s=_k(p))&&this.parseID3PES(o,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+Sk)),p.size+=t+Sk-w);break;case 0:r&&(w+=e[w]+1),y=this._pmtId=Ak(e,w);break;case y:{r&&(w+=e[w]+1);const s=Ck(e,w,this.typeSupported,n);c=s.avc,c>0&&(i.pid=c),u=s.audio,u>0&&(a.pid=u,a.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(o.pid=h),null===g||m||(RC.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=v}}else w++;if(w>0){const e=new Error(`Found ${w} TS packet/s that do not start with 0x47`);this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=d,a.pesData=f,o.pesData=p;const S={audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:n,id3Track:r,textTrack:s}=e,i=n.pesData,a=t.pesData,o=r.pesData;let l;if(i&&(l=_k(i))?(this.parseAVCPES(n,s,l,!0),n.pesData=null):n.pesData=i,a&&(l=_k(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&RC.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=_k(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,n){const r=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new wk(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((n=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{n(e)})):n(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{n(e)}))}))}destroy(){this._duration=0}parseAVCPES(e,t,n,r){const s=this.parseAVCNALu(e,n.data);let i,a=this.avcSample,o=!1;n.data=null,a&&s.length&&!e.audFound&&(Rk(a,e),a=this.avcSample=Ik(!1,n.pts,n.dts,"")),s.forEach((r=>{var s;switch(r.type){case 1:{let t=!1;i=!0;const s=r.data;if(o&&s.length>4){const e=new bk(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=a)&&l.frame&&!a.key&&(Rk(a,e),a=this.avcSample=null);a||(a=this.avcSample=Ik(!0,n.pts,n.dts,"")),a.frame=!0,a.key=t;break}case 5:i=!0,null!=(s=a)&&s.frame&&!a.key&&(Rk(a,e),a=this.avcSample=null),a||(a=this.avcSample=Ik(!0,n.pts,n.dts,"")),a.key=!0,a.frame=!0;break;case 6:i=!0,M_(r.data,1,n.pts,t.samples);break;case 7:if(i=!0,o=!0,!e.sps){const t=r.data,n=new bk(t).readSPS();e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t],e.duration=this._duration;const s=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break;case 8:i=!0,e.pps||(e.pps=[r.data]);break;case 9:i=!1,e.audFound=!0,a&&Rk(a,e),a=this.avcSample=Ik(!1,n.pts,n.dts,"");break;case 12:i=!0;break;default:i=!1,a&&(a.debug+="unknown NAL "+r.type+" ")}if(a&&i){a.units.push(r)}})),r&&a&&(Rk(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let n,r=this.avcSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;n=e[e.length-1]}return n}parseAVCNALu(e,t){const n=t.byteLength;let r=e.naluState||0;const s=r,i=[];let a,o,l,c=0,d=-1,u=0;for(-1===r&&(d=0,u=31&t[0],r=0,c=1);c<n;)if(a=t[c++],r)if(1!==r)if(a)if(1===a){if(d>=0){const e={data:t.subarray(d,c-r-1),type:u};i.push(e)}else{const n=this.getLastNalUnit(e.samples);if(n&&(s&&c<=4-s&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-s)),o=c-r-1,o>0)){const e=new Uint8Array(n.data.byteLength+o);e.set(n.data,0),e.set(t.subarray(0,o),n.data.byteLength),n.data=e,n.state=0}}c<n?(l=31&t[c],d=c,u=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(d>=0&&r>=0){const e={data:t.subarray(d,n),type:u,state:r};i.push(e)}if(0===i.length){const n=this.getLastNalUnit(e.samples);if(n){const e=new Uint8Array(n.data.byteLength+t.byteLength);e.set(n.data,0),e.set(t,n.data.byteLength),n.data=e}}return e.naluState=r,i}parseAACPES(e,t){let n=0;const r=this.aacOverFlow;let s,i,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+o.byteLength);e.set(r.sample.unit,0),e.set(o,s),o=e}else{const i=s-t;r.sample.unit.set(o.subarray(0,t),i),e.samples.push(r.sample),n=r.missing}}for(s=n,i=o.length;s<i-1&&!rk(o,s);s++);if(s!==n){let e;const t=s<i-1;e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES";const n=new Error(e);if(RC.warn(`parsing error: ${e}`),this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:n,reason:e}),!t)return}if(ik(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!r)return void RC.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=ak(e.samplerate);a=r.sample.pts+t}}let l,c=0;for(;s<i;){if(l=ok(e,o,s,a,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!rk(o,s);s++);}}parseMPEGPES(e,t){const n=t.data,r=n.length;let s=0,i=0;const a=t.pts;if(void 0!==a)for(;i<r;)if(yk(n,i)){const t=pk(e,n,i,a,s);if(!t)break;i+=t.length,s++}else i++;else RC.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void RC.warn("[tsdemuxer]: ID3 PES unknown PTS");const n=bC({},t,{type:this._avcTrack?AR:IR,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function Ik(e,t,n,r){return{key:e,frame:!1,pts:t,dts:n,units:[],debug:r,length:0}}function Tk(e,t){return((31&e[t+1])<<8)+e[t+2]}function Ak(e,t){return(31&e[t+10])<<8|e[t+11]}function Ck(e,t,n,r){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},i=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<i;){const i=Tk(e,t);switch(e[t]){case 207:if(!r){RC.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===s.audio&&(s.audio=i);break;case 21:-1===s.id3&&(s.id3=i);break;case 219:if(!r){RC.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===s.avc&&(s.avc=i);break;case 3:case 4:!0!==n.mpeg&&!0!==n.mp3?RC.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:RC.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function _k(e){let t,n,r,s,i,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;){const e=new Uint8Array(o[0].length+o[1].length);e.set(o[0]),e.set(o[1],o[0].length),o[0]=e,o.splice(1,1)}t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(n=(t[4]<<8)+t[5],n&&n>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(i=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-i>54e5&&(RC.warn(`${Math.round((s-i)/9e4)}s delta between PTS and DTS, align them`),s=i)):i=s),r=t[8];let c=r+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,n=o.length;e<n;e++){t=o[e];let n=t.byteLength;if(c){if(c>n){c-=n;continue}t=t.subarray(c),n-=c,c=0}d.set(t,a),a+=n}return n&&(n-=r+3),{data:d,pts:s,dts:i,len:n}}return null}function Rk(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const n=t.samples,r=n.length;if(!r)return void t.dropped++;{const t=n[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&RC.log(e.pts+"/"+e.dts+":"+e.debug)}class Ok{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const kk=Math.pow(2,32)-1;class Pk{static init(){let e;for(e in Pk.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Pk.types)Pk.types.hasOwnProperty(e)&&(Pk.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Pk.HDLR_TYPES={video:t,audio:n};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Pk.STTS=Pk.STSC=Pk.STCO=s,Pk.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Pk.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Pk.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Pk.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Pk.FTYP=Pk.box(Pk.types.ftyp,i,o,i,a),Pk.DINF=Pk.box(Pk.types.dinf,Pk.box(Pk.types.dref,r))}static box(e,...t){let n=8,r=t.length;const s=r;for(;r--;)n+=t[r].byteLength;const i=new Uint8Array(n);for(i[0]=n>>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=255&n,i.set(e,4),r=0,n=8;r<s;r++)i.set(t[r],n),n+=t[r].byteLength;return i}static hdlr(e){return Pk.box(Pk.types.hdlr,Pk.HDLR_TYPES[e])}static mdat(e){return Pk.box(Pk.types.mdat,e)}static mdhd(e,t){t*=e;const n=Math.floor(t/(kk+1)),r=Math.floor(t%(kk+1));return Pk.box(Pk.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Pk.box(Pk.types.mdia,Pk.mdhd(e.timescale,e.duration),Pk.hdlr(e.type),Pk.minf(e))}static mfhd(e){return Pk.box(Pk.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Pk.box(Pk.types.minf,Pk.box(Pk.types.smhd,Pk.SMHD),Pk.DINF,Pk.stbl(e)):Pk.box(Pk.types.minf,Pk.box(Pk.types.vmhd,Pk.VMHD),Pk.DINF,Pk.stbl(e))}static moof(e,t,n){return Pk.box(Pk.types.moof,Pk.mfhd(e),Pk.traf(n,t))}static moov(e){let t=e.length;const n=[];for(;t--;)n[t]=Pk.trak(e[t]);return Pk.box.apply(null,[Pk.types.moov,Pk.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(Pk.mvex(e)))}static mvex(e){let t=e.length;const n=[];for(;t--;)n[t]=Pk.trex(e[t]);return Pk.box.apply(null,[Pk.types.mvex,...n])}static mvhd(e,t){t*=e;const n=Math.floor(t/(kk+1)),r=Math.floor(t%(kk+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Pk.box(Pk.types.mvhd,s)}static sdtp(e){const t=e.samples||[],n=new Uint8Array(4+t.length);let r,s;for(r=0;r<t.length;r++)s=t[r].flags,n[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Pk.box(Pk.types.sdtp,n)}static stbl(e){return Pk.box(Pk.types.stbl,Pk.stsd(e),Pk.box(Pk.types.stts,Pk.STTS),Pk.box(Pk.types.stsc,Pk.STSC),Pk.box(Pk.types.stsz,Pk.STSZ),Pk.box(Pk.types.stco,Pk.STCO))}static avc1(e){let t,n,r,s=[],i=[];for(t=0;t<e.sps.length;t++)n=e.sps[t],r=n.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(n));for(t=0;t<e.pps.length;t++)n=e.pps[t],r=n.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(n));const a=Pk.box(Pk.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),o=e.width,l=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return Pk.box(Pk.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Pk.box(Pk.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Pk.box(Pk.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return Pk.box(Pk.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]),Pk.box(Pk.types.esds,Pk.esds(e)))}static mp3(e){const t=e.samplerate;return Pk.box(Pk.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?Pk.box(Pk.types.stsd,Pk.STSD,Pk.mp3(e)):Pk.box(Pk.types.stsd,Pk.STSD,Pk.mp4a(e)):Pk.box(Pk.types.stsd,Pk.STSD,Pk.avc1(e))}static tkhd(e){const t=e.id,n=e.duration*e.timescale,r=e.width,s=e.height,i=Math.floor(n/(kk+1)),a=Math.floor(n%(kk+1));return Pk.box(Pk.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const n=Pk.sdtp(e),r=e.id,s=Math.floor(t/(kk+1)),i=Math.floor(t%(kk+1));return Pk.box(Pk.types.traf,Pk.box(Pk.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Pk.box(Pk.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i])),Pk.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Pk.box(Pk.types.trak,Pk.tkhd(e),Pk.mdia(e))}static trex(e){const t=e.id;return Pk.box(Pk.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const n=e.samples||[],r=n.length,s=12+16*r,i=new Uint8Array(s);let a,o,l,c,d,u;for(t+=8+s,i.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<r;a++)o=n[a],l=o.duration,c=o.size,d=o.flags,u=o.cts,i.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Pk.box(Pk.types.trun,i)}static initSegment(e){Pk.types||Pk.init();const t=Pk.moov(e),n=new Uint8Array(Pk.FTYP.byteLength+t.byteLength);return n.set(Pk.FTYP),n.set(t,Pk.FTYP.byteLength),n}}Pk.types=void 0,Pk.HDLR_TYPES=void 0,Pk.STTS=void 0,Pk.STSC=void 0,Pk.STCO=void 0,Pk.STSZ=void 0,Pk.VMHD=void 0,Pk.SMHD=void 0,Pk.STSD=void 0,Pk.FTYP=void 0,Pk.DINF=void 0;function Dk(e,t,n=1,r=!1){const s=e*t*n;return r?Math.round(s):s}function Lk(e,t=!1){return Dk(e,1e3,1/9e4,t)}let xk,Mk=null,Uk=null;class Fk{constructor(e,t,n,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,null===Mk){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mk=e?parseInt(e[1]):0}if(null===Uk){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Uk=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){RC.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){RC.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){RC.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const n=e.reduce(((e,n)=>{const r=n.pts-e;return r<-4294967296?(t=!0,Nk(e,n.pts)):r>0?e:n.pts}),e[0].pts);return t&&RC.debug("PTS rollover detected"),n}remux(e,t,n,r,s,i,a,o){let l,c,d,u,h,f,p=s,g=s;const m=e.pid>-1,y=t.pid>-1,v=t.samples.length,b=e.samples.length>0,w=a&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||a){this.ISGenerated||(d=this.generateIS(e,t,s,i));const n=this.isVideoContiguous;let r,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){RC.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,r=g}else-1===a&&(RC.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const n=this.getVideoStartPts(t.samples),r=(Nk(e.samples[0].pts,n)-n)/t.inputTimeScale;p+=Math.max(0,r),g+=Math.max(0,-r)}if(b){if(e.samplerate||(RC.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||o===pR?g:void 0),w){const r=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(RC.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,i)),l=this.remuxVideo(t,g,n,r)}}else w&&(l=this.remuxVideo(t,g,n,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(h=Bk(n,s,this._initPTS,this._initDTS)),r.samples.length&&(u=jk(r,s,this._initPTS))),{audio:c,video:l,initSegment:d,independent:f,text:u,id3:h}}generateIS(e,t,n,r){const s=e.samples,i=t.samples,a=this.typeSupported,o={},l=this._initPTS;let c,d,u,h=!l||r,f="audio/mp4";if(h&&(c=d=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Pk.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(u=e.inputTimeScale,l&&u===l.timescale?h=!1:c=d=s[0].pts-Math.round(u*n))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Pk.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(u=t.inputTimeScale,l&&u===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(u*n);d=Math.min(d,Nk(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(o).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:u},this._initDTS={baseTime:d,timescale:u}):c=u=void 0,{tracks:o,initPTS:c,timescale:u}}remuxVideo(e,t,n,r){const s=e.inputTimeScale,i=e.samples,a=[],o=i.length,l=this._initPTS;let c,d,u=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!n||null===u){u=t*s-(i[0].pts-Nk(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<o;e++){const t=i[e];t.pts=Nk(t.pts-y,u),t.dts=Nk(t.dts-y,u),t.dts<i[e>0?e-1:e].dts&&(m=!0)}m&&i.sort((function(e,t){const n=e.dts-t.dts,r=e.pts-t.pts;return n||r})),c=i[0].dts,d=i[i.length-1].dts;const v=d-c,b=v?Math.round(v/(o-1)):f||e.inputTimeScale/30;if(n){const e=c-u,t=e>b,n=e<-1;if((t||n)&&(t?RC.warn(`AVC: ${Lk(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):RC.warn(`AVC: ${Lk(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!n||u>=i[0].pts)){c=u;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,RC.log(`Video: First PTS/DTS adjusted: ${Lk(t,!0)}/${Lk(c,!0)}, delta: ${Lk(e,!0)} ms`)}}c=Math.max(0,c);let w=0,S=0;for(let e=0;e<o;e++){const t=i[e],n=t.units,r=n.length;let s=0;for(let e=0;e<r;e++)s+=n[e].data.length;S+=s,w+=r,t.length=s,t.dts=Math.max(t.dts,c),p=Math.min(t.pts,p),g=Math.max(t.pts,g)}d=i[o-1].dts;const E=S+4*w+8;let I;try{I=new Uint8Array(E)}catch(e){return void this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MUX_ERROR,details:IC.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating video mdat ${E}`})}const T=new DataView(I.buffer);T.setUint32(0,E),I.set(Pk.types.mdat,4);let A=!1,C=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=i[e],n=t.units;let l,c=0;for(let e=0,t=n.length;e<t;e++){const t=n[e],r=t.data,s=t.data.byteLength;T.setUint32(h,s),h+=4,I.set(r,h),h+=s,c+=4+s}if(e<o-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const n=this.config,a=e>0?t.dts-i[e-1].dts:b;if(l=e>0?t.pts-i[e-1].pts:b,n.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(n.maxBufferHole*s),i=(r?p+r*s:this.nextAudioPts)-t.pts;i>e?(f=i-a,f<0?f=a:A=!0,RC.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(t.pts-t.dts);C=Math.min(C,f),R=Math.max(R,f),_=Math.min(_,l),O=Math.max(O,l),a.push(new $k(t.key,f,c,d))}if(a.length)if(Mk){if(Mk<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Uk&&O-_<R-C&&b/R<.025&&0===a[0].cts){RC.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,n=a.length;t<n;t++){const r=e+a[t].duration,s=e+a[t].cts;if(t<n-1){const e=r+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=r}}f=A||!f?b:f,this.nextAvcDts=u=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const k={data1:Pk.moof(e.sequenceNumber++,c,bC({},e,{samples:a})),data2:I,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,k}remuxAudio(e,t,n,r,s){const i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),o="aac"===e.segmentCodec?1024:1152,l=o*a,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==s;let f=e.samples,p=d?0:8,g=this.nextAudioPts||-1;const m=t*i,y=c.baseTime*i/c.timescale;if(this.isAudioContiguous=n=n||f.length&&g>0&&(r&&Math.abs(m-g)<9e3||Math.abs(Nk(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=Nk(e.pts-y,m)})),!n||g<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;g=0===s?0:r&&!h?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let n=0,r=g;n<f.length;n++){const s=f[n],a=s.pts,o=a-r,c=Math.abs(1e3*o/i);if(o<=-t*l&&h)0===n&&(RC.warn(`Audio frame @ ${(a/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/i)} ms.`),this.nextAudioPts=g=r=a);else if(o>=t*l&&c<1e4&&h){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===n&&(this.nextAudioPts=g=r),RC.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/i).toFixed(3)}s due to ${Math.round(1e3*o/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(r,0);let i=Ok.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(RC.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),i=s.unit.subarray()),f.splice(n,0,{unit:i,pts:t}),r+=l,n++}}s.pts=r,r+=l}}let v,b=null,w=null,S=0,E=f.length;for(;E--;)S+=f[E].unit.byteLength;for(let t=0,r=f.length;t<r;t++){const r=f[t],s=r.unit;let i=r.pts;if(null!==w){u[t-1].duration=Math.round((i-w)/a)}else{if(n&&"aac"===e.segmentCodec&&(i=g),b=i,!(S>0))return;S+=p;try{v=new Uint8Array(S)}catch(e){return void this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MUX_ERROR,details:IC.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(v.buffer).setUint32(0,S),v.set(Pk.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,u.push(new $k(!0,o,l,0)),w=i}const I=u.length;if(!I)return;const T=u[u.length-1];this.nextAudioPts=g=w+a*T.duration;const A=d?new Uint8Array(0):Pk.moof(e.sequenceNumber++,b/a,bC({},e,{samples:u}));e.samples=[];const C=b/i,_=g/i,R={data1:A,data2:v,startPTS:C,endPTS:_,startDTS:C,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,R}remuxEmptyAudio(e,t,n,r){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,c=(null!==a?a:r.startDTS*s)+l,d=r.endDTS*s+l,u=1024*i,h=Math.ceil((d-c)/u),f=Ok.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(RC.warn("[mp4-remuxer]: remux empty Audio"),!f)return void RC.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const p=[];for(let e=0;e<h;e++){const t=c+e*u;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,n,!1)}}function Nk(e,t){let n;if(null===t)return e;for(n=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=n;return e}function Bk(e,t,n,r){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let a=0;a<s;a++){const s=e.samples[a];s.pts=Nk(s.pts-n.baseTime*i/n.timescale,t*i)/i,s.dts=Nk(s.dts-r.baseTime*i/r.timescale,t*i)/i}const a=e.samples;return e.samples=[],{samples:a}}function jk(e,t,n){const r=e.samples.length;if(!r)return;const s=e.inputTimeScale;for(let i=0;i<r;i++){const r=e.samples[i];r.pts=Nk(r.pts-n.baseTime*s/n.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const i=e.samples;return e.samples=[],{samples:i}}class $k{constructor(e,t,n,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=n,this.cts=r,this.flags=new qk(e)}}class qk{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}function Kk(e,t){const n=null==e?void 0:e.codec;return n&&n.length>4?n:"hvc1"===n||"hev1"===n?"hvc1.1.6.L120.90":"av01"===n?"av01.0.04M.08":"avc1"===n||t===UC?"avc1.42e01e":"mp4a.40.5"}try{xk=self.performance.now.bind(self.performance)}catch(e){RC.debug("Unable to use Performance API on this environment"),xk="undefined"!=typeof self&&self.Date.now}const Gk=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,n,r){const s=this.videoTrack=JO("video",1),i=this.audioTrack=JO("audio",1),a=this.txtTrack=JO("text",1);if(this.id3Track=JO("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=O_(e);if(o.video){const{id:e,timescale:t,codec:n}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=n}if(o.audio){const{id:e,timescale:t,codec:n}=o.audio;i.id=e,i.timescale=t,i.codec=n}a.id=S_.text,s.sampleDuration=0,s.duration=i.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return __(e=e.length>16384?e.subarray(0,16384):e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let n=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=D_(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},n=__(e,["moof"]);if(!n)return t;if(n.length<2)return t.remainder=e,t;const r=n[n.length-1];return t.valid=t_(e,0,r.byteOffset-8),t.remainder=t_(e,r.byteOffset-8),t}(n);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=n;const i=this.extractID3Track(r,t);return s.samples=L_(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:i,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return n.samples=L_(e,t),{videoTrack:t,audioTrack:JO(),id3Track:r,textTrack:JO()}}extractID3Track(e,t){const n=this.id3Track;if(e.samples.length){const r=__(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let n="",r="",s=0,i=0,a=0,o=0,l=0,c=0;if(0===t){for(;"\0"!==E_(e.subarray(c,c+1));)n+=E_(e.subarray(c,c+1)),c+=1;for(n+=E_(e.subarray(c,c+1)),c+=1;"\0"!==E_(e.subarray(c,c+1));)r+=E_(e.subarray(c,c+1)),c+=1;r+=E_(e.subarray(c,c+1)),c+=1,s=T_(e,12),i=T_(e,16),o=T_(e,20),l=T_(e,24),c=28}else if(1===t){c+=4,s=T_(e,c),c+=4;const t=T_(e,c);c+=4;const i=T_(e,c);for(c+=4,a=2**32*t+i,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,RC.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=T_(e,c),c+=4,l=T_(e,c),c+=4;"\0"!==E_(e.subarray(c,c+1));)n+=E_(e.subarray(c,c+1)),c+=1;for(n+=E_(e.subarray(c,c+1)),c+=1;"\0"!==E_(e.subarray(c,c+1));)r+=E_(e.subarray(c,c+1)),c+=1;r+=E_(e.subarray(c,c+1)),c+=1}return{schemeIdUri:n,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:o,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(lk.test(r.schemeIdUri)){const e=wC(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const i=r.payload;n.samples.push({data:i,len:i.byteLength,dts:e,pts:e,type:AR,duration:s})}}))}return n}demuxSampleAes(e,t,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(function(e,t){if(!e||!t)return e;const n=t.keyId;n&&t.isCommonEncryption&&__(e,["moov","trak"]).forEach((e=>{const t=__(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=__(t,["enca"]);const s=r.length>0;s||(r=__(t,["encv"])),r.forEach((e=>{__(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=k_(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(RC.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${v_(e)} -> ${v_(n)}`),t.set(n,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:n}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=O_(e);t||(t=Kk(r.audio,MC)),n||(n=Kk(r.video,UC));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+n,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:RC.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,n,r,s,i){var a,o;let{initPTS:l,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};wC(c)||(c=this.lastEndTime=s||0);const u=t.samples;if(null==u||!u.length)return d;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return RC.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let n=0,r=0,s=0;const i=__(e,["moof","traf"]);for(let e=0;e<i.length;e++){const a=i[e],o=__(a,["tfhd"])[0],l=t[T_(o,4)];if(!l)continue;const c=l.default,d=T_(o,0)|(null==c?void 0:c.flags);let u=null==c?void 0:c.duration;8&d&&(u=T_(o,2&d?12:8));const h=l.timescale||9e4,f=__(a,["trun"]);for(let e=0;e<f.length;e++)n=P_(f[e]),!n&&u&&(n=u*T_(f[e],4)),l.type===UC?r+=n/h:l.type===MC&&(s+=n/h)}if(0===r&&0===s){let t=0;const n=__(e,["sidx"]);for(let e=0;e<n.length;e++){const r=R_(n[e]);null!=r&&r.references&&(t+=r.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return r||s}(u,f),g=function(e,t){return __(t,["moof","traf"]).reduce(((t,n)=>{const r=__(n,["tfdt"])[0],s=r[0],i=__(n,["tfhd"]).reduce(((t,n)=>{const i=T_(n,4),a=e[i];if(a){let e=T_(r,4);if(1===s){if(e===b_)return RC.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=b_+1,e+=T_(r,8)}const n=e/(a.timescale||9e4);if(isFinite(n)&&(null===t||n<t))return n}return t}),null);return null!==i&&isFinite(i)&&(null===t||i<t)?i:t}),null)}(f,u),m=null===g?s:g;(function(e,t,n,r){if(null===e)return!0;const s=Math.max(r,1),i=t-e.baseTime/e.timescale;return Math.abs(i-n)>s}(l,m,s,p)||h.timescale!==l.timescale&&i)&&(h.initPTS=m-s,l&&1===l.timescale&&RC.warn("Adjusting initPTS by "+(h.initPTS-l.baseTime)),this.initPTS=l={baseTime:h.initPTS,timescale:1});const y=e?m-l.baseTime/l.timescale:c,v=y+p;!function(e,t,n){__(t,["moof","traf"]).forEach((t=>{__(t,["tfhd"]).forEach((r=>{const s=T_(r,4),i=e[s];if(!i)return;const a=i.timescale||9e4;__(t,["tfdt"]).forEach((e=>{const t=e[0];let r=T_(e,4);if(0===t)r-=n*a,r=Math.max(r,0),C_(e,4,r);else{r*=Math.pow(2,32),r+=T_(e,8),r-=n*a,r=Math.max(r,0);const t=Math.floor(r/(b_+1)),s=Math.floor(r%(b_+1));C_(e,4,t),C_(e,8,s)}}))}))}))}(f,u,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(RC.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,w=!!f.video;let S="";b&&(S+="audio"),w&&(S+="video");const E={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:S,hasAudio:b,hasVideo:w,nb:1,dropped:0};return d.audio="audio"===E.type?E:void 0,d.video="audio"!==E.type?E:void 0,d.initSegment=h,d.id3=Bk(n,s,l,l),r.samples.length&&(d.text=jk(r,s,l)),d}}},{demux:Ek,remux:Fk},{demux:class extends XO{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(s_(e,0)||[]).length;for(let n=e.length;t<n;t++)if(sk(e,t))return RC.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&ek(e,t)&&nk(e,t)<=e.length-t}(e,t)}appendFrame(e,t,n){ik(e,this.observer,t,n,e.manifestCodec);const r=ok(e,t,n,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Fk},{demux:class extends XO{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(s_(e,0)||[]).length;for(let n=e.length;t<n;t++)if(vk(e,t))return RC.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return mk(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,n){if(null!==this.basePTS)return pk(e,t,n,this.basePTS,this.frameIndex)}},remux:Fk}];class Wk{constructor(e,t,n,r,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.vendor=r,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){const s=n.transmuxing;s.executeStart=xk();let i=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=r||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=o,b=function(e,t){let n=null;e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(n=t);return n}(i,t);if(b&&"AES-128"===b.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(i,b.key.buffer,b.iv.buffer).then((e=>{const t=this.push(e,null,n);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(i,b.key.buffer,b.iv.buffer);if(n.part>-1&&(t=e.flush()),!t)return s.executeEnd=xk(),Hk(n);i=new Uint8Array(t)}}const w=this.needsProbing(c,d);if(w){const e=this.configureTransmuxer(i);if(e)return RC.warn(`[transmuxer] ${e.message}`),this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=xk(),Hk(n)}(c||d||f||w)&&this.resetInitSegment(v,p,g,y,t),(c||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(i,b,h,u,n),E=this.currentTransmuxState;return E.contiguous=!0,E.discontinuity=!1,E.trackSwitch=!1,s.executeEnd=xk(),S}flush(e){const t=e.transmuxing;t.executeStart=xk();const{decrypter:n,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:a}=r;if(n){const t=n.flush();t&&i.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=xk(),[Hk(e)];const c=o.flush(a);return Vk(c)?c.then((t=>(this.flushRemux(i,t,e),i))):(this.flushRemux(i,c,e),i)}flushRemux(e,t,n){const{audioTrack:r,videoTrack:s,id3Track:i,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;RC.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const c=this.remuxer.remux(r,s,i,a,l,o,!0,this.id);e.push({remuxResult:c,chunkMeta:n}),n.transmuxing.executeEnd=xk()}resetInitialTimestamp(e){const{demuxer:t,remuxer:n}=this;t&&n&&(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,s){const{demuxer:i,remuxer:a}=this;i&&a&&(i.resetInitSegment(e,t,n,r),a.resetInitSegment(e,t,n,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,n,r,s){let i;return i=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,n,r,s):this.transmuxUnencrypted(e,n,r,s),i}transmuxUnencrypted(e,t,n,r){const{audioTrack:s,videoTrack:i,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,a,o,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,s){return this.demuxer.demuxSampleAes(e,t,n).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:n,typeSupported:r,vendor:s}=this;let i;for(let t=0,n=Gk.length;t<n;t++)if(Gk[t].demux.probe(e)){i=Gk[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,c=i.demux;o&&o instanceof l||(this.remuxer=new l(n,t,r,s)),a&&a instanceof c||(this.demuxer=new c(n,t,r),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new MO(this.config)),e}}const Hk=e=>({remuxResult:{},chunkMeta:e});function Vk(e){return"then"in e&&e.then instanceof Function}class Yk{constructor(e,t,n,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=s||null}}class Qk{constructor(e,t,n,r,s,i){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=i}}var zk={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,i||e,a),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,a=new Array(i);s<i;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,s,i,a){var o=n?n+e:e;if(!this._events[o])return!1;var l,c,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,i),!0;case 6:return d.fn.call(d.context,t,r,s,i,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,f=d.length;for(c=0;c<f;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,r);break;case 4:d[c].fn.call(d[c].context,t,r,s);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},o.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},o.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},o.prototype.removeListener=function(e,t,r,s){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return a(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||s&&!o.once||r&&o.context!==r||a(this,i);else{for(var l=0,c=[],d=o.length;l<d;l++)(o[l].fn!==t||s&&!o[l].once||r&&o[l].context!==r)&&c.push(o[l]);c.length?this._events[i]=1===c.length?c[0]:c:a(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o}(zk);var Jk=fC(zk.exports);const Xk=H_()||{isTypeSupported:()=>!1};class Zk{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;const i=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===SC.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Jk,this.observer.on(SC.FRAG_DECRYPTED,i),this.observer.on(SC.ERROR,i);const a={mp4:Xk.isTypeSupported("video/mp4"),mpeg:Xk.isTypeSupported("audio/mpeg"),mp3:Xk.isTypeSupported('audio/mp4; codecs="mp3"')},o=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(RC.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(RC.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const n=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,RC.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:n})},e.postMessage({cmd:"init",typeSupported:a,vendor:o,id:t,config:JSON.stringify(s)})}catch(e){RC.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new Wk(this.observer,a,s,o,t)}return}}this.transmuxer=new Wk(this.observer,a,s,o,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,n,r,s,i,a,o,l,c){var d,u;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,f=i?i.start:s.start,p=s.decryptdata,g=this.frag,m=!(g&&s.cc===g.cc),y=!(g&&l.level===g.level),v=g?l.sn-g.sn:-1,b=this.part?l.part-this.part.index:-1,w=0===v&&l.id>1&&l.id===(null==g?void 0:g.stats.chunkCount),S=!y&&(1===v||0===v&&(1===b||w&&b<=0)),E=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=E),!i||!b&&S||(i.stats.parsing.start=E);const I=!(g&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=g.initSegment)?void 0:u.url)),T=new Qk(m,S,o,y,f,I);if(!S||m||I){RC.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${I}`);const e=new Yk(n,r,t,a,c);this.configureTransmuxer(e)}if(this.frag=s,this.part=i,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:T},e instanceof ArrayBuffer?[e]:[]);else if(h){const t=h.push(e,p,l,T);Vk(t)?(h.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(h.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let n=t.flush(e);Vk(n)||t.async?(Vk(n)||(n=Promise.resolve(n)),n.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(n,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data,n=this.hls;switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":RC[t.data.logType]&&RC[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,n.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class eP{constructor(e,t,n,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=n,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:n,media:r,stalled:s}=this;if(null===r)return;const{currentTime:i,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;RC.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!AO.getBuffered(r).length)return;const c=AO.bufferInfo(r,i,0),d=c.len>0,u=c.nextStart||0;if(!d&&!u)return;if(a){const e=c.len>2,n=!u||t&&t.start<=i||u-i>2&&!this.fragmentTracker.getPartialFragment(i);if(e||n)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;const e=Math.max(u,c.start||0)-i,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,n=(null==t||null==(h=t.details)?void 0:h.live)?2*t.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(i);if(e>0&&(e<=n||r))return void this._trySkipBufferHole(r)}const f=self.performance.now();if(null===s)return void(this.stalled=f);const p=f-s;if(!a&&p>=250&&(this._reportStall(c),!this.media))return;const g=AO.bufferInfo(r,i,n.maxBufferHole);this._tryFixBufferStall(g,p)}_tryFixBufferStall(e,t){const{config:n,fragmentTracker:r,media:s}=this;if(null===s)return;const i=s.currentTime,a=r.getPartialFragment(i);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-i<n.maxBufferHole)&&t>1e3*n.highBufferWatchdogPeriod&&(RC.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:n,stallReported:r}=this;if(!r&&n){this.stallReported=!0;const r=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);RC.warn(r.message),t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:n,media:r}=this;if(null===r)return 0;const s=r.currentTime,i=AO.bufferInfo(r,s,0),a=s<i.start?i.start:i.nextStart;if(a){const o=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&r.readyState<3,c=a-s;if(c>0&&(o||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let n=!1;if(0===s){const e=t.getAppendedFrag(0,fR);e&&a<e.end&&(n=!0)}if(!n){const n=e||t.getAppendedFrag(s,fR);if(n){let e=!1,r=n.end;for(;r<a;){const n=t.getPartialFragment(r);if(!n){e=!0;break}r+=n.duration}if(e)return 0}}}const i=Math.max(a+.05,s+.1);if(RC.warn(`skipping hole, adjusting currentTime from ${s} to ${i}`),this.moved=!0,this.stalled=null,r.currentTime=i,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${i}`);n.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return i}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:n,nudgeRetry:r}=this;if(null===n)return;const s=n.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const i=s+(r+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${i}`);RC.warn(a.message),n.currentTime=i,t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);RC.error(n.message),t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}class tP extends QO{constructor(e,t,n){super(e,t,n,"[stream-controller]",fR),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(SC.ERROR,this.onError,this),e.on(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this),e.on(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(SC.ERROR,this.onError,this),e.off(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this),e.off(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=n.startLevel;-1===e&&(n.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=n.nextAutoLevel),this.level=n.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=NO,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=FO}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case YO:{var e;const{levels:t,level:n}=this,r=null==t||null==(e=t[n])?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=NO;break}if(this.hls.nextLoadLevel!==this.level){this.state=NO;break}break}case $O:{var t;const e=self.performance.now(),n=this.retryDate;(!n||e>=n||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=NO)}}this.state===NO&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:n,media:r}=this,{config:s,nextLoadLevel:i}=e;if(null===t||!r&&(this.startFragRequested||!s.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==n||!n[i])return;const a=n[i],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(SC.BUFFER_EOS,e),void(this.state=WO)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=a.details;if(!c||this.state===YO||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=YO);const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==pO){var p;const e=(null!=(p=this.backtrackFragment)?p:f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?MC:UC,t=(e===UC?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,fR)}f=this.getNextFragmentLoopLoading(f,c,o,fR,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===uO||r===fO?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,fR)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let n;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;n=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else n=0;const i=this.getBufferedFrag(t.currentTime+n);if(i){const e=this.followingBufferedFrag(i);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(i.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,.5*n),.75*n));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case BO:case jO:case $O:case KO:case GO:this.state=NO}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const n=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),n.addEventListener("playing",this.onvplaying),n.addEventListener("seeked",this.onvseeked),this.gapController=new eP(this.config,n,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;wC(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const n=this.getMainFwdBufferInfo();null!==n&&0!==n.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${n?n.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(SC.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let n,r=!1,s=!1;t.levels.forEach((e=>{n=e.audioCodec,n&&(-1!==n.indexOf("mp4a.40.2")&&(r=!0),-1!==n.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=r&&s&&!function(){var e;const t=zO();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:n}=this;if(!n||this.state!==NO)return;const r=n[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=YO)}onLevelLoaded(e,t){var n;const{levels:r}=this,s=t.level,i=t.details,a=i.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""}, cc [${i.startCC}, ${i.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==jO&&this.state!==$O||l.level===t.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(n=o.details)&&n.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,o.details)}if(o.details=i,this.levelLastLoaded=s,this.hls.trigger(SC.LEVEL_UPDATED,{details:i,level:s}),this.state===YO){if(this.waitForCdnTuneIn(i))return;this.state=NO}this.startFragRequested?i.live&&this.synchronizeToLiveEdge(i):this.setStartPosition(i,c),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:n,part:r,payload:s}=e,{levels:i}=this;if(!i)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);const a=i[n.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),void this.fragmentTracker.removeFragment(n);const l=a.videoCodec,c=o.PTSKnown||!o.live,d=null==(t=n.initSegment)?void 0:t.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Zk(this.hls,fR,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,p=-1!==f,g=new CO(n.level,n.sn,n.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[n.cc];h.push(s,d,u,l,n,r,o.totalduration,c,g,m)}onAudioTrackSwitching(e,t){const n=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;n&&(e.trigger(SC.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(SC.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const n=t.id,r=!!this.hls.audioTracks[n].url;if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const n=t.tracks;let r,s,i=!1;for(const e in n){const t=n[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=n[e];t&&(this.videoBuffer=t.buffer)}}else i=!0}i&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:n,part:r}=t;if(n&&n.type!==fR)return;if(this.fragContextChanged(n))return this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===GO&&(this.state=NO));const s=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==n.sn&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}onError(e,t){var n;if(t.fatal)this.state=HO;else switch(t.details){case IC.FRAG_GAP:case IC.FRAG_PARSING_ERROR:case IC.FRAG_DECRYPT_ERROR:case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(fR,t);break;case IC.LEVEL_LOAD_ERROR:case IC.LEVEL_LOAD_TIMEOUT:case IC.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==YO||(null==(n=t.context)?void 0:n.type)!==dR||(this.state=NO);break;case IC.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case IC.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!AO.getBuffered(e).length){const e=this.state!==NO?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=NO,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==MC||this.audioOnly&&!this.altAudio){const e=(t===UC?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,fR)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let n=this.startPosition;if(n>=0&&t<n){if(e.seeking)return void this.log(`could not seek to ${n}, already seeking at ${t}`);const r=AO.getBuffered(e),s=(r.length?r.start(0):0)-n;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),this.log(`seek to target start position ${n} from current time ${t}`),e.currentTime=n}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((n=>{const{hls:r}=this;if(!n||this.fragContextChanged(e))return;t.fragmentError=0,this.state=NO,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(SC.FRAG_LOADED,n),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const n="main",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{video:d,text:u,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=KO,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(c,f.tracks,e,i),r.trigger(SC.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;wC(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(SC.INIT_PTS_FOUND,{frag:o,id:n,initPTS:e,timescale:t}))}if(d&&p&&"initSegment"!==o.sn){const e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===i.id&&!n&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!n)return void this.backtrack(o);n&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,r,o.start,a,!0)}o.setElementaryStreamInfo(d.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,i,t||n)}else{if(!t&&!n)return void this.backtrack(o);o.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=g;l&&(l.elementaryStreams[MC]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(MC,e,t,n,r),this.bufferFragmentData(g,o,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:n,frag:o,details:p,samples:h.samples};r.trigger(SC.FRAG_PARSING_METADATA,e)}if(p&&u){const e={id:n,frag:o,details:p,samples:u.samples};r.trigger(SC.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,n,r){if(this.state!==KO)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:a}=t;if(s){let t=e.audioCodec;const n=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===n.indexOf("firefox")&&(t="mp4a.40.5")),-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}i&&(i.levelCodec=e.videoCodec,i.id="main",this.log(`Init video buffer, container:${i.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(SC.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(SC.BUFFER_APPENDING,{type:e,data:s,frag:n,part:null,chunkMeta:r,parent:n.type})})),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,fR)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=NO}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const n=e.currentTime;if(AO.isBuffered(e,n)?t=this.getAppendedFrag(n):AO.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,n=t.level;e&&t.sn===e.sn&&e.level===n&&t.urlId===e.urlId||(this.fragPlaying=t,this.hls.trigger(SC.FRAG_CHANGED,{frag:t}),e&&e.level===n||this.hls.trigger(SC.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,n=this.currentFrag;if(n&&wC(t)&&wC(n.programDateTime)){const e=n.programDateTime+1e3*(t-n.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class nP{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){const n=Math.pow(this.alpha_,e);this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class rP{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new nP(e),this.fast_=new nP(t),this.defaultTTFB_=r,this.ttfb_=new nP(e)}update(e,t){const{slow_:n,fast_:r,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new nP(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new nP(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new nP(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const n=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class sP{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let n;return e.length?(n=1===e.length?e[0]:function(e,t){const n=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}(e,t),this.reset(),n):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function iP(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!aP(e[n].attrs,t[n].attrs))return!1;return!0}function aP(e,t){const n=e["STABLE-RENDITION-ID"];return n?n===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some((n=>e[n]!==t[n]))}class oP{constructor(e){this.buffered=void 0;const t=(t,n,r)=>{if((n>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end:n=>t("end",n,e.length),start:n=>t("start",n,e.length)}}}function lP(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[n])}return t}class cP{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const n=this.queues[t];n.push(e),1===n.length&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const n=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),n}executeNext(e){const{buffers:t,queues:n}=this,r=t[e],s=n[e];if(s.length){const t=s[0];try{t.execute()}catch(n){RC.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),t.onError(n),null!=r&&r.updating||(s.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const dP=H_(),uP=/([ha]vc.)(?:\.[^.,]+)+/;const hP={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},fP=function(e){let t=e;return hP.hasOwnProperty(e)&&(t=hP[e]),String.fromCharCode(t)},pP=15,gP=100,mP={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},yP={17:2,18:4,21:6,22:8,23:10,19:13,20:15},vP={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},bP={25:2,26:4,29:6,30:8,31:10,27:13,28:15},wP=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class SP{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const n="function"==typeof t?t():t;RC.log(`${this.time} [${e}] ${n}`)}}}const EP=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t};class IP{constructor(e,t,n,r,s){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=n||!1,this.background=r||"black",this.flash=s||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let n=0;n<t.length;n++){const r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class TP{constructor(e,t,n,r,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new IP(t,n,r,s,i)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class AP{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<gP;e++)this.chars.push(new TP);this.logger=e,this.pos=0,this.currPenState=new IP}equals(e){let t=!0;for(let n=0;n<gP;n++)if(!this.chars[n].equals(e.chars[n])){t=!1;break}return t}copy(e){for(let t=0;t<gP;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<gP;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>gP&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=gP)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=fP(e);this.pos>=gP?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<gP;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let n=0;n<gP;n++){const r=this.chars[n].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class CP{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<pP;t++)this.rows.push(new AP(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<pP;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<pP;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<pP;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<pP;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<pP;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const r=n.rows[e].cueStartTime,s=this.logger.time;if(r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;const n=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let n="",r=-1;for(let n=0;n<pP;n++){const s=this.rows[n].getTextString();s&&(r=n+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(n=e?"["+t.join(" | ")+"]":t.join("\n")),n}getTextAndFormat(){return this.rows}}class _P{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new CP(n),this.nonDisplayedMemory=new CP(n),this.lastOutputScreen=new CP(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const n=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class RP{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const r=new SP;this.channels=[null,new _P(e,t,r),new _P(e+1,n,r)],this.cmdHistory={a:null,b:null},this.logger=r}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let n,r,s,i=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(r=127&t[e],s=127&t[e+1],0!==r||0!==s){if(this.logger.log(3,"["+EP([t[e],t[e+1]])+"] -> ("+EP([r,s])+")"),n=this.parseCmd(r,s),n||(n=this.parseMidrow(r,s)),n||(n=this.parsePAC(r,s)),n||(n=this.parseBackgroundAttributes(r,s)),!n&&(i=this.parseChars(r,s),i)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(i)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||i||this.logger.log(2,"Couldn't parse cleaned data "+EP([r,s])+" orig: "+EP([t[e],t[e+1]]))}}parseCmd(e,t){const{cmdHistory:n}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(kP(e,t,n))return OP(null,null,n),this.logger.log(3,"Repeated command ("+EP([e,t])+") is dropped"),!0;const r=20===e||21===e||23===e?1:2,s=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),OP(e,t,n),this.currentChannel=r,!0}parseMidrow(e,t){let n=0;if((17===e||25===e)&&t>=32&&t<=47){if(n=17===e?1:2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[n];return!!r&&(r.ccMIDROW(t),this.logger.log(3,"MIDROW ("+EP([e,t])+")"),!0)}return!1}parsePAC(e,t){let n;const r=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(kP(e,t,r))return OP(null,null,r),!0;const s=e<=23?1:2;n=t>=64&&t<=95?1===s?mP[e]:vP[e]:1===s?yP[e]:bP[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(n,t)),OP(e,t,r),this.currentChannel=s,!0)}interpretPAC(e,t){let n;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=1==(1&n),n<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((n-16)/2),r}parseChars(e,t){let n,r=null,s=null;if(e>=25?(n=2,s=e-8):(n=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+fP(e)+"' in channel "+n),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);if(r){const n=EP(r);this.logger.log(3,"Char codes = "+n.join(",")),OP(e,t,this.cmdHistory)}return r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let n;const r={};16===e||24===e?(n=Math.floor((t-32)/2),r.background=wP[n],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),OP(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const n=this.channels[t];n&&n.cueSplitAtTime(e)}}}function OP(e,t,n){n.a=e,n.b=t}function kP(e,t,n){return n.a===e&&n.b===t}class PP{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var DP=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function n(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const n=t.toLowerCase();return!!~e.indexOf(n)&&n}function r(e){return n(t,e)}function s(e,...t){let n=1;for(;n<arguments.length;n++){const t=arguments[n];for(const n in t)e[n]=t[n]}return e}function i(t,i,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let c="",d=!1,u=t,h=i,f=a,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",S=50,E="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return g},set:function(t){const r=function(t){return n(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return v},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return w},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return E},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),o.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class LP{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function xP(e){function t(e,t,n,r){return 3600*(0|e)+60*(0|t)+(0|n)+parseFloat(r||0)}const n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}class MP{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}}function UP(e,t,n,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(n);if(2!==r.length)continue;t(r[0],r[1])}}const FP=new DP(0,0,""),NP="middle"===FP.align?"middle":"center";function BP(e,t,n){const r=e;function s(){const t=xP(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function i(){e=e.replace(/^\s+/,"")}if(i(),t.startTime=s(),i(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),i(),t.endTime=s(),i(),function(e,t){const r=new MP;UP(e,(function(e,t){let s;switch(e){case"region":for(let s=n.length-1;s>=0;s--)if(n[s].id===t){r.set(e,n[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",NP,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",NP,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",NP,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===FP.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",NP);let i=r.get("position","auto");"auto"===i&&50===FP.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function jP(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class $P{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new LP,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function n(){let e=t.buffer,n=0;for(e=jP(e);n<e.length&&"\r"!==e[n]&&"\n"!==e[n];)++n;const r=e.slice(0,n);return"\r"===e[n]&&++n,"\n"===e[n]&&++n,t.buffer=e.slice(n),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=n();const r=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=n(),t.state){case"HEADER":/:/.test(e)?UP(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new DP(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{BP(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const n=-1!==e.indexOf("--\x3e");if(!e||n&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const qP=/\r\n|\n\r|\n|\r/g,KP=function(e,t,n=0){return e.slice(n,n+t.length)===t},GP=function(e){let t=5381,n=e.length;for(;n;)t=33*t^e.charCodeAt(--n);return(t>>>0).toString()};function WP(e,t,n){return GP(e.toString())+GP(t.toString())+GP(n)}function HP(e,t,n,r,s,i,a){const o=new $P,l=g_(new Uint8Array(e)).trim().replace(qP,"\n").split("\n"),c=[],d=t?function(e,t=1){return Dk(e,9e4,1/t)}(t.baseTime,t.timescale):0;let u,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const i=n[r];let a=n.ccOffset;const o=(f-d)/9e4;if(null!=i&&i.new&&(void 0!==p?a=n.ccOffset=i.start:function(e,t,n){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(i=s)&&i.new;){var i;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=n}(n,r,o)),o){if(!t)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-n.presentationOffset}const l=e.endTime-e.startTime,h=Nk(9e4*(e.startTime+a-p),9e4*s)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=WP(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},o.onparsingerror=function(e){u=e},o.onflush=function(){u?a(u):i(c)},l.forEach((e=>{if(g){if(KP(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{KP(e,"LOCAL:")?h=e.slice(6):KP(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(wC(t)&&wC(n)&&wC(r)&&wC(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=6e4*r,t+=36e5*s,t}(h)/1e3}catch(e){u=e}return}""===e&&(g=!1)}o.parse(e+"\n")})),o.flush()}const VP="stpp.ttml.im1t",YP=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,QP=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zP={left:"start",center:"center",right:"end",start:"start",end:"end"};function JP(e,t,n,r){const s=__(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>g_(e))),a=function(e,t,n=1,r=!1){return Dk(e,t,1/n,r)}(t.baseTime,1,t.timescale);try{i.forEach((e=>n(function(e,t){const n=new DOMParser,r=n.parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=ZP(XP(r,"styling","style")),l=ZP(XP(r,"layout","region")),c=XP(r,"body","[begin]");return[].map.call(c,(e=>{const n=eD(e,a);if(!n||!e.hasAttribute("begin"))return null;const r=rD(e.getAttribute("begin"),i),s=rD(e.getAttribute("dur"),i);let c=rD(e.getAttribute("end"),i);if(null===r)throw nD(e);if(null===c){if(null===s)throw nD(e);c=r+s}const d=new DP(r-t,c-t,n);d.id=WP(d.startTime,d.endTime,d.text);const u=function(e,t,n){const r="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&n.hasOwnProperty(a)&&(s=n[a]);return i.reduce(((n,i)=>{const a=tD(t,r,i)||tD(e,r,i)||tD(s,r,i);return a&&(n[i]=a),n}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=u;if(h){const e=zP[h];e&&(d.lineAlign=e),d.align=h}return bC(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function XP(e,t,n){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function ZP(e){return e.reduce(((e,t)=>{const n=t.getAttribute("xml:id");return n&&(e[n]=t),e}),{})}function eD(e,t){return[].slice.call(e.childNodes).reduce(((e,n,r)=>{var s;return"br"===n.nodeName&&r?e+"\n":null!=(s=n.childNodes)&&s.length?eD(n,t):t?e+n.textContent.trim().replace(/\s+/g," "):e+n.textContent}),"")}function tD(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function nD(e){return new Error(`Could not parse ttml timestamp ${e}`)}function rD(e,t){if(!e)return null;let n=xP(e);return null===n&&(YP.test(e)?n=function(e,t){const n=YP.exec(e),r=(0|n[4])+(0|n[5])/t.subFrameRate;return 3600*(0|n[1])+60*(0|n[2])+(0|n[3])+r/t.frameRate}(e,t):QP.test(e)&&(n=function(e,t){const n=QP.exec(e),r=Number(n[1]);switch(n[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),n}function sD(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class iD{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(SC.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(SC.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){const n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const n=t.filter(((t,n)=>this.isLevelAllowed(t)&&n<=e));return this.clientRect=null,iD.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,t.width||t.height||(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,n){if(null==e||!e.length)return-1;let r=e.length-1;for(let a=0;a<e.length;a+=1){const o=e[a];if((o.width>=t||o.height>=n)&&(s=o,!(i=e[a+1])||s.width!==i.width||s.height!==i.height)){r=a;break}}var s,i;return r}}const aD="[eme]";class oD{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=oD.CDMCleanupPromise?[oD.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=RC.debug.bind(RC,aD),this.log=RC.log.bind(RC,aD),this.warn=RC.warn.bind(RC,aD),this.error=RC.error.bind(RC,aD),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(SC.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(SC.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===WC.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,n=t[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(n),s=t.map((e=>e.videoCodec)).filter(n);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,n)=>{const i=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?i(e):n(t instanceof lD?t:new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};i(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:n}=this.config;if("function"!=typeof n){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return null===e_&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){const r=function(e,t,n,r){let s;switch(e){case WC.FAIRPLAY:s=["cenc","sinf"];break;case WC.WIDEVINE:case WC.PLAYREADY:s=["cenc"];break;case WC.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:n.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,n,r)}(e,t,n,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let i=null==s?void 0:s.keySystemAccess;if(!i){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),i=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:i};return i.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),i.then((n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=n.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((n=>n?this.setMediaKeysServerCertificate(t,e,n):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return i.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${v_(e.keyId||[])}`);const r=n.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const n=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return v_(e.keyId)}updateKeySession(e,t){var n;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${v_((null==(n=e.decryptdata)?void 0:n.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,n)=>{const r=ZC(this.config),s=e.map(zC).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=XC(e);r?t(r):n(new Error(`Unable to find format for key-system "${e}"`))})).catch(n)}))}loadKey(e){const t=e.keyInfo.decryptdata,n=this.getKeyIdString(t),r=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[n];return s||(s=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(t).then((({keySystem:n,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(n,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:n,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof lD?this.hls.trigger(SC.ERROR,e.data):this.hls.trigger(SC.ERROR,{type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[t];if(!n){const t=zC(e.keyFormat),n=t?[t]:ZC(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=ZC(this.config)),0===e.length)throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:n}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===n)return;let r,s;if("sinf"===t&&this.config.drmSystems[WC.FAIRPLAY]){const e=E_(new Uint8Array(n));try{const t=qC(JSON.parse(e).sinf),n=k_(new Uint8Array(t));if(!n)return;r=n.subarray(8,24),s=WC.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},n=new DataView(e),r=n.getUint32(0);if(e.byteLength!==r&&r>44)return null;if(1886614376!==n.getUint32(4))return null;if(t.version=n.getUint32(8)>>>24,t.version>1)return null;t.systemId=v_(new Uint8Array(e,12,16));const s=n.getUint32(28);if(0===t.version){if(r-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let n=0;n<s;n++)t.kids.push(new Uint8Array(e,32+16*n,16))}return t}(n);if(null===e)return;0===e.version&&e.systemId===JC&&e.data&&(r=e.data.subarray(8,24)),s=function(e){if(e===JC)return WC.WIDEVINE}(e.systemId)}if(!s||!r)return;const i=v_(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[i];for(let e=0;e<o.length;e++){const s=o[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const d=v_(c.keyId);if(i===d||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=a[d],delete a[d],c.pssh=new Uint8Array(n),c.keyId=r,l=a[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,n,"encrypted-event-key-match")));break}}l||(l=a[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new B_("ISO-23001-7",i,null!=(a=XC(e))?a:"");return o.pssh=new Uint8Array(n),o.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,n,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(n).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===n.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,n,r){var s,i;const a=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(a)try{const r=a.call(this.hls,t,n,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,n=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===n)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${n?n.byteLength:null})`);const c=new Jk;e.mediaKeysSession.onmessage=t=>{const n=e.mediaKeysSession;if(!n)return void c.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),c.emit("error",e)})):"license-release"===r?e.keySystem===WC.FAIRPLAY&&(this.updateKeySession(e,GC("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const n=e.keyStatus;c.emit("keyStatus",n),"expired"===n&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};const d=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(n=>{n.startsWith("usable")?e():"output-restricted"===n?t(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===n?t(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${n}"`)):"expired"===n?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${n}"`)}))}));return e.mediaKeysSession.generateRequest(t,n).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>d)).catch((t=>{throw c.removeAllListeners(),this.removeSession(e),t})).then((()=>(c.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,n)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${v_("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${v_(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,n=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise(((s,i)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{s(e.data)},onError:(t,n,s,o)=>{i(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:yC({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,s)=>{i(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,n)=>{i(new Error("aborted"))}};n.load(a,l,c)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise(((r,s)=>{e.setServerCertificate(n).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==n?void 0:n.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}setupLicenseXHR(e,t,n,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!n.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,n,r)})).catch((i=>{if(!n.decryptdata)throw i;return e.open("POST",t,!0),s.call(this.hls,e,t,n,r)})).then((n=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:n||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const n=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const i=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${i}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,a,i,e)}catch(e){this.error(e)}r(t)}else{const o=n.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:i,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${i}). Status: ${a.status} (${a.statusText})`));else{const n=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,i,e,t).then((({xhr:e,licenseChallenge:t})=>{e.send(t)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const n=t.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},B_.clearKeyUriToKeyIdMap();const n=t.length;oD.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)})))).then((()=>{n&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:n}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}oD.CDMCleanupPromise=void 0;class lD extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var cD="m",dD="a",uD="v",hD="av",fD="i",pD="tt";class gD{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:cD,su:!this.initialized})}catch(e){RC.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,n=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};r!==uD&&r!==dD&&r!=hD||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){RC.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:n}=t;null!=n&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||gD.uuid(),this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHED,this.onMediaDetached,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHED,this.onMediaDetached,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var n,r;this.audioBuffer=null==(n=t.tracks.audio)?void 0:n.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){bC(t,this.createData());const n=t.ot===fD||t.ot===uD||t.ot===hD;if(this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const n=gD.toHeaders(t);if(!Object.keys(n).length)return;e.headers||(e.headers={}),bC(e.headers,n)}else{const n=gD.toQuery(t);if(!n)return;e.url=gD.appendQueryToUri(e.url,n)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?pD:"initSegment"===e.sn?fD:"audio"===t?dD:"main"===t?this.hls.audioTracks.length?uD:hD:void 0}getTopBandwidth(e){let t,n=0;const r=this.hls;if(e===dD)t=r.audioTracks;else{const e=r.maxAutoLevel,n=e>-1?e+1:r.levels.length;t=r.levels.slice(0,n)}for(const e of t)e.bitrate>n&&(n=e.bitrate);return n>0?n:NaN}getBufferLength(e){const t=this.hls.media,n=e===dD?this.audioBuffer:this.videoBuffer;if(!n||!t)return NaN;return 1e3*AO.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],n=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,r=e=>Math.round(e),s=e=>100*r(e/100),i={br:r,d:r,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:r},a=Object.keys(e||{}).sort();for(const r of a){let s=e[r];if(!n(s))continue;if("v"===r&&1===s)continue;if("pr"==r&&1===s)continue;const a=i[r];a&&(s=a(s));const o=typeof s;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${s}`:"boolean"===o?r:"number"===o?`${r}=${s}`:`${r}=${JSON.stringify(s)}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),n={},r=["Object","Request","Session","Status"],s=[{},{},{},{}],i={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const n of t){s[null!=i[n]?i[n]:1][n]=e[n]}for(let e=0;e<s.length;e++){const t=gD.serialize(s[e]);t&&(n[`CMCD-${r[e]}`]=t)}return n}static toQuery(e){return`CMCD=${encodeURIComponent(gD.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const n=e.includes("?")?"&":"?";return`${e}${n}${t}`}}function mD(e,t,n,r){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=bC({},e);return i.details=void 0,i.attrs=new PC(i.attrs),i.url=i.attrs.URI=yD(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),i.groupId=i.attrs["GROUP-ID"]=t[s],i.attrs["PATHWAY-ID"]=r,i}));e.push(...i)}))}function yD(e,t,n,r){const{HOST:s,PARAMS:i,[n]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const vD=/^age:\s*[\d.]+\s*$/im;class bD{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new xC,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(!this.stats.aborted)return s(n,t.url)})).catch((e=>(n.open("GET",t.url,!0),s(n,t.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(n,t,e)})).catch((e=>{this.callbacks.onError({code:n.status,text:e.message},t,n,r)})):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open("GET",t.url,!0);const r=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:i}=n.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=s&&wC(s)?s:i,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:n}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!n.aborted&&r>=2&&(0===n.loading.first&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,i="text"!==t.responseType;if(r>=200&&r<300&&(i&&t.response||null!==t.responseText)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const s=i?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(n.loaded=n.total=a,n.bwEstimate=8e3*n.total/(n.loading.end-n.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(n,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,n,e,t)}else{const i=s.loadPolicy.errorRetry;YR(i,n.retry,!1,r)?this.retry(i):(RC.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,n))}}}loadtimeout(){var e;const t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(YR(t,this.stats.retry,!0))this.retry(t);else{RC.warn(`timeout while loading ${this.context.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:n}=this;this.retryDelay=HR(e,n.retry),n.retry++,RC.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&vD.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const wD=/(\d+)-(\d+)\/(\d+)/;class SD{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||ED,this.controller=new self.AbortController,this.stats=new xC}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;null!=e&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(bC({},e.headers))};e.rangeEnd&&n.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return n}(e,this.controller.signal),i=n.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&wC(l)?l:c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),n.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),n.onTimeout(r,e,this.response)}),c-(o-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new ID(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=wD.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(wC(e))return e}const n=e.get("Content-Length");if(n)return parseInt(n)}(s.headers)||r.total,i&&wC(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,i):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const c={url:a.url,data:s,code:a.status};i&&!wC(t.highWaterMark)&&i(r,e,s,a),n.onSuccess(c,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,i=t?t.message:null;n.onError({code:s,text:i},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,s){const i=new sP,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return i.dataLength&&s(t,n,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,c=l.length;return t.loaded+=c,c<r||i.dataLength?(i.push(l),i.dataLength>=r&&s(t,n,i.flush(),e)):s(t,n,l,e),o()})).catch((()=>Promise.reject()));return o()}}function ED(e,t){return new self.Request(e.url,t)}class ID extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}}const TD=/\s/,AD={newCue(e,t,n,r){const s=[];let i,a,o,l,c;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(i=r.rows[h],o=!0,l=0,c="",!i.isEmpty()){var u;for(let e=0;e<i.chars.length;e++)TD.test(i.chars[e].uchar)&&o?l++:(c+=i.chars[e].uchar,o=!1);i.cueStartTime=t,t===n&&(n+=1e-4),l>=16?l--:l++;const r=jP(c.trim()),f=WP(t,n,r);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new d(t,n,r),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>wR(e,t)))),s}},CD=yC(yC({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:bD,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new rP(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(SC.FRAG_LOADING,this.onFragLoading,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.FRAG_LOADING,this.onFragLoading,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var n;const r=t.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const n=this.hls.config,{total:r,bwEstimate:s}=t.stats;wC(r)&&wC(s)&&(this.lastLevelLoadSec=8*r/s),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:n}=this,{autoLevelEnabled:r,media:s}=n;if(!e||!s)return;const i=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=i-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||0===e.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const c=n.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const h=c.len/u;if(h>=2*o/u)return;const f=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=n,v=m[e.level],b=a.total||Math.max(a.loaded,Math.round(o*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*a.loaded/g));const S=p?1e3*a.loaded/w:0,E=S?(b-a.loaded)/S:8*b/g+d/1e3;if(E<=h)return;const I=S?8*S:g;let T,A=Number.POSITIVE_INFINITY;for(T=e.level-1;T>y;T--){const e=m[T].maxBitrate;if(A=this.getTimeToLoadFrag(d/1e3,I,o*e,!m[T].details),A<h)break}A>=E||A>10*o||(n.nextLoadLevel=T,p?this.bwEstimator.sample(l-Math.min(d,f),a.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),RC.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${h.toFixed(3)} s\n Estimated load time for current fragment: ${E.toFixed(3)} s\n Estimated load time for down switch fragment: ${A.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${wC(g)?(g/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${T}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),n.trigger(SC.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:n}){const r=n?n.stats:t.stats;if(t.type===fR&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const e=n?n.duration:t.duration,s=this.hls.levels[t.level],i=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:a},s.realBitrate=Math.round(8*i/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(SC.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:n,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:n.stats;if(s.aborted)return;if(this.ignoreFragment(n))return;const i=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(i,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),n.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==fR||"initSegment"===e.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(-1!==e&&!t.canEstimate())return e;let n=this.getNextABRAutoLevel();if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,n)&&t[e].loadError<=t[n].loadError)return e}return-1!==e&&(n=Math.min(e,n)),n}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:n}=this,{maxAutoLevel:r,config:s,minAutoLevel:i,media:a}=n,o=t?t.duration:e?e.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,d=n.mainForwardBufferInfo,u=(d?d.len:0)/l;let h=this.findBestLevel(c,i,r,u,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;RC.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!u){const e=this.bitrateTestDelay;if(e){f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-e,RC.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),p=g=1}}return h=this.findBestLevel(c,i,r,u+f,p,g),Math.max(h,0)}findBestLevel(e,t,n,r,s,i){var a;const{fragCurrent:o,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:d}=this.hls,u=d[c],h=!(null==u||null==(a=u.details)||!a.live),f=null==u?void 0:u.codecSet,p=l?l.duration:o?o.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let a=n;a>=t;a--){const t=d[a];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(a,m),y=Math.max(a,y));continue}-1!==y&&RC.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${d[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const n=t.details,o=(l?null==n?void 0:n.partTarget:null==n?void 0:n.averagetargetduration)||p;let v;v=a<=c?s*e:i*e;const b=d[a].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*o,void 0===n);if(RC.trace(`[abr] level:${a} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${o.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!wC(w)||h&&!this.bitrateTestDelay||w<r))return a}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;RC.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(SC.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{RC.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{RC.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&RC.error(`Media element src was set while attaching MediaSource (${t} > ${e.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.BUFFER_RESET,this.onBufferReset,this),e.on(SC.BUFFER_APPENDING,this.onBufferAppending,this),e.on(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.on(SC.BUFFER_EOS,this.onBufferEos,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(SC.FRAG_PARSED,this.onFragParsed,this),e.on(SC.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.BUFFER_RESET,this.onBufferReset,this),e.off(SC.BUFFER_APPENDING,this.onBufferAppending,this),e.off(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.off(SC.BUFFER_EOS,this.onBufferEos,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(SC.FRAG_PARSED,this.onFragParsed,this),e.off(SC.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new cP(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,RC.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const n=this.media=t.media;if(n&&dP){const e=this.mediaSource=new dP;e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),n.src=self.URL.createObjectURL(e),this._objectUrl=n.src,n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:n}=this;if(t){if(RC.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){RC.warn(`[buffer-controller]: onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),e.src===n?(e.removeAttribute("src"),e.load()):RC.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(SC.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(t){RC.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}})),this._initSourceBuffer()}onBufferCodecs(e,t){const n=this.getSourceBufferTypes().length;Object.keys(t).forEach((e=>{if(n){const n=this.tracks[e];if(n&&"function"==typeof n.buffer.changeType){const{id:r,codec:s,levelCodec:i,container:a,metadata:o}=t[e],l=(n.levelCodec||n.codec).replace(uP,"$1"),c=(i||s).replace(uP,"$1");if(l!==c){const t=`${a};codecs=${i||s}`;this.appendChangeType(e,t),RC.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:n.buffer,codec:s,container:a,levelCodec:i,metadata:o,id:r}}}}else this.pendingTracks[e]=t[e]})),n||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:n}=this,r={execute:()=>{const r=this.sourceBuffer[e];r&&(RC.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{RC.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}};n.append(r,e)}onBufferAppending(e,t){const{hls:n,operationQueue:r,tracks:s}=this,{data:i,type:a,frag:o,part:l,chunkMeta:c}=t,d=c.buffering[a],u=self.performance.now();d.start=u;const h=o.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=u),f&&0===f.start&&(f.start=u);const p=s.audio;let g=!1;"audio"===a&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=o.start,y={execute:()=>{if(d.executeStart=self.performance.now(),g){const e=this.sourceBuffer[a];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(RC.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===h.first&&(h.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,n={};for(const e in t)n[e]=AO.getBuffered(t[e]);this.appendError=0,this.hls.trigger(SC.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:n})},onError:e=>{RC.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,e);const t={type:EC.MEDIA_ERROR,parent:o.type,details:IC.BUFFER_APPEND_ERROR,frag:o,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=IC.BUFFER_FULL_ERROR:(this.appendError++,t.details=IC.BUFFER_APPEND_ERROR,this.appendError>n.config.appendErrorMaxRetry&&(RC.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),n.trigger(SC.ERROR,t)}};r.append(y,a)}onBufferFlushing(e,t){const{operationQueue:n}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(SC.BUFFER_FLUSHED,{type:e})},onError:t=>{RC.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?n.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{n.append(r(e),e)}))}onFragParsed(e,t){const{frag:n,part:r}=t,s=[],i=r?r.elementaryStreams:n.elementaryStreams;i[FC]?s.push("audiovideo"):(i[MC]&&s.push("audio"),i[UC]&&s.push("video"));0===s.length&&RC.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers((()=>{const e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:n.stats;this.hls.trigger(SC.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})}),s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){const n=this.getSourceBufferTypes().reduce(((e,n)=>{const r=this.sourceBuffer[n];return!r||t.type&&t.type!==n||(r.ending=!0,r.ended||(r.ended=!0,RC.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0);n&&(RC.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(RC.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&RC.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:n,sourceBuffer:r}=this;if(!n||null===t)return;const s=this.getSourceBufferTypes();if(!s.length)return;const i=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(!wC(i)||i<0)return;const a=n.currentTime,o=t.levelTargetDuration,l=Math.max(i,o),c=Math.floor(a/o)*o-l;s.forEach((n=>{const s=r[n];if(s){const r=AO.getBuffered(s);if(r.length>0&&c>r.start(0)){if(e.trigger(SC.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(SC.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&r.end(r.length-1)-a<2*o)return void RC.info(`[buffer-controller]: Cannot flush ${n} back buffer while SourceBuffer is in ended state`);e.trigger(SC.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:n})}}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:n,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,i=n.duration,a=wC(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(RC.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>i||!wC(i))&&(RC.log(`[buffer-controller]: Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){const t=this.mediaSource,n=e.fragments;if(n.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,n[0].start),s=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:n}=this,r=Object.keys(n).length;if(r&&!e||2===r){this.createSourceBuffers(n),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(SC.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){const s=e[r];if(!s)throw Error(`source buffer exists for track ${r}, however track does not`);const i=s.levelCodec||s.codec,a=`${s.container};codecs=${i}`;RC.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const e=t[r]=n.addSourceBuffer(a),o=r;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.tracks[r]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){RC.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const n=new Error(`${e} SourceBuffer error`);RC.error(`[buffer-controller]: ${n}`,t),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_APPENDING_ERROR,error:n,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(t)}removeExecutor(e,t,n){const{media:r,mediaSource:s,operationQueue:i,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return RC.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=wC(r.duration)?r.duration:1/0,c=wC(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(n,l,c);u>d&&!o.ending?(o.ended=!1,RC.log(`[buffer-controller]: Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:n,sourceBuffer:r}=this,s=r[t];if(!s)return RC.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return RC.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:n}=this,r=t.map((e=>n.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||n.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,n){const r=this.sourceBuffer[e];if(!r)return;const s=n.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:iD,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=RC.log.bind(RC,"[info]:"),this.warn=RC.warn.bind(RC,"[warning]:"),this.error=RC.error.bind(RC,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(SC.ERROR,this.onError,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(SC.ERROR,this.onError,this),e.off(SC.ERROR,this.onErrorOut,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(null==e?void 0:e.type)===fR?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var n,r;if(t.fatal)return;const s=this.hls,i=t.context;switch(t.details){case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case IC.FRAG_PARSING_ERROR:if(null!=(n=t.frag)&&n.gap)return void(t.errorAction={action:ZR,flags:nO});case IC.FRAG_GAP:case IC.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=eO);case IC.LEVEL_EMPTY_ERROR:case IC.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===fR?t.level:s.loadLevel;t.details===IC.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case IC.LEVEL_LOAD_ERROR:case IC.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case IC.AUDIO_TRACK_LOAD_ERROR:case IC.AUDIO_TRACK_LOAD_TIMEOUT:case IC.SUBTITLE_LOAD_ERROR:case IC.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===uR&&i.groupId===e.audioGroupId||i.type===hR&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=eO,void(t.errorAction.flags=rO)}return;case IC.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],n=null==e?void 0:e.attrs["HDCP-LEVEL"];n&&(t.errorAction={action:eO,flags:sO,hdcpLevel:n})}return;case IC.BUFFER_ADD_CODEC_ERROR:case IC.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case IC.INTERNAL_EXCEPTION:case IC.BUFFER_APPENDING_ERROR:case IC.BUFFER_APPEND_ERROR:case IC.BUFFER_FULL_ERROR:case IC.LEVEL_SWITCH_ERROR:case IC.BUFFER_STALLED_ERROR:case IC.BUFFER_SEEK_OVER_HOLE:case IC.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:ZR,flags:nO})}if(t.type===EC.KEY_SYSTEM_ERROR){const e=this.getVariantLevelIndex(t.frag);return t.levelRetry=!1,void(t.errorAction=this.getLevelSwitchAction(t,e))}}getPlaylistRetryOrSwitchAction(e,t){var n;const r=WR(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(n=e.response)?void 0:n.code;if(YR(r,s,GR(e),i))return{action:tO,flags:nO,retryConfig:r,retryCount:s};const a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,a=WR(e.details.startsWith("key")?i:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){var l;e.details!==IC.FRAG_GAP&&r.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(YR(a,o,GR(e),t))return{action:tO,flags:nO,retryConfig:a,retryCount:o}}const c=this.getLevelSwitchAction(e,n);return a&&(c.retryConfig=a,c.retryCount=o),c}getLevelSwitchAction(e,t){const n=this.hls;null==t&&(t=n.loadLevel);const r=this.hls.levels[t];if(r&&(r.loadError++,n.autoLevelEnabled)){var s,i;let t=-1;const{levels:a,loadLevel:o,minAutoLevel:l,maxAutoLevel:c}=n,d=null==(s=e.frag)?void 0:s.type,{type:u,groupId:h}=null!=(i=e.context)?i:{};for(let n=a.length;n--;){const s=(n+o)%a.length;if(s!==o&&s>=l&&s<=c&&0===a[s].loadError){const n=a[s];if(e.details===IC.FRAG_GAP&&e.frag){const t=a[s].details;if(t){const n=zR(e.frag,t.fragments,e.frag.start);if(null!=n&&n.gap)continue}}else{if(u===uR&&h===n.audioGroupId||u===hR&&h===n.textGroupId)continue;if(d===pR&&r.audioGroupId===n.audioGroupId||d===gR&&r.textGroupId===n.textGroupId)continue}t=s;break}}if(t>-1&&n.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:eO,flags:nO,nextAutoLevel:t}}return{action:eO,flags:rO}}onErrorOut(e,t){var n;switch(null==(n=t.errorAction)?void 0:n.action){case ZR:break;case eO:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===IC.FRAG_GAP||(t.fatal=!0)}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,n=e.errorAction;if(!n)return;const{flags:r,hdcpLevel:s,nextAutoLevel:i}=n;switch(r){case nO:this.switchLevel(e,i);break;case rO:n.resolved||(n.resolved=this.redundantFailover(e));break;case sO:s&&(t.maxHdcpLevel=PR[PR.indexOf(s)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}n.resolved||this.switchLevel(e,i)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:n}=this,r=e.parent===fR?e.level:t.loadLevel,s=t.levels[r],i=s.url.length,a=e.frag?e.frag.urlId:s.urlId;s.urlId!==a||e.frag&&!s.details||this.penalizeRendition(s,e);for(let o=1;o<i;o++){const l=(a+o)%i,c=n[l];if(!c||iO(c,e,n[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${i}: "${s.url[l]}" after ${e.details}`),this.playlistError=0,t.levels.forEach((e=>{e.urlId=l})),t.nextLoadLevel=r,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:n}=this,r=n[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(t),r.details=e.details,n[e.urlId]=r}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const n=this.hls.config;if(n.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,n){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=n-this.lastDroppedFrames,i=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(SC.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:n}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*i){let e=o.currentLevel;RC.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(SC.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:e_,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:AD,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends QO{constructor(e,t,n){super(e,t,n,"[subtitle-stream-controller]",gR),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.ERROR,this.onError,this),e.on(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(SC.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(SC.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.ERROR,this.onError,this),e.off(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(SC.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(SC.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=NO,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:n,success:r}=t;if(this.fragPrevious=n,this.state=NO,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const a=n.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){i=s[e];break}const o=n.start+n.duration;i?i.end=o:(i={start:a,end:o},s.push(i)),this.fragmentTracker.fragBuffered(n)}onBufferFlushing(e,t){const{startOffset:n,endOffset:r}=t;if(0===n&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let n=0;n<t.length;)if(t[n].end<=e)t.shift();else{if(!(t[n].start<e))break;t[n].start=e,n++}})),this.fragmentTracker.removeFragmentsInRange(n,e,gR)}}onFragBuffered(e,t){var n;this.loadedmetadata||t.frag.type!==fR||null!=(n=this.media)&&n.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const n=t.frag;(null==n?void 0:n.type)===gR&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==FO&&(this.state=NO))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){iP(this.levels,t)?this.levels=t.map((e=>new UR(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new UR(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,gR),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const n=this.levels[this.currentTrackId];null!=n&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var n;const{details:r,id:s}=t,{currentTrackId:i,levels:a}=this;if(!a.length)return;const o=a[i];if(s>=a.length||s!==i||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(n=o.details)&&n.live){const e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;const t=e.fragments[0];o.details?(l=this.alignPlaylists(r,o.details),0===l&&t&&(l=t.start,$R(r,l))):r.hasProgramDateTime&&e.hasProgramDateTime?(PO(r,e),l=r.fragments[0].start):t&&(l=t.start,$R(r,l))}if(o.details=r,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(o.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===NO){zR(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:n}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r&&r.key&&r.iv&&"AES-128"===r.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((n=>{const r=performance.now();s.trigger(SC.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=NO}))}}doTick(){if(this.media){if(this.state===NO){const{currentTrackId:e,levels:t}=this,n=t[e];if(!t.length||!n||!n.details)return;const{config:r}=this,s=this.getLoadPosition(),i=AO.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=i,l=this.getFwdBufferInfo(this.media,fR),c=n.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const d=c.fragments,u=d.length,h=c.edge;let f=null;const p=this.fragPrevious;if(a<h){const e=r.maxFragLookUpTolerance,t=a>h-e?0:e;f=zR(p,d,Math.max(d[0].start,a),t),!f&&p&&p.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=d[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===uO&&(f=e)}this.fragmentTracker.getState(f)===uO&&this.loadFragment(f,n,a)}}else this.state=NO}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,n){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,n))}get mediaBufferTimeRanges(){return new oP(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends aO{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(SC.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);lP(this.media.textTracks).forEach((e=>{SR(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:n,details:r}=t,{trackId:s}=this,i=this.tracksInGroup[s];if(!i)return void this.warn(`Invalid subtitle track id ${n}`);const a=i.details;i.details=t.details,this.log(`subtitle track ${n} loaded [${r.startSN}-${r.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.textGroupIds)return;const n=t.textGroupIds[t.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==n){const e=this.tracks.filter((e=>!n||e.groupId===n));this.tracksInGroup=e;const t=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=n||null;const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n}" group-id`),this.hls.trigger(SC.SUBTITLE_TRACKS_UPDATED,s),-1!==t&&this.setSubtitleTrack(t,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||e===r.name))return r.id}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===hR&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const n=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(SC.SUBTITLE_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:n}=this;if(!t)return;const r=lP(t.textTracks),s=r.filter((e=>e.groupId===this.groupId));if(-1===e)[].slice.call(r).forEach((e=>{e.mode="disabled"}));else{const e=s[n];e&&(e.mode="disabled")}const i=s[e];i&&(i.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var n;const r=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(-1===e||null!=(n=r[e])&&n.details)||e<-1||e>=r.length)return;this.clearTimer();const s=r[e];if(this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:"")),this.trackId=e,s){const{id:e,groupId:n="",name:r,type:i,url:a}=s;this.hls.trigger(SC.SUBTITLE_TRACK_SWITCH,{id:e,groupId:n,name:r,type:i,url:a});const o=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(o)}else this.hls.trigger(SC.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=lP(this.media.textTracks);for(let n=0;n<t.length;n++)if("hidden"===t[n].mode)e=n;else if("showing"===t[n].mode){e=n;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}},timelineController:class{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const e=new PP(this,"textTrack1"),t=new PP(this,"textTrack2"),n=new PP(this,"textTrack3"),r=new PP(this,"textTrack4");this.cea608Parser1=new RP(1,e,t),this.cea608Parser2=new RP(3,n,r)}e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(SC.FRAG_LOADING,this.onFragLoading,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(SC.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(SC.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(SC.FRAG_LOADING,this.onFragLoading,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(SC.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(SC.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,n,r,s){let i=!1;for(let e=s.length;e--;){const r=s[e],d=(a=r[0],o=r[1],l=t,c=n,Math.min(o,c)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),i=!0,d/(n-t)>.5))return}var a,o,l,c;if(i||s.push([t,n]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,n,r)}else{const s=this.Cues.newCue(null,t,n,r);this.hls.trigger(SC.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s}){const{unparsedVttFrags:i}=this;"main"===n&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),i.length&&(this.unparsedVttFrags=[],i.forEach((e=>{this.onFragLoaded(SC.FRAG_LOADED,e)})))}getExistingTrack(e){const{media:t}=this;if(t)for(let n=0;n<t.textTracks.length;n++){const r=t.textTracks[n];if(r[e])return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:n,media:r}=this,{label:s,languageCode:i}=t[e],a=this.getExistingTrack(e);if(a)n[e]=a,SR(n[e]),bR(n[e],r);else{const t=this.createTextTrack("captions",s,i);t&&(t[e]=!0,n[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const n={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(SC.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,n){const r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{SR(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)SR(t[e])}onSubtitleTracksUpdated(e,t){const n=t.subtitleTracks||[],r=n.some((e=>e.textCodec===VP));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(iP(this.tracks,n))return void(this.tracks=n);if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const e=this.media?this.media.textTracks:null;this.tracks.forEach(((t,n)=>{let r;if(e&&n<e.length){let n=null;for(let r=0;r<e.length;r++)if(sD(e[r],t)){n=e[r];break}n&&(r=n)}if(r)SR(r);else{const e=this._captionsOrSubtitlesFromCharacteristics(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&(r.groupId=t.groupId,this.textTracks.push(r))}))}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(SC.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),n=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&n)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:n,cea608Parser2:r,lastSn:s,lastPartIndex:i}=this;if(this.enabled&&n&&r&&t.frag.type===fR){var a,o;const e=t.frag.sn,l=null!=(a=null==t||null==(o=t.part)?void 0:o.index)?a:-1;e===s+1||e===s&&l===i+1||(n.reset(),r.reset()),this.lastSn=e,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:n,payload:r}=t;if(n.type===gR)if(r.byteLength){const e=n.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[n.level],s=this.vttCCs;s[n.cc]||(s[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===VP?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const n=this.hls;JP(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),n.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{RC.log(`Failed to parse IMSC1: ${t}`),n.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:n,payload:r}=e,{initPTS:s,unparsedVttFrags:i}=this,a=s.length-1;if(!s[n.cc]&&-1===a)return void i.push(e);const o=this.hls;HP(null!=(t=n.initSegment)&&t.data?D_(n.initSegment.data,new Uint8Array(r)):r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,(e=>{this._appendCues(e,n.level),o.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?i.push(e):this._fallbackToIMSC1(n,r),RC.log(`Failed to parse VTT cue: ${t}`),s&&a>n.cc||o.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})}))}_fallbackToIMSC1(e,t){const n=this.tracks[e.level];n.textCodec||JP(t,this.initPTS[e.cc],(()=>{n.textCodec=VP,this._parseIMSC1(e,t)}),(()=>{n.textCodec="wvtt"}))}_appendCues(e,t){const n=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||"disabled"===n.mode)return;e.forEach((e=>wR(n,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;n.trigger(SC.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:n}=t;n.type===gR&&this.onFragLoaded(SC.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:n,cea608Parser2:r}=this;if(!this.enabled||!n||!r)return;const{frag:s,samples:i}=t;if(s.type!==fR||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){const s=this.extractCea608Data(t);n.addData(i[e].pts,s[0]),r.addData(i[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:s}){const{media:i}=this;if(i&&!(i.currentTime<n)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((r=>ER(e[r],t,n)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((n=>ER(e[n],t,r)))}}}extractCea608Data(e){const t=[[],[]],n=31&e[0];let r=2;for(let s=0;s<n;s++){const n=e[r++],s=127&e[r++],i=127&e[r++];if(0===s&&0===i)continue;if(0!=(4&n)){const e=3&n;0!==e&&1!==e||(t[e].push(s),t[e].push(i))}}return t}},audioStreamController:class extends QO{constructor(e,t,n){super(e,t,n,"[audio-stream-controller]",pR),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(SC.ERROR,this.onError,this),e.on(SC.BUFFER_RESET,this.onBufferReset,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this),e.on(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(SC.ERROR,this.onError,this),e.off(SC.BUFFER_RESET,this.onBufferReset,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this),e.off(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s}){if("main"===n){const e=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${r}`),this.videoTrackCC=e,this.state===VO&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=FO);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=NO):(this.loadedmetadata=!1,this.state=qO),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case NO:this.doTickIdle();break;case qO:{var e;const{levels:t,trackId:n}=this,r=null==t||null==(e=t[n])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=VO}break}case $O:{var t;const e=performance.now(),n=this.retryDate;(!n||e>=n||null!=(t=this.media)&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=NO);break}case VO:{const e=this.waitingData;if(e){const{frag:t,part:n,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=jO;const e={frag:t,part:n,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),n=AO.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);JR(n.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${n.end} is needed`),this.clearWaitingFragment())}}else this.state=NO}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=NO)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:n,trackId:r}=this,s=e.config;if(null==t||!t[r])return;if(!n&&(this.startFragRequested||!s.startFragPrefetch))return;const i=t[r],a=i.details;if(!a||a.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(a))return void(this.state=qO);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,MC,pR));const l=this.getFwdBufferInfo(o,pR);if(null===l)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return e.trigger(SC.BUFFER_EOS,{type:"audio"}),void(this.state=WO);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,fR),h=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(h>=f&&!d)return;const p=a.fragments[0].start;let g=l.end;if(d&&n){const e=this.getLoadPosition();c&&d.attrs!==c.attrs&&(g=e),a.PTSKnown&&e<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}let m=this.getNextFragment(g,a),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,a,l,fR,f)),!m)return void(this.bufferFlushed=!0);const v=u&&m.start>u.end+a.targetduration;if(v||(null==u||!u.len)&&l.len){const e=this.getAppendedFrag(m.start,fR);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===u.len),v&&!y||y&&l.nextStart&&l.nextStart<e.end)return}this.loadFragment(m,i,g)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new UR(e)))}onAudioTrackSwitching(e,t){const n=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?this.setInterval(100):this.resetTransmuxer(),n?(this.switchingTrack=t,this.state=NO):(this.switchingTrack=null,this.bufferedTrack=t,this.state=FO),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(SC.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var n;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:r}=this,{details:s,id:i}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${i}`);this.log(`Track ${i} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[i];let o=0;if(s.live||null!=(n=a.details)&&n.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(PO(s,e),o=s.fragments[0].start):o=this.alignPlaylists(s,a.details)}a.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(a.details,o),this.state!==qO||this.waitForCdnTuneIn(s)||(this.state=NO),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:n,part:r,payload:s}=e,{config:i,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const c=l.details;if(!c)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(n.start);const d=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Zk(this.hls,pR,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[n.cc],f=null==(t=n.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=r?r.index:-1,i=-1!==t,a=new CO(n.level,n.sn,n.stats.chunkCount,s.byteLength,t,i);u.push(s,f,d,"",n,r,c.totalduration,e,a,h)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:n,part:r,cache:new sP,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=VO}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:n,part:r}=t;if(n.type===pR)if(this.fragContextChanged(n))this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==n.sn){this.fragPrevious=n;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(SC.AUDIO_TRACK_SWITCHED,yC({},e)))}this.fragBufferedComplete(n,r)}else if(!this.loadedmetadata&&n.type===fR){const e=this.videoBuffer||this.media;if(e){AO.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var n;if(t.fatal)this.state=HO;else switch(t.details){case IC.FRAG_GAP:case IC.FRAG_PARSING_ERROR:case IC.FRAG_DECRYPT_ERROR:case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(pR,t);break;case IC.AUDIO_TRACK_LOAD_ERROR:case IC.AUDIO_TRACK_LOAD_TIMEOUT:case IC.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==qO||(null==(n=t.context)?void 0:n.type)!==uR||(this.state=NO);break;case IC.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case IC.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===MC&&(this.bufferFlushed=!0,this.state===WO&&(this.state=NO))}_handleTransmuxComplete(e){var t;const n="audio",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{details:d}=c,{audio:u,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(o)&&d){if(this.state=KO,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;this._bufferInitSegment(p.tracks,e,i),r.trigger(SC.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:p.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=u;l&&(l.elementaryStreams[MC]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(MC,e,t,n,r),this.bufferFragmentData(u,o,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=bC({id:n,frag:o,details:d},f);r.trigger(SC.FRAG_PARSING_METADATA,e)}if(h){const e=bC({id:n,frag:o,details:d},h);r.trigger(SC.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,n){if(this.state!==KO)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.levelCodec=r.codec,r.id="audio",this.log(`Init audio buffer, container:${r.container}, codecs[parsed]=[${r.codec}]`),this.hls.trigger(SC.BUFFER_CODECS,e);const s=r.initSegment;if(null!=s&&s.byteLength){const e={type:"audio",frag:t,part:null,chunkMeta:n,parent:t.type,data:s};this.hls.trigger(SC.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||r===uO||r===fO)?"initSegment"===e.sn?this._loadInitSegment(e,t):null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=VO):(this.startFragRequested=!0,super.loadFragment(e,t,n)):this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:n,bufferedTrack:r}=this,s=null==r?void 0:r.attrs,i=e.attrs;n&&s&&(s.CHANNELS!==i.CHANNELS||s.NAME!==i.NAME||s.LANGUAGE!==i.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(SC.AUDIO_TRACK_SWITCHED,yC({},e))}},audioTrackController:class extends aO{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(SC.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:n,groupId:r,details:s}=t,i=this.tracksInGroup[n];if(!i||i.groupId!==r)return void this.warn(`Track with id:${n} and group:${r} not found in active group ${i.groupId}`);const a=i.details;i.details=t.details,this.log(`audio-track ${n} "${i.name}" lang:${i.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.audioGroupIds)return;const n=t.audioGroupIds[t.urlId];if(this.groupId!==n){this.groupId=n||null;const e=this.tracks.filter((e=>!n||e.groupId===n));this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),this.tracksInGroup=e;const t={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group:${n}`),this.hls.trigger(SC.AUDIO_TRACKS_UPDATED,t),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&t.context.type===uR&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const n=this.currentTrack;t[this.trackId];const r=t[e],{groupId:s,name:i}=r;if(this.log(`Switching to audio-track ${e} "${i}" lang:${r.lang} group:${s}`),this.trackId=e,this.currentTrack=r,this.selectDefaultTrack=!1,this.hls.trigger(SC.AUDIO_TRACK_SWITCHING,yC({},r)),r.details&&!r.details.live)return;const a=this.switchParams(r.url,null==n?void 0:n.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==t)this.setAudioTrack(t);else{const t=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if(!this.selectDefaultTrack||r.default){if(!e||void 0!==e.attrs["STABLE-RENDITION-ID"]&&e.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"])return r.id;if(e.name===r.name&&e.lang===r.lang)return r.id}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const n=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${n} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(SC.AUDIO_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:e||null})}}},emeController:oD,cmcdController:gD,contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=RC.log.bind(RC,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:n}=t;null!==n&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:n}=t;if((null==n?void 0:n.action)===eO&&n.flags===rO){let e=this.pathwayPriority;const t=this.pathwayId;this.penalizedPathways[t]||(this.penalizedPathways[t]=performance.now()),!e&&this.levels&&(e=this.levels.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),n.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach((e=>{r-n[e]>3e5&&delete n[e]}));for(let r=0;r<e.length;r++){const s=e[r];if(n[s])continue;if(s===this.pathwayId)return;const i=this.hls.nextLoadLevel,a=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(SC.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=i);break}}}clonePathways(e){const t=this.levels;if(!t)return;const n={},r={};e.forEach((e=>{const{ID:s,"BASE-ID":i,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(i).map((e=>{const t=bC({},e);t.details=void 0,t.url=yD(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a);const i=new PC(e.attrs);i["PATHWAY-ID"]=s;const o=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;o&&(n[i.AUDIO]=o,i.AUDIO=o),l&&(r[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new UR(t);return cO(c,"audio",o),cO(c,"text",l),c}));t.push(...o),mD(this.audioTracks,n,a,s),mD(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,n=t.loader;let r;this.loader&&this.loader.destroy(),this.loader=new n(t);try{r=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==r.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:r.href},i=t.steeringManifestLoadPolicy.default,a=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,n,s)=>{this.log(`Loaded steering manifest: "${r}"`);const i=e.data;if(1!==i.VERSION)return void this.log(`Steering VERSION ${i.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=i.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=i;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||n.url),o&&this.clonePathways(o),l&&this.updatePathwayPriority(l)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function _D(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(_D):Object.keys(e).reduce(((t,n)=>(t[n]=_D(e[n]),t)),{}):e}function RD(e){const t=e.loader;if(t!==SD&&t!==bD)RC.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=SD,e.progressive=!0,e.enableSoftwareAES=!0,RC.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class OD{static get version(){return"1.4.10"}static isSupported(){return function(){const e=H_();if(!e)return!1;const t=zO(),n=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!n&&!!r}()}static get Events(){return SC}static get ErrorTypes(){return EC}static get ErrorDetails(){return IC}static get DefaultConfig(){return OD.defaultConfig?OD.defaultConfig:CD}static set DefaultConfig(e){OD.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Jk,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function(e,t){if(self.console&&!0===e||"object"==typeof e){_C(e,"debug","log","info","warn","error");try{CC.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){CC=AC}}else CC=AC}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=_D(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],a=[];r.forEach((r=>{const o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&i){a.push(o);const e=n[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&RC.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),yC(yC({},n),t)}(OD.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&RD(t);const{abrController:n,bufferController:r,capLevelController:s,errorController:i,fpsController:a}=t,o=new i(this),l=this.abrController=new n(this),c=this.bufferController=new r(this),d=this.capLevelController=new s(this),u=new a(this),h=new vR(this),f=new OR(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new lO(this,g),y=new gO(this),v=new IO(this.config),b=this.streamController=new tP(this,y,v);d.setStreamController(b),u.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const S=[l,c,d,u,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const E=t.audioStreamController;E&&w.push(new E(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const I=t.subtitleStreamController;I&&w.push(new I(this,y,v)),this.createController(t.timelineController,S),v.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(kR,S),this.coreComponents=S,w.push(o);const T=o.onErrorOut;"function"==typeof T&&this.on(SC.ERROR,T,o)}createController(e,t){if(e){const n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){RC.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){RC.log("destroy"),this.trigger(SC.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){RC.log("attachMedia"),this._media=e,this.trigger(SC.MEDIA_ATTACHING,{media:e})}detachMedia(){RC.log("detachMedia"),this.trigger(SC.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,n=this.url,r=this.url=gC.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});RC.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(SC.MANIFEST_LOADING,{url:e})}startLoad(e=-1){RC.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){RC.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){RC.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){RC.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){RC.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){RC.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){RC.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){RC.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){RC.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(RC.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){PR.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this;let r;if(r=-1===t&&e&&e.length?e.length-1:t,n)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=n)return t}return r}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}OD.defaultConfig=void 0;class kD{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const s=e();if(s.length)try{const n=(new Date).toISOString(),i=await xb({timestamp:n,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const a={signature:i.signature,nonceStr:i.nonceStr,timestamp:n,streams:s},o=Ye();await o.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||r()}catch(e){return s.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let PD=null;class DD{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=PD||(PD=new kD,PD),this._usageCollector.registerStream(e.id),this._sessionId=String(Rf.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(cE((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var LD=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!OD.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await HA(t),{watcherUrl:r,status:s,recordings:i=[],resolution:a}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const o=document.createElement("video");o.id=t,o.controls=!0;const l=new OD;if(l.attachMedia(o),"recorded"!==s){let{url:e}=r.hls;e=e.replace("http:","https:"),l.loadSource(e)}else{const e=i.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");o.src=e.mp4.url}return new DD(o,a,t).registerEvents(),o}});const xD=e=>{const t=(e=>{var t;const n=Ye(),r=new Date,s=r.getTime()+31536e6,i=new Date(s).toISOString();let a=null===(t=tt(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return a||(a={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:i,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Ff({storyTargets:[a]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Ff(t),t},MD=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const i=new FileReader;i.readAsDataURL(s),i.onload=()=>r(xD(n?Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,videoFileId:{original:void 0},fileData:null==i?void 0:i.result})}):Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:null==i?void 0:i.result})})))}return r(xD(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},UD=async e=>{const t=Ye();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=hT(n.data);t.cache&&Ff(r),nt(["story-sync-state",e.targetId],"synced"),Ut("local.story.created",r);const s=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:s}},FD=async({targetId:e,targetType:t})=>{var n,r;if(!tt(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await zE(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await Iw(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}nt(["storyTarget","get",e],s)}},ND=e=>e?tt(["story","get",e]):{data:void 0,cachedAt:void 0},BD=async(e,t=!1)=>{var n,r,s;const i=Ye();let a;if(i.log("story/deleteStory",e),i.cache&&(a=ND(e),null==a?void 0:a.data)){const{data:i}=a;if(Ut("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},i),{isDeleted:!0})]}),"synced"!==i.syncState){t?it(["story","get",e]):nt(["story","get",e],Object.assign(Object.assign({},a.data),{isDeleted:!0}));const r=null===(n=et(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===i.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));nt(["story-expire",a.data.targetId],e.toISOString())}else it(["story-expire",a.data.targetId]);return!0}const o=null===(r=tt(["storyTarget","get",i.targetId]))||void 0===r?void 0:r.data,l=null===(s=et(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===i.targetId&&!0!==e.data.isDeleted));let c;l&&l.length>0&&(c=null==l?void 0:l.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),o&&nt(["storyTarget","get",i.targetId],Object.assign(Object.assign({},o),{lastStoryExpiresAt:c}))}return(await i.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},jD=e=>{const t=Ye(),n=[Mt(t,"onStoryUpdated","story.updated",(async t=>{const n=hT(t);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},$D=e=>{const t=Ye(),n=[Mt(t,"onStoryUpdated","local.story.updated",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},qD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Bf(t,["reactions"]),s=hT(r),i=dS("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Ff(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},KD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Ff({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},GD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Bf(t,["reactions"]),s=hT(r),i=dS("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Ff(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},WD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Ff({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},HD=e=>{e.forEach((e=>{const t=tt(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||nt(["story-expire",e.targetId],n.toISOString())}))},VD=e=>{e.forEach((e=>{nt(["story-reference",e.storyId],e.referenceId)}))},YD=async({targetType:e,targetId:t,options:n})=>{const r=Ye();r.log("story/getActiveStoriesByTarget");const s=r.cache&&Date.now(),i=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),a=hT(i.data);return r.cache&&(Ff(a),HD(a.stories),VD(a.stories)),{data:a.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},QD=e=>{const t=Ye(),n=[Mt(t,"onStoryCreated","story.created",(async t=>{const n=hT(t,!0);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},zD=e=>{const t=Ye(),n=[Mt(t,"onStoryCreated","local.story.created",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},JD=e=>{const t=Ye(),n=[Mt(t,"onStoryDeleted","story.deleted",(async t=>{const n=hT(t);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},XD=e=>{const t=Ye(),n=[Mt(t,"onStoryDeleted","local.story.deleted",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ZD=e=>{const t=Ye();return Mt(t,"onStoryError","local.story.error",(async t=>{Ff(t),e(t.stories)}))},eL=e=>t=>e((e=>t(e[0]))),tL=async e=>{const t=Ye();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Ff(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class nL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),r=hT(e);t.cache&&(Ff(r,{cachedAt:n}),HD(r.stories),VD(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rL extends Ov{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class sL extends kv{constructor(e,t){const n=Tv(e),r=["story-target-ids","collection",n],s=new rL(e);super(s,n,r,t),this.query=e,this.queryStreamController=new nL(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>tt(["story","get",e]))).filter(Boolean).map((e=>gw.story(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:void 0,data:i,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(bt):r.sort(St)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QD,action:"onCreate"},{fn:jD,action:"onUpdate"},{fn:JD,action:"onDelete"},{fn:ZD,action:"onError"}])}}const iL=(e,t)=>{var n,r;const s=null===(n=tt(e))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];nt(e,Object.assign(Object.assign({},s),{data:[...new Set([...i,...t])]}))};class aL extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=s}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Ff(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?nt(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):iL(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&iL(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oL extends Av{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:s="unseen"}=e,i=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:r,token:t});if(null===(n=i.paging)||void 0===n?void 0:n.next)return i;if("smart"!==s)return i;if("seen"===this.smartFilterState)return i;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:r});return l=a,{categories:(o=i).categories.concat(l.categories),communities:o.communities.concat(l.communities),communityUsers:o.communityUsers.concat(l.communityUsers),files:o.files.concat(l.files),storyTargets:o.storyTargets.concat(l.storyTargets),users:o.users.concat(l.users),paging:l.paging};var o,l}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class lL extends kv{constructor(e,t){const n=Tv(e),r=["story-global-feed","collection",n],s=new oL(e);super(s,n,r,t),this.query=e,this.queryStreamController=new aL(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=Bf(Kv(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=s.data,a=et(["storyTarget"]);a&&(null==a?void 0:a.length)>0&&(null==a||a.forEach((({key:e})=>{s.data.includes(e[2])||i.push(e[2])})));let o=i.map((e=>tt(["storyTarget","get",e]))).filter(Boolean).map((e=>gw.storyTarget(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o).filter((({localSortingDate:e})=>!!e)).map((e=>Bf(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(wt);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(wt)||[],r=t.unseen.sort(wt)||[],s=t.seen.sort(wt)||[];return n.concat(r,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QD,action:"onCreate"},{fn:jD,action:"onUpdate"},{fn:JD,action:"onDelete"},{fn:zD,action:"onCreate"},{fn:$D,action:"onUpdate"},{fn:XD,action:"onDelete"},{fn:ZD,action:"onError"}])}}var cL=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},s="fit",i=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Of(),dataType:"image",items:i,targetType:e,targetId:t,metadata:r};const o=new Date;nt(["story-sync-state",t],"syncing"),nt(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),MD({payload:a,formData:n},(e=>{Ut("local.story.created",e)}));try{const{data:r}=await Gw(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:s}=r[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:s})}),FD({targetId:t,targetType:e}),MD({payload:a,formData:n},(e=>{Ut("local.story.created",e)}));const i=await UD(a);return i.data?Object.assign(Object.assign({},i),{data:gw.story(i.data)}):i}catch(e){throw nt(["story-sync-state",t],"error"),MD({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n},(e=>{Ut("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Of(),dataType:"video",items:s,targetType:e,targetId:t,metadata:r};const a=new Date;nt(["story-sync-state",t],"syncing"),nt(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),FD({targetId:t,targetType:e}),MD({payload:i,formData:n,isVideo:!0},(e=>{Ut("local.story.created",e)}));try{const{data:e}=await Kw(n,m.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:t,videoFileId:{original:t}})}),MD({payload:i,formData:n,isVideo:!0},(e=>{Ut("local.story.created",e)}));const r=await UD(i);return r.data?Object.assign(Object.assign({},r),{data:gw.story(r.data)}):r}catch(e){throw nt(["story-sync-state",t],"error"),MD({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Ut("local.story.error",e)})),e}},hardDeleteStory:async e=>await BD(e,!0),softDeleteStory:async e=>await BD(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Ye(),s=[],i=["story-target","collection",e],a=Date.now();n(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),r||console.log(Y);const o=t=>{var n,r;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",i=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===i?t.sort(bt):t.sort(St):"asc"===i?t.sort(Et):t.sort(It)},l=e=>{var n;const r=e.data.map((e=>{const t=ND(e);if(null==t?void 0:t.data)return gw.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=o(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=o(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=o(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},c=(t,n,r=!1,s=!1,a=!1)=>{var o;const c=tt(i),d={loading:s,error:a,params:{page:void 0},data:(null==c?void 0:c.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(Je("story")):[...new Set([...d.data,...t.map(Je("story"))])];const u=null===(o=et(["story","get"]))||void 0===o?void 0:o.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Je("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),nt(i,d.data),l(d)},d=e=>t=>{c(t,e)};return(t=>{const n=Be(YD,e);$e(n,(({data:e,error:n,loading:r})=>{c(e,"fetch",t,r,n)}))})(!0),s.push(QD(d("onCreate")),jD(d("onUpdate")),JD(d("onDelete")),qD(d("onReactionAdded")),GD(d("onReactionRemoved")),ZD(d("onError")),zD(d("onCreate")),$D(d("onUpdate")),XD(d("onDelete")),KD(d("onReactionAdded")),WD(d("onReactionRemoved")),(e=>{const t=Ye();return Mt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=tt(i);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};l(n)})),(()=>it(i))),()=>{n(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Nv(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:gw.story(e.data)})):t(e)}),"storyId",fT,[eL(jD),eL(JD),eL(qD),eL(GD),eL(ZD),eL($D),eL(XD),eL(KD),eL(WD)]),getTargetById:(e,t)=>Nv(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:gw.storyTarget(e.data[0])})):t(e)}),"query",(e=>tL([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Ye(),s=[],i=["storyTargets","collection",e],a=Date.now();n(`getTargetsByTargetIds(tmpid: ${a}) > listen`),r||console.log(Y);const o=(e,n=!1,r=!1,s=!1)=>{const a=tt(i),o={loading:r,error:s,params:{page:void 0},data:[]};e&&(o.data=n?e.map(Je("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(Je("storyTarget"))])]),nt(i,o.data),(e=>{var n;const r=e.data.map((e=>{const t=tt(["storyTarget","get",e]);if(null==t?void 0:t.data)return gw.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(o)};return(t=>{const n=Be(tL,e);$e(n,(({data:e,error:n,loading:r})=>{o(e,t,r,n)}))})(!0),s.push((()=>it(i))),()=>{n(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const o=new sL(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const o=new lL(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});const dL=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),uL=e=>Object.assign({},e);var hL=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(dL),r=t.advertisers.map(uL);return Ff({ads:n,advertisers:r,files:t.files}),nt(["ad","setting"],t.settings),{ads:n.map(gw.ad),settings:t.settings}}});const fL=async()=>{const e=Ye();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];nt(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};fL.locally=()=>{var e;const t=Ye();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=tt(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const pL=e=>{const t=Ye(),n=[Mt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class gL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class mL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.notificationTrayItems.map(Je("notificationTrayItem"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Je("notificationTrayItem"))])]}))}}}const yL=e=>{const t=e.users.map(fp);return Object.assign(Object.assign({},e),{users:t})};class vL extends kv{constructor(e,t){const n=Tv(e),r=["notificationTrayItem","collection",n];super(new gL(e),n,r,t),this.query=e,this.queryStreamController=new mL(this.query,this.cacheKey,this.notifyChange.bind(this),yL),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["notificationTrayItem","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.notificationTray);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var bL=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Rt();return Nv(t,e,"userId",fL,[pL],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Hf(e.lastTraySeenAt)>Hf(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getNotificationTrayItems(tmpid: ${i}) > listen`);const a=new vL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getNotificationTrayItems(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ye();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=tt(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const s=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();nt(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Ut("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Ye();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=tt(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,i={userId:n.userId,lastTraySeenAt:r.lastSeenAt},a=Object.assign(Object.assign({},s),i),o=n.cache&&Date.now();return n.cache&&nt(["notificationTraySeen","get",n.userId],a,{cachedAt:o}),Ut("local.notificationTraySeen.updated",i),{data:r,cachedAt:o}},onNotificationTraySeenUpdated:pL});class wL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:s})}),a=i.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==a?void 0:a.length)>0&&await QE(a),i}}class SL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.invitations.map(Je("invitation"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Je("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===lb.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===lb.OnLocalInvitationCreated){const e=Ye(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===lb.OnLocalInvitationCanceled&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class EL extends kv{constructor(e,t){const n=Tv(e),r=["invitation","collection",n];super(new wL(e),n,r,t),this.query=e,this.queryStreamController=new SL(this.query,this.cacheKey,this.notifyChange.bind(this),ib),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ub,action:lb.OnLocalInvitationCreated},{fn:hb,action:lb.OnLocalInvitationUpdated},{fn:fb,action:lb.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["invitation","get",e]))).filter(Pv).map((({data:e})=>ab(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}var IL=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ye();n.log("invitation/cancelInvitation",e);const{data:r}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return Nf("invitation",e),s&&Ut("local.invitation.canceled",[s]),r.success},onLocalInvitationCreated:ub,onLocalInvitationUpdated:hb,onLocalInvitationCanceled:fb,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMyCommunityInvitations: (tmpid: ${i}) > listen`);const a=new EL(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getInvitations (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=$t();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ye(),{targetId:s,targetType:i}=e,a=Date.now();r(`observeInvitations(tmpid: ${a}) > listen for ${i}: ${s}`);const o=[],l=n=>{const r=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(gw.invitation))})(r)};return"room"===i&&(o.push(EA(l)),o.push(TA(l)),o.push(AA(l)),o.push(CA(l))),()=>{r(`getInvitations(tmpid: ${a}) > dispose for ${i}: ${s}`),o.forEach((e=>e()))}}});const TL=e=>{const t=Ye();return Mt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var AL=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r,roomId:s})=>{const i=Ye();if(i.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:r,roomId:s}),!r&&!s)throw new Ke("You have to specify either streamId or roomId",800110,"error");const a=xm(),o={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:r,occurredAt:(new Date).toISOString()};return a.createLiveReaction(o),Ut("local.liveReaction.created",[Object.assign(Object.assign({},o),{userId:i.userId,referenceId:e})]),!0},onLiveReactionCreated:TL,getReactions:(e,t)=>{const{_id:n}=Rt();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ye();r(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],i=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(TL(i)),s.push((e=>{const t=Ye();return Mt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(i)),()=>{s.forEach((e=>e()))}}});const CL=async e=>{const t=Ye();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),r=Qb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(ie(null==n?void 0:n.code)){const r=CL.locally(e);if(!r)throw n;const s=Object.assign(Object.assign({},null==r?void 0:r.data),{isDeleted:!0});st(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};CL.locally=e=>{const t=Ye();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=tt(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class _L extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class RL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.events.map(Je("event"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Je("event"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Zb.OnEventCreated&&(r.data=[...new Set([t.eventId,...r.data])]),e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class OL extends kv{constructor(e,t){const n=Tv(e),r=["event","collection",n];super(new _L(e),n,r,t),this.query=e,this.queryStreamController=new RL(this.query,this.cacheKey,this.notifyChange.bind(this),Qb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:nw,action:Zb.OnEventCreated},{fn:rw,action:Zb.OnEventUpdated},{fn:sw,action:Zb.OnEventDeleted},{fn:iw,action:Zb.OnEventCreated},{fn:aw,action:Zb.OnEventUpdated},{fn:ow,action:Zb.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["event","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.event);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class kL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class PL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.events.map(Je("event"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Je("event"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Zb.OnEventCreated){if(Ye().userId!==t.userId)return;r.data=[...new Set([t.eventId,...r.data])]}e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class DL extends kv{constructor(e,t){const n=Tv(e),r=["event","collection",n];super(new kL(e),n,r,t),this.query=e,this.queryStreamController=new PL(this.query,this.cacheKey,this.notifyChange.bind(this),Qb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:nw,action:Zb.OnEventCreated},{fn:rw,action:Zb.OnEventUpdated},{fn:sw,action:Zb.OnEventDeleted},{fn:iw,action:Zb.OnEventCreated},{fn:aw,action:Zb.OnEventUpdated},{fn:ow,action:Zb.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["event","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.event);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var LL=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ye();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Ut("local.event.created",n);const r=Qb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:pw(r.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ye();n.log("event/updateEvent",e,t);const{data:r}=await n.http.put(`/api/v1/events/${e}`,t);Ut("local.event.updated",r);const s=Qb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:pw(s.events.find((t=>t.eventId===e))),cachedAt:i}},deleteEvent:async e=>{const t=Ye();t.log("event/deleteEvent",e);const n=await CL(e);await t.http.delete(`/api/v1/events/${e}`);const r=Object.assign(Object.assign({},n.data),{isDeleted:!0});st(["event","get",e],r),Ut("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[r]})},onEventCreated:nw,onEventUpdated:rw,onEventDeleted:sw,onLocalEventCreated:iw,onLocalEventUpdated:aw,onLocalEventDeleted:ow,onRSVPCreated:lw,onRSVPUpdated:cw,onLocalRSVPCreated:dw,onLocalRSVPUpdated:uw,getEvent:(e,t)=>Nv(e,t,"eventId",CL,[rw,sw,aw,ow],{callbackDataSelector:e=>e?pw(e):e}),getEvents:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getEvents: (tmpid: ${i}) > listen`);const a=new OL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getEvents (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMyEvents: (tmpid: ${i}) > listen`);const a=new DL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getMyEvents (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getRSVPs:fw});const xL=async e=>{const t=Ye();let n;t.log("product/getProduct",e),Xf("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("product",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:r}};xL.locally=e=>{const t=Ye();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=tt(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ML extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class UL extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Ff(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.products.map(Je("product"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Je("product"))])]}))}}}class FL extends kv{constructor(e,t){const n=Tv(e),r=["products","collection",n];super(new ML(e),n,r,t),this.query=e,this.queryStreamController=new UL(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["product","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.product))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var NL=Object.freeze({__proto__:null,getProduct:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.product(n):n}))}),"productId",xL,[]),searchProducts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchProducts(tmpid: ${i}) > listen`);const a=new FL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchProducts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});return e.API_REGIONS=hn,e.AdRepository=hL,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=iT,e.ChannelRepository=VE,e.Client=sv,e.CommentRepository=TT,e.CommunityPostSettingMaps=f,e.CommunityPostSettings=h,e.CommunityRepository=nT,e.ContentFeedType=m,e.DefaultCommunityPostSetting=p,e.EventRepository=LL,e.FeedRepository=zT,e.FileRepository=Ww,e.FileType=a,e.GET_WATCHER_URLS=Sb,e.InvitationRepository=IL,e.LiveReactionRepository=AL,e.LiveStreamPlayer=LD,e.MessageContentType=v,e.MessageRepository=mE,e.PollRepository=hC,e.PostContentType=b,e.PostRepository=WA,e.PostStructureType=w,e.ProductRepository=NL,e.ReactionRepository=BS,e.RoomPresenceRepository=lC,e.RoomRepository=jA,e.StoryRepository=cL,e.StreamRepository=rC,e.SubChannelRepository=IE,e.UserRepository=$w,e.VERSION=G,e.VideoResolution=o,e.VideoSize=c,e.VideoTranscodingStatus=l,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:s}=Ye();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const i=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(i).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(i)),!0)},e.createQuery=Be,e.createReport=async(e,t,n)=>{const r=Ye();return r.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await yw(e,t))({referenceId:t,options:n}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await dp(n);Ff(e)}return Ut("message.flagged",n),!!n})({client:r,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await nS(n);Ff(e)}return Ut("post.flagged",n),!!n})({client:r,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await jS(n);Ff(e)}return Ut("comment.flagged",n),!!n})({client:r,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Pf(),s=Df(),i=Ps(pn("http",t)),{data:a}=await i.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const n=Ye();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Xg(n);Ff(e)}return Ut("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await dp(n);Ff(e)}return Ut("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await nS(n);Ff(e)}return Ut("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await jS(n);Ff(e)}return Ut("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=it,e.enableCache=(e={},t)=>{const n=Ye();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Ct,e.filterByChannelMembership=ct,e.filterByCommunityMembership=ut,e.filterByFeedType=dt,e.filterByPostDataTypes=ht,e.filterByPropEquality=at,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=lt,e.filterBySearchTerm=ft,e.filterByStringComparePartially=ot,e.filterByUntilAt=(e,t,n)=>{const r=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<r)):e.filter((e=>new Date(e.createdAt).valueOf()>r))},e.filterCommentsByBlockUsers=mt,e.filterPostsByBlockUsers=gt,e.getBlockUsersId=pt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Rt();return`${Gt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Kt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Xt,e.getMarkedMessageTopic=Vt,e.getMarkerUserFeedTopic=()=>{const e=Rt();return`${Gt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Wt,e.getMyFollowingsTopic=Ht,e.getNetworkId=Gt,e.getNetworkTopic=Yt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Vw,e.getRoomStreamerTopic=e=>{const t=$t();return`${Gt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=$t();return`${Gt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Qt,e.getSmartFeedMessageTopic=Jt,e.getSmartFeedSubChannelTopic=zt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Rt();return`${Gt(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Kt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=Oe,e.isAfterBeforeRaw=ke,e.isCachable=Fe,e.isFetcher=xe,e.isFresh=Ne,e.isLocal=e=>Fe(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Me,e.isOffline=Ue,e.isPaged=Pe,e.isReportedByMe=async(e,t)=>{const n=Ye();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Re,e.mergeInCache=rt,e.notificationTray=bL,e.onChannelMarkerFetched=Qy,e.onFeedMarkerFetched=e=>{const t=Ye();return Mt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ye();return Mt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Ff(t),e(t.feedMarkers[0])}))},e.onMessageMarked=ev,e.onMessageMarkerFetched=Zy,e.onSubChannelMarkerFetched=zy,e.onSubChannelMarkerUpdated=Jy,e.onUserMarkerFetched=Xy,e.onUserMarkerFetchedLegacy=e=>{const t=Ye();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=tt,e.pushToCache=nt,e.queryCache=et,e.queryOptions=je,e.queryRoles=Hw,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ye();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=$e,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=yt,e.sortByFirstCreated=bt,e.sortByFirstUpdated=Et,e.sortByLastActivity=Tt,e.sortByLastCreated=St,e.sortByLastUpdated=It,e.sortByLocalSortingDate=wt,e.sortByName=vt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Zt,e.toPage=Le,e.toPageRaw=e=>{if(!e)return;const t=JSON.parse(_e(e));return ke(t)?t:void 0},e.toToken=De,e.upsertInCache=st,e.validateUntilAt=At,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Ye();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|
|
13
|
+
class Sh{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let Eh;var Ih=()=>(Eh||(Eh=new Sh),Eh);const Th=e=>Ih().onSessionStateChange(e),Ah={[e.AmityAutoSubscription.NETWORK]:[Yt],[e.AmityAutoSubscription.CHAT]:[Qt,zt,Jt],[e.AmityAutoSubscription.LIVESTREAM]:[Xt],[e.AmityAutoSubscription.BLOCK]:[Wt,Ht]},Ch=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],_h=Object.values(e.AmityAutoSubscription);class Rh{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Ch.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Ah[e].map((e=>Zt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){_h.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return _h.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Ah[e].length})))}reset(){_h.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let Oh=null;const kh=()=>(Oh||(Oh=new Rh),Oh);class Ph{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Dh=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ph},Lh=async(e,t)=>new Promise((n=>{Dh().localStorage.setItem(e,t),n(!0)})),xh=async e=>new Promise((t=>{t(Dh().localStorage.getItem(e))}));var Mh={},Uh={},Fh={};Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.bytesToString=Fh.stringToBytes=Fh.NIL=Fh.X500=Fh.OID=Fh.URL=Fh.DNS=Fh.hexToByte=Fh.byteToHex=void 0;let Nh=[],Bh={};for(var jh=0;jh<256;jh++)Nh[jh]=(jh+256).toString(16).substr(1),Bh[Nh[jh]]=jh;Fh.byteToHex=Nh,Fh.hexToByte=Bh,Fh.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Fh.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Fh.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",Fh.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",Fh.NIL="00000000-0000-0000-0000-000000000000";Fh.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t};Fh.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Uh,"__esModule",{value:!0}),Uh.parse=void 0;const $h=Fh;Uh.parse=(e,t,n)=>{let r=t&&n||0,s=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(s<16&&t&&(t[r+s++]=$h.hexToByte[e]),"")));s<16;)t[r+s++]=0;return t};var qh={};Object.defineProperty(qh,"__esModule",{value:!0}),qh.unparse=void 0;const Kh=Fh;qh.unparse=(e,t)=>{let n=t||0,r=Kh.byteToHex;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]};var Gh={},Wh={};Object.defineProperty(Wh,"__esModule",{value:!0});Wh.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var Hh=nn&&nn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gh,"__esModule",{value:!0}),Gh.validate=void 0;const Vh=Hh(Wh);Gh.validate=e=>"string"==typeof e&&Vh.default.test(e);var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0}),Yh.version=void 0;const Qh=Gh;Yh.version=e=>{if(!Qh.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var zh={},Jh={};Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.stringify=void 0;const Xh=Gh,Zh=[];for(let e=0;e<256;++e)Zh.push((e+256).toString(16).substr(1));Jh.stringify=(e,t=0)=>{const n=(Zh[e[t+0]]+Zh[e[t+1]]+Zh[e[t+2]]+Zh[e[t+3]]+"-"+Zh[e[t+4]]+Zh[e[t+5]]+"-"+Zh[e[t+6]]+Zh[e[t+7]]+"-"+Zh[e[t+8]]+Zh[e[t+9]]+"-"+Zh[e[t+10]]+Zh[e[t+11]]+Zh[e[t+12]]+Zh[e[t+13]]+Zh[e[t+14]]+Zh[e[t+15]]).toLowerCase();if(!Xh.validate(n))throw TypeError("Stringified UUID is invalid");return n};var ef={};Object.defineProperty(ef,"__esModule",{value:!0}),ef.rng=void 0;ef.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(zh,"__esModule",{value:!0}),zh.v1=void 0;const tf=Jh,nf=ef;let rf,sf,af=0,of=0;zh.v1=(e,t,n=0)=>{let r=t&&n||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:rf,a=e&&e.clockseq?e.clockseq:sf;if(null==i||null==a){const t=e&&e.random?e.random:e&&e.rng?e.rng():nf.rng();null==i&&(i=rf=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==a&&(a=sf=16383&(t[6]<<8|t[7]))}let o=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:of+1;const c=o-af+(l-of)/1e4;if(c<0&&e&&!e.clockseq&&(a=a+1&16383),(c<0||o>af)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");af=o,of=l,sf=a,o+=122192928e5;const d=(1e4*(268435455&o)+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=255&d;const u=o/4294967296*1e4&268435455;s[r++]=u>>>8&255,s[r++]=255&u,s[r++]=u>>>24&15|16,s[r++]=u>>>16&255,s[r++]=a>>>8|128,s[r++]=255&a;for(let e=0;e<6;++e)s[r+e]=i[e];return t||tf.stringify(s)};var lf={};Object.defineProperty(lf,"__esModule",{value:!0}),lf.v4=void 0;const cf=qh,df=ef;lf.v4=(e,t,n)=>{let r=t&&n||0,s=df.rng();if(!e||e instanceof String||(e.random&&(s=e.random),e.rng&&(s=e.rng())),s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var i=0;i<16;i++)t[r+i]=s[i];return t||cf.unparse(s)};var uf={},hf={};Object.defineProperty(hf,"__esModule",{value:!0}),hf.v35=void 0;const ff=Jh,pf=Uh,gf=Fh;hf.v35=(e,t,n)=>(e,r,s,i=0)=>{if("string"==typeof e&&(e=gf.stringToBytes(e)),"string"==typeof r&&(r=pf.parse(r)),r&&16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+e.length);if(a.set(r),a.set(e,r.length),a=gf.stringToBytes(n(gf.bytesToString(a))),a[6]=15&a[6]|t,a[8]=63&a[8]|128,s)for(let e=0;e<16;++e)s[i+e]=a[e];return s||ff.stringify(a)};var mf={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,n="";e.hex_sha1=e=>i(r(l(e))),e.default=e.hex_sha1;e.b64_sha1=e=>a(r(l(e)));e.any_sha1=(e,t)=>o(r(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>a(s(l(e),l(t)));e.any_hmac_sha1=(e,t,n)=>o(s(l(e),l(t)),n);const r=e=>d(u(c(e),8*e.length)),s=(e,t)=>{let n=c(e);n.length>16&&(n=u(n,8*e.length));let r=Array(16),s=Array(16);for(var i=0;i<16;i++)r[i]=909522486^n[i],s[i]=1549556828^n[i];var a=u(r.concat(c(t)),512+8*t.length);return d(u(s.concat(a),672))},i=e=>{for(var n,r=t?"0123456789ABCDEF":"0123456789abcdef",s="",i=0;i<e.length;i++)n=e.charCodeAt(i),s+=r.charAt(n>>>4&15)+r.charAt(15&n);return s},a=e=>{for(var t="",r=e.length,s=0;s<r;s+=3)for(var i=e.charCodeAt(s)<<16|(s+1<r?e.charCodeAt(s+1)<<8:0)|(s+2<r?e.charCodeAt(s+2):0),a=0;a<4;a++)8*s+6*a>8*e.length?t+=n:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-a)&63);return t},o=(e,t)=>{var n,r,s,i,a=t.length,o=[],l=Array(Math.ceil(e.length/2));for(n=0;n<l.length;n++)l[n]=e.charCodeAt(2*n)<<8|e.charCodeAt(2*n+1);for(;l.length>0;){for(i=[],s=0,n=0;n<l.length;n++)s=(s<<16)+l[n],s-=(r=Math.floor(s/a))*a,(i.length>0||r>0)&&(i[i.length]=r);o[o.length]=s,l=i}var c="";for(n=o.length-1;n>=0;n--)c+=t.charAt(o[n]);var d=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(n=c.length;n<d;n++)c=t[0]+c;return c},l=e=>{for(var t,n,r="",s=-1;++s<e.length;)t=e.charCodeAt(s),n=s+1<e.length?e.charCodeAt(s+1):0,t>=55296&&t<=56319&&n>=56320&&n<=57343&&(t=65536+((1023&t)<<10)+(1023&n),s++),t<=127?r+=String.fromCharCode(t):t<=2047?r+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?r+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(r+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return r},c=e=>{for(var t=Array(e.length>>2),n=0;n<t.length;n++)t[n]=0;for(n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<24-n%32;return t},d=e=>{for(var t="",n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>24-n%32&255);return t},u=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n=Array(80),r=1732584193,s=-271733879,i=-1732584194,a=271733878,o=-1009589776,l=0;l<e.length;l+=16){for(var c=r,d=s,u=i,m=a,y=o,v=0;v<80;v++){n[v]=v<16?e[l+v]:g(n[v-3]^n[v-8]^n[v-14]^n[v-16],1);let t=p(p(g(r,5),h(v,s,i,a)),p(p(o,n[v]),f(v)));o=a,a=i,i=g(s,30),s=r,r=t}r=p(r,c),s=p(s,d),i=p(i,u),a=p(a,m),o=p(o,y)}return[r,s,i,a,o]},h=(e,t,n,r)=>e<20?t&n|~t&r:e<40?t^n^r:e<60?t&n|t&r|n&r:t^n^r,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n},g=(e,t)=>e<<t|e>>>32-t}(mf);var yf=nn&&nn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(uf,"__esModule",{value:!0}),uf.v5=void 0;const vf=hf,bf=yf(mf);uf.v5=vf.v35("v5",80,bf.default),Object.defineProperty(Mh,"__esModule",{value:!0});const wf=Uh,Sf=qh,Ef=Gh,If=Yh,Tf=zh,Af=lf,Cf=uf,_f=Fh;var Rf=Mh.default={parse:wf.parse,unparse:Sf.unparse,validate:Ef.validate,version:If.version,v1:Tf.v1,v4:Af.v4,v5:Cf.v5,NIL:_f.NIL,DNS:_f.DNS,URL:_f.URL,OID:_f.OID,X500:_f.X500};const Of=()=>Rf.v4().toString();let kf=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Of(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:kf}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(kf=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Pf=async()=>{var e;const t=`${null!==(e=Ye().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await xh(t);if(n)return n;const r=`ascWebSdk#${Of()}`;return await Lh(t,r),r},Df=()=>{const e=(()=>{var e,t;return(null===(e=dn.versions)||void 0===e?void 0:e.node)?dn.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:G}},Lf=1e3;var xf;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(xf||(xf={}));const Mf=e=>{let t;const n=new Map;function r(e,s,i){const a=(t,a)=>{var o;if(t||128===(null===(o=null==a?void 0:a[0])||void 0===o?void 0:o.qos))if(s<2){const t=Math.min(2**s*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${s+1}/3). Retrying in ${t}ms.`);const a=setTimeout((()=>{r(e,s+1,i)}),t);n.set(e,{timer:a,callback:i})}else{n.delete(e);const r=t?new Ke(t.message,8e5,"error"):new We(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,r),null==i||i(r)}else n.delete(e),console.log(`Subscribed to topic ${e}`),null==i||i()};t?t.subscribe(e,{qos:0},a):a(new Error("No connection to broker"),[])}return{connect:async function(r){const s=await(async e=>`mqttjs_${await Pf()}_${e}_${kf}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=wh.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:Lf,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:r.userId,password:r.accessToken,clientId:s})),t.on("connect",(()=>{t.options.reconnectPeriod=Lf,kh().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Lf),8e3)})),t.on("close",(()=>{n.forEach((({timer:e})=>clearTimeout(e))),n.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,t){return r(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var r;const s=n.get(e);if(void 0!==s){clearTimeout(s.timer),n.delete(e);const t=new Ke("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(r=s.callback)||void 0===r||r.call(s,t)}null==t||t.unsubscribe(e)}}},Uf=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Ff=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const s=Xe[e];if(!s)return;const i=Je(s);i&&r&&r.forEach((e=>{(n?nt:st)([s,"get",i(e)],e,t)}))}))},Nf=(e,t)=>{const{log:n,cache:r}=Ye(),s=[e,ee,t],i={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:s,data:i}),it([e,"get",t],!0),nt(s,i))};function Bf(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}const jf=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ye().cache)return;return(null===(n=tt(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},$f=(e,t,n="userId",r="user")=>{const s=e,i=t,a=s[i],o=Bf(s,["symbol"==typeof i?i:i+""]),l=jf(a,n,r);return Object.assign(Object.assign({},o),{[t]:l})};function qf(e){return e.map((e=>{var{isMentioned:t}=e,n=Bf(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Kf(e){return qf(e)}function Gf(e){return qf(e)}const Wf=e=>{var t,n;return null!==(n=null===(t=tt(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Hf=e=>new Date(e).getTime(),Vf=e=>{var t,n;return null!==(n=null===(t=tt(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yf=e=>{var t;const n=e.messagePreviewId?Vf(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=tt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},Qf=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,messageId:a,creatorPublicId:o,data:l,dataType:c,isDeleted:d,segment:u,createdAt:h,updatedAt:f}=t;return{messagePreviewId:a,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:d,segment:u,creatorId:o,createdAt:h,updatedAt:f,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Ff(r)};function zf(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Jf(e,t,n){nt(["subChannel","get",e],zf(t,n))}const Xf=(e,t)=>{const{log:n,cache:r}=Ye(),s=[e,ee,t];if(!r)return;n("cache/api/isInTombstone",s);const i=tt(s),{lifeSpan:a}=je("cache_then_server",18e4);if(i&&Ne(i.data,a))throw new Ge("Item not found!",400400,"error")},Zf=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=tt(n))||void 0===t?void 0:t.data,s=et(["subChannelUnreadInfo","get"]);let i=0,a=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));i=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}const o=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:i,isMentioned:a});return nt(n,o),o},ep=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Ff({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{Zf(e)}))}},tp=async()=>{const e=Ye();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Ff({userMarkers:n},{cachedAt:r}),Ut("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},np=e=>{var t,n;const r=null===(t=tt(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const s=et(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},rp=e=>!0===e&&void 0;function sp(e,t,n){var r,s;if(n)return n.hasMentioned;const i=Ye();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=tt(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Rt()._id},o=null===(s=tt(["subChannelMarker","get",Je("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return!!o&&o.hasMentioned}const ip=["broadcast","conversation","community"],ap=({channelType:e})=>ip.includes(e);function op(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:o,lastMessageTimestamp:l,messageFeedId:c,name:d}=e,u=Bf(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,s;if(n)return n.unreadCount;const i=Ye();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=tt(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Rt()._id},o=null===(s=tt(["subChannelMarker","get",Je("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return o?o.unreadCount:0}(t,c)},get hasMentioned(){return sp(t,c)},get isMentioned(){return sp(t,c)}},u),{channelId:n,creatorId:a,displayName:d,lastActivity:l,latestMessageId:o,messageCount:s,subChannelId:c,isUnreadCountSupport:ap({channelType:r})})}function lp(e,t,n){var r;const s=(e=>{var t,n,r;const s=null===(n=null===(t=et(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(r=s.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:i,childCount:a,creatorPublicId:o,mentionedUsers:l,messageFeedId:c,myReactions:d,reactionCount:u,reactions:h,referenceId:f,segment:p,messageId:g,creatorId:m}=s,y=Bf(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;f&&(v=tt(["message","get",f])),v||(v=tt(["message","get",g]));const b=Object.assign(Object.assign({},y),{messageId:g,channelId:i,channelSegment:p,childrenNumber:a,creatorId:o,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:c,uniqueId:v?v.data.uniqueId:g,referenceId:f,syncState:"synced"});return l&&(b.mentionees=l.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=Ye(),s=np(e.messageId),i=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:i});const a=t[0];a&&a.userId===r.userId&&("message.reactionAdded"!==n||i.includes(a.reactionName)||Object.assign(e,{myReactions:[...i,a.reactionName]}),"message.reactionRemoved"===n&&i.includes(a.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==a.reactionName))}))})(b,t,n),b}const cp={},dp=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Ff({messages:(r=e).messages.map((e=>lp(e,r.reactions)))});const t=n.join("");cp[t]&&clearTimeout(cp[t]),cp[t]=setTimeout((()=>{try{(async e=>{const t=Ye();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();t.cache&&Ff({contentMarkers:r,feedMarkers:s,userMarkers:i},{cachedAt:a}),Ut("local.feedMarker.fetched",{feedMarkers:s}),Ut("local.messageMarker.fetched",{contentMarkers:r}),Ut("local.userMarker.fetched",{userMarkers:i})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:s}=e,i=Bf(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const r=null!==(n=null===(t=tt(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Bf(op(e),["unreadCount","isMentioned"]);Jf(e.messageFeedId,r,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((n=>lp(n,e.reactions,t)))})};function up(e){var{subChannelId:t,mentionees:n,dataType:r,data:s}=e,i=Bf(e,["subChannelId","mentionees","dataType","data"]);return r===v.IMAGE||r===v.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},s)},i):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:s},i)}function hp(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:s,includeDeleted:i,aroundMessageId:a,limit:o,type:l}=e,c=Bf(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},c),{messageFeedId:n,isDeleted:rp(i),options:{sortBy:t,limit:o||W,around:a}});return r&&(d.includeTags=r),l&&(d.dataType=l),s&&(d.excludeTags=s),d}function fp(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const pp=["broadcast","conversation","community"],gp=({channelType:e})=>pp.includes(e),mp=async e=>{const t=e.messageFeeds.filter(gp).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Ff({messageFeeds:e.messageFeeds.map((e=>op(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ye();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:De(t,"skiplimit")}}}),{paging:s}=r,i=Bf(r,["paging"]),{userEntityMarkers:a,userFeedMarkers:o,userMarkers:l,feedMarkers:c}=i;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&ep({feedMarkers:c,userFeedMarkers:o});const d=Kf(a),u=Gf(o),h=n.cache&&Date.now();n.cache&&Ff({userEntityMarkers:d,userFeedMarkers:u,userMarkers:l},{cachedAt:h}),Ut("local.channelMarker.fetched",{userEntityMarkers:d}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:u}),Ut("local.userMarker.fetched",{userMarkers:l});const f=Le(s.next);return{data:u,cachedAt:h,prevPage:Le(s.previous),nextPage:f}})(t)}catch(e){}}Qf(e);const n=e.messageFeeds.map(op),r=e.messages.map((e=>lp(e))),s=e.users.map(fp);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:s})};const yp=async e=>{const t=Ye();t.log("channel/getSubChannel",e),Xf("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:s}}catch(t){throw ie(null==t?void 0:t.code)&&Nf("subChannel",e),t}};yp.locally=e=>{const t=Ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=tt(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const vp=async e=>{var t;let n=null===(t=tt(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await yp(e)).data),n},bp=async e=>{const t=await(async()=>Ye().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=await vp(c);"no-message-preview"!==t?(e=>{var t;const n=null===(t=tt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Hf(n.createdAt)<=Hf(e.createdAt)})(e)&&(nt(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),Jf(e.subChannelId,h,{lastActivity:i,messagePreviewId:r})):Hf(h.lastActivity)<Hf(i)&&Jf(e.subChannelId,h,{lastActivity:i})},wp=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=null===(t=tt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await vp(c);nt(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Sp=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:s,updatedAt:i,data:a,dataType:o,subChannelId:l,channelSegment:c,isDeleted:d}=e;if((e=>{var t;const n=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hf(n.createdAt)<=Hf(e.createdAt)})(e)){const u=await vp(l);nt(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:s,updatedAt:i,subChannelId:l,data:a,dataType:o,segment:c,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Ep=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:i,updatedAt:a,data:o,dataType:l,subChannelId:c,channelSegment:d,isDeleted:u}=e,h=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await vp(c);nt(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:i,updatedAt:a,subChannelId:c,data:o,dataType:l,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ip=async e=>{var t,n,r,s;const{channelId:i,subChannelId:a}=e,o=null===(t=tt(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==o?void 0:o.subChannelId)===a){const e=null===(n=tt(["subChannel","get",a]))||void 0===n?void 0:n.data;nt(["messagePreviewChannel","get",i],Object.assign(Object.assign({},o),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(r=tt(["messagePreviewSubChannel","get",a]))||void 0===r?void 0:r.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=tt(["subChannel","get",a]))||void 0===s?void 0:s.data;nt(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Tp=["broadcast","conversation","community"],Ap=({type:e})=>Tp.includes(e);function Cp(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const s=null===(n=tt(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ap(e),messagePreviewId:r})}const _p=(e,t={isMessagePreviewUpdated:!0})=>{Ff({channels:e.channels.map((e=>Cp(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Rp=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ye(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})).filter((e=>{var t;const n=null===(t=tt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hf(n.createdAt)<=Hf(e.createdAt)}));0!==n.length&&Ff({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var r,s;const i=[];for(let a=0;a<t.length;a+=1)if(Ap(t[a])){const o=["channelUnread","get",t[a].channelId],l=n.find((n=>n.channelId===t[a].channelId&&n.userId===e)),c=null===(r=tt(o))||void 0===r?void 0:r.data,d=Math.max(null!==(s=null==c?void 0:c.lastSegment)&&void 0!==s?s:0,t[a].messageCount);let u=null,h=null,f=0,p=!1;if(l){const e=l.readToSegment,t=l.lastMentionedSegment;u="number"==typeof(null==c?void 0:c.readToSegment)&&("number"!=typeof e||c.readToSegment>e)?c.readToSegment:null!=e?e:null,h="number"==typeof(null==c?void 0:c.lastMentionedSegment)&&("number"!=typeof t||c.lastMentionedSegment>t)?c.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;f=Math.max(d-n,0),p="number"==typeof h&&n<h}const g={channelId:t[a].channelId,lastSegment:d,readToSegment:u,lastMentionedSegment:h,unreadCount:f,isMentioned:p,isDeleted:t[a].isDeleted||!1};nt(o,g),i.push(g)}i.length>0&&Ut("local.channelUnread.updated",i)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ap).map((({channelInternalId:e})=>e));if(n.length>0){_p(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ye();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:s}=n,i=Kf(r),a=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:i,userMarkers:s},{cachedAt:a}),Ut("local.channelMarker.fetched",{userEntityMarkers:i}),Ut("local.userMarker.fetched",{userMarkers:s}),{data:i,cachedAt:a}})(n)}catch(e){}}}const s=e.channels.map((e=>Cp(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),i=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ye().cache)return(null===(e=tt(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),a=e.users.map(fp),o=Bf(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},o),{users:a,channels:s,channelUsers:i})},Op=async e=>{const t=Ye();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Ut("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},kp=async e=>{const t=Ye(),n=await Op(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:s}=n;ep({feedMarkers:r,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Pp=(e,t)=>{var n,r,s,i;const a=Ye();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=tt(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(i=null===(s=(e=>{var t;const n={entityId:e,userId:Rt()._id};return null===(t=tt(["channelMarker","get",Je("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==i&&i},Dp=(e,t)=>{var n,r,s,i,a;const o=Ye();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=tt(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(i=(e=>{var t;const n={entityId:e,userId:Rt()._id};return null===(t=tt(["channelMarker","get",Je("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===i?void 0:i.unreadCount)&&void 0!==a?a:0},Lp=e=>{var t;return null===(t=tt(["channelUnread","get",e]))||void 0===t?void 0:t.data},xp=e=>{const t=Ye(),n=Bf(e,["messageCount"]);return zf(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Lp(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Dp(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Lp(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Pp(n)}})},Mp=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=tt(n))||void 0===t?void 0:t.data;return r?jt(r):void 0})()}}),Up=e=>{const t=Ye();t.log("channel/getMyMembership.locally");const n=tt(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Ge("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Fp(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Fp(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>Fp(e[n],t[n])))}const Np=[];let Bp=null;const jp=e=>{if(0===Np.length){const e=Ye(),t=async e=>{const t=await Rp(e);Ff(t),Np.forEach((e=>e(t.channels[0])))};Bp=Mt(e,"onChannelCreated","channel.created",t)}return Np.push(e),()=>(e=>{const t=Np.indexOf(e);t>-1&&Np.splice(t,1),0===Np.length&&(null==Bp||Bp())})(e)},$p=[],qp=[],Kp=e=>{const t=Ye();if(0===$p.length){const e=async e=>{const t=await Rp(e);Ff(t),$p.forEach((e=>e(t.channels[0])))};qp.push(Mt(t,"onChannelUpdated","channel.updated",e)),qp.push(Mt(t,"onChannelUpdated","local.channel.updated",(e=>$p.forEach((t=>t(e.channels[0]))))))}return $p.push(e),()=>(e=>{const t=$p.indexOf(e);t>-1&&$p.splice(t,1),0===$p.length&&qp.forEach((e=>e()))})(e)},Gp=e=>{const t=et(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{nt(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Wp=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=tt(n))||void 0===t?void 0:t.data)&&it(n)},Hp=[];let Vp=null;const Yp=e=>{if(0===Hp.length){const e=Ye(),t=async t=>{const n=await Rp(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)Gp(e.channelId),Wp(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=tt(t);n&&nt(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Ff(n),Hp.forEach((e=>e(n.channels[0])))};Vp=Mt(e,"onChannelDeleted","channel.deleted",t)}return Hp.push(e),()=>(e=>{const t=Hp.indexOf(e);t>-1&&Hp.splice(t,1),0===Hp.length&&(null==Vp||Vp())})(e)},Qp=[];let zp=null;const Jp=e=>{if(0===Qp.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),Qp.forEach((e=>e(n[0],r[0])))};zp=Mt(e,"onChannelJoined","channel.joined",t)}return Qp.push(e),()=>(e=>{const t=Qp.indexOf(e);t>-1&&Qp.splice(t,1),0===Qp.length&&(null==zp||zp())})(e)},Xp=[];let Zp=null;const eg=e=>{if(0===Xp.length){const e=Ye(),t=async t=>{const{userId:n}=Ye(),{channelUsers:r}=t,s=r.some((e=>e.userId===n)),i=await Rp(t,{isMessagePreviewUpdated:s}),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,o=e.useLegacyUnreadCount;s&&i.channels.forEach((e=>{a?(Gp(e.channelId),Wp(e.channelId)):o&&it(["channelUnread","get",e.channelId])}));const{channels:l,channelUsers:c}=i;Ff(i),Xp.forEach((e=>e(l[0],c[0])))};Zp=Mt(e,"onChannelLeft","channel.left",t)}return Xp.push(e),()=>(e=>{const t=Xp.indexOf(e);t>-1&&Xp.splice(t,1),0===Xp.length&&(null==Zp||Zp())})(e)},tg=[];let ng=null;const rg=e=>{if(0===tg.length){const e=Ye(),t=async e=>{var t;st(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&tg.forEach((e=>e(n)))};ng=Mt(e,"onChannelMute","channel.setMuted",t)}return tg.push(e),()=>(e=>{const t=tg.indexOf(e);t>-1&&tg.splice(t,1),0===tg.length&&(null==ng||ng())})(e)},sg=[];let ig=null;const ag=e=>{if(0===sg.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),sg.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))};ig=Mt(e,"onChannelMemberAdded","channel.membersAdded",t)}return sg.push(e),()=>(e=>{const t=sg.indexOf(e);t>-1&&sg.splice(t,1),0===sg.length&&(null==ig||ig())})(e)},og=[];let lg=null;const cg=e=>{if(0===og.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),og.forEach((e=>e(n[0],r[0])))};lg=Mt(e,"onChannelMemberRemoved","channel.membersRemoved",t)}return og.push(e),()=>(e=>{const t=og.indexOf(e);t>-1&&og.splice(t,1),0===og.length&&(null==lg||lg())})(e)},dg=[];let ug=null;const hg=e=>{const t=Ye();return ug=Mt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Rp(e),{channels:r,channelUsers:s}=n,i=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&i&&n.channels.forEach((e=>{Gp(e.channelId),Wp(e.channelId)})),Ff(n),dg.forEach((e=>e(r[0],s.find((e=>"banned"===e.membership)))))})),dg.push(e),()=>(e=>{const t=dg.indexOf(e);t>-1&&dg.splice(t,1),0===dg.length&&(null==ug||ug())})(e)},fg=[];let pg=null;const gg=e=>{if(0===fg.length){const e=Ye(),t=async e=>{const t=await Rp(e),{channels:n,channelUsers:r}=t;Ff(t),fg.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))};pg=Mt(e,"onChannelMemberUnbanned","channel.unbanned",t)}return fg.push(e),()=>(e=>{const t=fg.indexOf(e);t>-1&&fg.splice(t,1),0===fg.length&&(null==pg||pg())})(e)},mg=[];let yg=null;const vg=e=>{if(0===mg.length){const e=Ye(),t=async e=>{const{channels:t,channelUsers:n}=e;mg.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))};yg=Mt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",t)}return mg.push(e),()=>(e=>{const t=mg.indexOf(e);t>-1&&mg.splice(t,1),0===mg.length&&(null==yg||yg())})(e)},bg=[];let wg=null;const Sg=e=>{if(0===bg.length){const e=Ye(),t=async e=>{const{channels:t,channelUsers:n}=e;bg.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))};wg=Mt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",t)}return bg.push(e),()=>(e=>{const t=bg.indexOf(e);t>-1&&bg.splice(t,1),0===bg.length&&(null==wg||wg())})(e)},Eg=e=>{const t=Ye();return Mt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Ig=e=>{const t=Ye();return Mt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Tg=[];let Ag=null;const Cg=e=>{if(0===Tg.length){const e=Ye(),t=async e=>{var t,n,r;e.userIds.forEach((t=>st(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=et(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,i=null===(r=tt(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===r?void 0:r.data;s&&i&&Tg.forEach((e=>e(s,i)))};Ag=Mt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Tg.push(e),()=>(e=>{const t=Tg.indexOf(e);t>-1&&Tg.splice(t,1),0===Tg.length&&(null==Ag||Ag())})(e)},_g=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=et(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Mp(e))))}return zf(e,{markAsRead:()=>(async e=>{const t=Ye();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:i}=n,a=Bf(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=t.cache&&Date.now(),l=Kf(s),c=Gf(i);return t.cache&&Ff(Object.assign({userMarkers:r,userEntityMarkers:l,userFeedMarkers:c},a),{cachedAt:o}),Ut("local.channelMarker.updated",{userEntityMarkers:l}),Ut("local.subChannelMarker.updated",{userFeedMarkers:c}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Rt();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:s}=Ye();s||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const i=[];let a=!1;const o=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Mp(e.data):e.data}))},l=(t,n)=>{const{data:r}=Up(e);Fp(void 0,r)||o({loading:!1,data:r})};return i.push(hg(l)),i.push(gg(l)),i.push(Cg(l)),(()=>{const t=Be((async()=>Up(e)));$e(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,i.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&i.forEach((e=>e()))}))})(),()=>{i.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Rg=e=>_g(xp((e=>{var t;const n=e.messagePreviewId?Wf(e.channelId):null,r=null===(t=tt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:r?jt(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),Og=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("channel",e)})),t}const s=await Rp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(r);const i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("local.channel.fetched",s.channels),{data:s.channels.map((e=>Rg(e))),cachedAt:i}};Og.locally=e=>{var t,n;const r=Ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const i=s.map((({data:e})=>e)),a=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:i.map((e=>Rg(e))),cachedAt:a.cachedAt}};const kg=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Pg=!1;const Dg={},Lg=async()=>{const e=Object.entries(Dg).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ye();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=n,o=Kf(r),l=Gf(s),c=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Ut("local.feedMarker.fetched",{feedMarkers:i}),Ut("local.channelMarker.fetched",{userEntityMarkers:o}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:l}),Ut("local.userMarker.fetched",{userMarkers:a}),!0})(e)},xg=()=>{Pg=!1},Mg=()=>(Pg=!0,Th((e=>{"notLoggedIn"===e&&xg()})),()=>{xg()});kg((async()=>{Pg&&await Lg()}),3e4);const Ug=async e=>{const t=Ye();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:s}};Ug.locally=e=>{var t;const n=Ye();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>tt(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Fg=async(e=!0)=>{var t;const n=null===(t=tt(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await Uf();var s;return(s=r).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Ng=async()=>{var e;const t=await Fg();if(t===(null===(e=tt(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;nt(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=et(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=et(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Og(n),0!==r.length&&await Ug(r)}},Bg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},jg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},$g={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},qg=async()=>{var t,n;const r=Ye(),{data:s}=await r.http.get("/api/v3/network-settings/video-streaming"),i=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,a=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(o=i)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&o!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&o!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(a)?(r.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:i,threshold:a}),$g):{mode:i,threshold:a};var o},Kg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Gg=async()=>{var e,t;const n=Ye(),{data:r}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=r.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},Wg=(e,t)=>{var n;const r=null===(n=tt(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Hg=e=>{const{userId:t}=Ye();return{currentUser:()=>Wg(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=tt(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Wg(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=tt(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Wg(e,t))})(t,e,n)}},Vg=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},Yg=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},Qg=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},zg={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Jg=(e,t)=>{const n=Ye();n.log("client/api/setSessionState",e,t);const{sessionState:r}=n;if(r===e)return!1;if(!((e,t)=>zg[e].includes(t))(r,e))throw new Ke(`Session state cannot change from ${r} to ${e}`,8e5,"error");return n.sessionState=e,Ih().setSessionState(e,t),!0};function Xg(e){return{users:e.users.map(fp),files:e.files}}const Zg=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getToken",e);const r=Df(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},em=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getVisitorToken",e);const r=Df(),{data:s}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},tm=async()=>{var e;const t=Ye();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&Jg("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=void 0,t.isGloballyBanned=!1,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},nm=e=>{const t=Ye();Jg("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,tm()};let rm=null;const sm=e=>{rm=e},im=({user:e,userType:t})=>{Ot(e),sm(t)},am=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Xg(e);n.cache&&Ff(r),t(r.users[0])}))},om=e=>am("user.deleted",e),lm=["analytic","normal-priority"],cm=["analytic","high-priority"],dm=async e=>{const t=Ye(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class um{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=tt(lm);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await dm(t),it(lm)}catch(e){this.stop(),it(lm)}}async syncHighPriorityCapturedEvent(){try{const e=tt(cm);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await dm(t),it(cm)}catch(e){this.stop(),it(cm)}}}class hm{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(r.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const i=new Date,a={event:[]},o=tt(lm);(null==o?void 0:o.data)&&(a.event=o.data.event),a.event.length>=this._poolLimit&&a.event.shift();const l={contentId:t,contentType:n,activityType:r,timestamp:i.toISOString()};s&&(l.metadata=s),a.event.push(l),st(lm,a),this._recentViewed[e]=i}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const r=null===(n=tt(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),r&&(s.feedSnapshotPosition=r.feedSnapshotPosition,s.feedInjectionType=r.feedInjectionType,s.feedRelevanceScore=r.feedRelevanceScore,s.feedPopularityScore=r.feedPopularityScore,s.feedFreshnessScore=r.feedFreshnessScore,s.feedAffinityScore=r.feedAffinityScore,s.feedFinalScore=r.feedFinalScore,s.feedMmrPenalty=r.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const s={event:[]},i=tt(cm);if((null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),st(cm,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;nt(["story-seen","get",e.storyId],(new Date).toISOString());const a=tt(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&nt(["story-last-seen",e.targetId],e.expiresAt):nt(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Ut("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},it(lm),it(cm)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markProductAsClicked(e,t,n,r){const s={location:t,sourceType:n,sourceId:r},i="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:i,metadata:s})}markProductAsViewed(e,t,n,r){const s={location:t,sourceType:n,sourceId:r},i="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:i,metadata:s})}}class fm{constructor(){this._client=Ye(),this._eventCapturer=new hm,this._eventSyncer=new um}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}markProductAsClicked(e,t,n,r){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,r)}markProductAsViewed(e,t,n,r){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,r)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let pm;var gm=()=>(pm||(pm=new fm),pm),mm=()=>{const e=gm();return e.established(),Th((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class ym{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=et(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=tt(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Ye();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],s=null===(t=tt(r))||void 0===t?void 0:t.data;nt(r,Object.assign(Object.assign({},s),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],s=null===(n=tt(r))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),nt(r,s),Ut("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=tt(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)nt(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{nt(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let vm=null;var bm=()=>(vm||(vm=new ym),vm),wm=()=>{const e=bm();return e.startSyncReadReceipt(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Sm{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=et(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=tt(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:s}=n,i=await(async({subChannelId:e,readToSegment:t})=>{const n=Ye();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:s});if(i){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=tt(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;nt(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else i||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],s=null===(n=tt(r))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=Zf(s.channelId);Ut("local.channelUnreadInfo.updated",e),nt(r,s),Ut("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=tt(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)nt(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{nt(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let Em=null;var Im=()=>(Em||(Em=new Sm),Em),Tm=()=>{const e=Im();return e.startSyncReadReceipt(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Am=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("online",e),()=>window.removeEventListener("online",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("online",e),()=>document.removeEventListener("online",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),Cm=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("offline",e),()=>window.removeEventListener("offline",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("offline",e),()=>document.removeEventListener("offline",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),_m=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("channel",e)})),t}const s=await Rp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(r);const i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("local.channel.fetched",s.channels),{data:s.channels,cachedAt:i}};_m.locally=e=>{var t,n;const r=Ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Rm{constructor(){this.TIMER_INTERVAL_MS=J,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Am((()=>{this.isConnected=!0}))),this.connectionListener.push(Cm((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await _m(e);const s=null!==(r=null===(n=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];Ut("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await Op(e),{feedMarkers:n,userFeedMarkers:r}=t;ep({feedMarkers:n,userFeedMarkers:r}),Ut("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Om=null;var km=()=>(Om||(Om=new Rm),Om),Pm=()=>{const e=km();return e.startResolver(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Dm{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Am((()=>{this.isConnected=!0}))),this.connectionListener.push(Cm((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{roomId:n,streamId:r}=t,s=Bf(t,["roomId","streamId"]),i=r?"liveStream":"room",a=null!=r?r:n;return e[a]||(e[a]={referenceType:i,reactions:[]}),e[a].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const r=Ye();r.log("live_reaction/addReaction",e);const{data:s}=await r.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Lm;var xm=()=>(Lm||(Lm=new Dm),Lm);function Mm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:fp(n)})})),users:t.map(fp)})}class Um{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),r=Mm(t);e.cache&&Ff(r,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=et(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,r;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(r=t.updatedAt)&&void 0!==r?r:"")?1:-1})).map((e=>{var t;return null===(t=tt(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(jt)}}let Fm=null;var Nm=()=>(Fm||(Fm=new Um),Fm);function Bm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:fp(n)})})),users:t.map(fp)})}class jm{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),r=Bm(t);e.cache&&Ff(r,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=et(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,r;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(r=t.updatedAt)&&void 0!==r?r:"")?1:-1})).map((e=>{var t;return null===(t=tt(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(jt)}}let $m=null;var qm=()=>($m||($m=new jm),$m);function Km(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(fp)})}function Gm(e){const{users:t,follows:n}=e,r=Bf(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(fp)})}function Wm(e){const{follows:t}=e,n=Bf(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Hm=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Km(e);n.cache&&Ff(r),t(r.follows[0])}))},Vm=e=>Hm("user.didBlock",e),Ym=e=>Hm("user.didUnblock",e);class Qm{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=$t();if(!e)return null;const t=Gt(e),{userId:n}=e;return t&&n?new Qm(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return Th((e=>{var t;"terminated"===e&&(null===(t=Qm.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await xh(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await Lh(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await Lh(this.key,"")}}const zm=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Jm=e=>{const t=Ye(),n=zm.map((n=>Mt(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new Ke(t.message,t.code,"fatal"):new He(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Xm=e=>{const t=Ye();return Mt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Zm=e=>{const t=Ye();return Mt(t,"client/onTokenExpired","tokenExpired",e)},ey=e=>{const t=Ye();return Mt(t,"client/onTokenTerminated","tokenTerminated",e)},ty=e=>{const t=Je("channelMarker")({userId:Rt()._id,entityId:e.channelId});it(["channelMarker","get",t],!0)},ny=e=>{const t=Ye(),n=[];return n.push(Xm((t=>{nm("globalBan"),n.forEach((e=>e())),e()})),ey((t=>{nm(),n.forEach((e=>e())),e()})),om((r=>{r.userId===t.userId&&(nm("userDeleted"),n.forEach((e=>e())),e())})),Zm((e=>{Ih().setSessionState(e),tm(),n.forEach((e=>e()))})),Yp(ty),hg(ty),Mg(),mm(),Pm(),(()=>{const e=xm();return e.startReactionsSync(),Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Nm();return Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=qm();return Th((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Vm((()=>{})),Ym((()=>{}))];return()=>e.forEach((e=>e()))})(),Th((e=>{"established"!==e&&kh().reset()})),Qm.clearOnLogout()),t.useLegacyUnreadCount?n.push(wm()):n.push(Tm()),n};let ry=[];const sy=async(e,t,n)=>{const r=Ye();let s;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await tm(),ry.forEach((e=>e())),ry=[]);const i=await Pf();try{const{users:n,userType:a}=await Zg({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||i}),options:{setAccessTokenCookie:!0}}),o=n.find((t=>t.userId===e.userId));if(null==o)throw new Ke(`${e.userId} has not been founded`,8e5,"error");if(o.isDeleted)return nm("userDeleted"),!1;if(o.isGlobalBan)return nm("globalBan"),!1;r.userId=o.userId,r.sessionHandler=t,r.loginType="userId",s=r.accessTokenExpiryWatcher(),im({user:o,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Bt()}(),await Ng(),0===ry.length&&(ry=ny(s)),!0},iy=[],ay=async e=>{const t=Ye();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const r=await Pf();let s;try{const{users:i,userType:a}=await em({params:Object.assign(Object.assign({},e),{deviceId:r}),options:{setAccessTokenCookie:!0}});[s]=i,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),im({user:s,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return await Ng(),0===iy.length&&iy.push(ey((e=>{nm(),iy.forEach((e=>e())),n()})),Zm((e=>{Ih().setSessionState(e),tm(),iy.forEach((e=>e()))}))),!0},oy=()=>{let e,t=!1;const n=Ye();n.log("initiating access token renewal");const r=async r=>{const{userId:s,displayName:i}=Rt(),a={userId:s,displayName:i,authToken:r,deviceId:await Pf()};"tokenExpired"===n.sessionState&&n.sessionHandler?await sy(a,n.sessionHandler):await Zg({params:a,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(oy())}),X)},renewWithAuthSignature:r=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:r,authSignatureExpiresAt:s})=>{const i=await Pf();"tokenExpired"===n.sessionState&&n.sessionHandler?await ay({sessionHandler:n.sessionHandler}):await em({params:{authSignature:r,authSignatureExpiresAt:s,deviceId:i},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(r)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(oy())}),X)}}};function ly(e){this.message=e}ly.prototype=new Error,ly.prototype.name="InvalidCharacterError";var cy="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new ly("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,s=0,i=0,a="";r=t.charAt(i++);~r&&(n=s%4?64*n+r:r,s++%4)?a+=String.fromCharCode(255&n>>(-2*s&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a};function dy(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(cy(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return cy(t)}}function uy(e){this.message=e}function hy(e,t){if("string"!=typeof e)throw new uy("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(dy(e.split(".")[n]))}catch(e){throw new uy("Invalid token specified: "+e.message)}}uy.prototype=new Error,uy.prototype.name="InvalidTokenError";const fy=async({token:e,userId:t})=>{const n=Ye(),{data:r}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:i,userType:a}=r,[o]=s;return t&&(null==o?void 0:o.userId)&&t!==o.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:o.userId}),n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,Ff(Xg({users:s,files:i})),sm(a),o},py=e=>{var t;const n=Ye(),r=hy(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId};let gy=[];const my=async e=>{var t,n;const r=Ye();let s,i;if(r.log("client/api/loginWithAccessToken",{apiKey:r.apiKey,sessionState:r.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Ke("Access token must be a non-empty string",8e5,"error");try{i=hy(e)}catch(e){throw new Ke("Invalid access token format",400100,"error")}const a=(null===(t=null==i?void 0:i.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==i?void 0:i.user)||void 0===n?void 0:n.userId);if(!a)throw new Ke("Access token does not contain userId",400100,"error");if(r.userId){py(e)||await tm()}try{Jg("establishing");const t={accessToken:e,issuedAt:i.iat?new Date(1e3*i.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*i.exp).toISOString()},n=await fy({token:t,userId:a});if(null==n)throw Jg("notLoggedIn"),new Ke(`User ${a} has not been found`,8e5,"error");r.userId=n.userId,r.loginType="accessToken",Ot(n),s=r.accessTokenExpiryWatcher(),Jg("established")}catch(e){if(Jg("notLoggedIn"),e instanceof Ke)throw 400312===e.code&&(r.isGloballyBanned=!0),e;throw new Ke((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await Bt()}(),await Ng(),0===gy.length&&(gy=ny(s)),!0},yy=async e=>{var t,n;const r=Ye();if(r.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Ke("Access token must be a non-empty string",8e5,"error");let s;try{s=hy(e)}catch(e){throw new Ke("Invalid access token format",400100,"error")}const i=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!i)throw new Ke("Access token does not contain userId",400100,"error");if(r.userId){py(e)||await tm()}const a={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===r.sessionState&&r.sessionHandler)await my(e);else try{await fy({token:a,userId:i})}catch(e){throw e instanceof Ke&&400312===e.code&&(r.isGloballyBanned=!0),e}},vy=async({useScheduledTask:e=!1})=>{const t=Ye();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Dt((()=>yy(n))):yy(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},by=3e5,wy=()=>{const e=setInterval((async()=>{const e=Ye(),{sessionHandler:t,accessTokenHandler:n,loginType:r}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:i}=e.token;if((e=>Date.now()>Date.parse(e)-by)(i))return Ut("tokenExpired","tokenExpired"),void("accessToken"===r&&n?await vy({useScheduledTask:!1}):"userId"===r&&t&&Dt((()=>t.sessionWillRenewAccessToken(oy()))));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),s=Date.parse(n),i=Date.now();return i>s+.8*(r-s-by)&&i<r})({expiresAt:i,issuedAt:s})&&("accessToken"===r&&n?await vy({useScheduledTask:!1}):"userId"===r&&t&&t.sessionWillRenewAccessToken(oy()))}),X);return()=>clearInterval(e)},Sy=e=>{if(Ye().useLegacyUnreadCount){bm().markRead(e.channelId,e.channelSegment)}else{Im().markRead(e.subChannelId,e.channelSegment)}},Ey=e=>{const t=Ye(),n=Rt(),r=[Mt(t,"message/onMessageCreated","message.created",(async r=>{const s=await dp(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Ye(),r=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=tt(r))||void 0===t?void 0:t.data;if(!s)return;const i=s.lastSegment<e.segment?e.segment:s.lastSegment,a=i-s.readToSegment;let{lastMentionSegment:o}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(o=e.segment)}));const l=Object.assign(Object.assign({},s),{lastMentionSegment:o,lastSegment:i,isMentioned:!(s.readToSegment>=o),unreadCount:Math.max(a,0)});nt(r,l)})(e),Zf(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r,s;const i=null===(n=tt(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!i||i.lastSegment>=e.segment)return;const a=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:i.lastMentionedSegment,l=null!==(s=i.readToSegment)&&void 0!==s?s:0,c=Object.assign(Object.assign({},i),{lastSegment:a,unreadCount:Math.max(a-l,0),lastMentionedSegment:o,isMentioned:"number"==typeof o&&l<o});nt(["channelUnread","get",e.channelId],c),Ut("local.channelUnread.updated",[c])})),Ff(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&Sy(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Iy=e=>{const t=Ye(),n=[Mt(t,"message/onMessageCreated","local.message.created",(async t=>(Ff(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Ty=e=>{const t=Ye();return Mt(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await mp(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:s}=e,i={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:s};nt(["subChannelUnreadInfo","get",i.subChannelId],i)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Ff(r),e(r.messageFeeds[0])}))},Ay=e=>{const t=Ye(),n=[Mt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await mp(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=tt(n))||void 0===t?void 0:t.data;r&&nt(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),Zf(e.channelId)})),Ff(r),e(r.messageFeeds[0])})),Mt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Cy=async e=>{const t=Ye();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=n,o=Kf(r),l=Gf(s),c=t.cache&&Date.now();return t.cache&&Ff({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Ut("local.feedMarker.fetched",{feedMarkers:i}),Ut("local.channelMarker.fetched",{userEntityMarkers:o}),Ut("local.subChannelMarker.fetched",{userFeedMarkers:l}),Ut("local.userMarker.fetched",{userMarkers:a}),{data:n,hasMore:n.feedMarkers.length>0}};let _y=!1,Ry=[],Oy=!1;let ky=null;let Py=[];const Dy=e=>{Py=e},Ly=async()=>{var e;if(!Oy&&0!==Py.length)try{Oy=!0,Py=[];const t=await Cy((null==ky?new Date:ky).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!ky||e.getTime()>ky.getTime())&&(ky=e),t.hasMore&&Py.push("has_more")}catch(e){}finally{Oy&&(Oy=!1)}};kg((async()=>{_y&&await Ly()}),2e3);const xy=()=>true;let My=[];var Uy;class Fy{constructor(){Uy.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?s.call(e,n):s?s.value=n:t.set(e,n)}(this,Uy,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,Uy,"f")}}let Ny;Uy=new WeakMap;var By=()=>(Ny||(Ny=new Fy),Ny);const jy={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},$y=async e=>{const t=Ye();Jg("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i,userType:a,files:o}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getBotToken");const r=Df(),{data:s}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:i,expiresAt:s},Jg("established"),Ff(Xg({users:r,files:o})),{accessToken:n,users:r,userType:a}},qy=[];function Ky(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function Gy(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Wy{constructor(e){this.channelId=e}async enable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ye(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Hy{async enable(t){var n;const r=Ye(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Gy(e.rolesFilter)))))&&void 0!==n?n:[],i={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await r.http.post("/api/v3/notification/setting",i)}async disableAllNotifications(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:r}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),i=(null!==(t=r.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:Ky(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:r.isPushNotifiable,modules:i}}}class Vy{constructor(e){this.communityId=e}async enable(t){var n;const r=Ye(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Gy(t.rolesFilter)))))&&void 0!==n?n:[],i={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await r.http.post("/api/v3/notification/setting",i)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:r}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),i=(null!==(t=r.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:Ky(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:r.isPushNotifiable,events:i}}}class Yy{user(){return new Hy}community(e){return new Vy(e)}channel(e){return new Wy(e)}}const Qy=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},zy=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Jy=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Xy=e=>{const t=Ye();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Zy=e=>{const t=Ye();return Mt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ev=e=>{const t=Ye();return Mt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,s;Ff(t);const i=et(["message","collection"]),{contentMarkers:a,feedMarkers:o}=t;if(i&&(null==i?void 0:i.length)>0&&(null==o?void 0:o.length)>0){const e=i.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===o[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(s=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>tt(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const r=["messageMarker","get",Je("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=tt(r))||void 0===t?void 0:t.data;if(!s)return;const i=a[0].feedId===s.feedId,o=a[0].readCount>s.readCount,l=(null===(n=a[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(i){const e=Object.assign(Object.assign({},s),{readCount:o?a[0].readCount:s.readCount,deliveredCount:l?a[0].deliveredCount:s.deliveredCount});nt(r,e)}}))}}e(t.contentMarkers[0])}))};function tv(e){return"object"==typeof e&&null!==e}const nv=e=>{if(!tv(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},rv=e=>{if(!tv(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var sv=Object.freeze({__proto__:null,getActiveClient:Ye,getActiveUser:Rt,setActiveUser:Ot,createClient:(e,t=hn.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:s,rteEnabled:i=!0}={})=>{var a,o,l;const c=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!un,n=ln(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);c("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(a=null==r?void 0:r.http)&&void 0!==a?a:pn("http",t),u=null!==(o=null==r?void 0:r.upload)&&void 0!==o?o:pn("upload",t),h=null!==(l=null==r?void 0:r.mqtt)&&void 0!==l?l:pn("mqtt",t),f=Ps(d),p=Ps(u);let g;i&&(g=Mf(h));const m=xt(),y={version:`${G}`,apiKey:e,log:c,cache:{data:{}},http:f,ws:undefined,mqtt:g,upload:p,emitter:m,sessionState:"notLoggedIn",accessTokenExpiryWatcher:wy,sessionHandler:undefined,hasPermission:Hg,validateUrls:Vg,validateTexts:Yg,getFeedSettings:Qg,getCoreUserSettings:jg,getSocialSettings:Bg,getChatSettings:Uf,getLiveViewerCountConfig:qg,getVisitorDeviceId:Pf,getMessagePreviewSetting:Fg,use:()=>Qe(y),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:xy,getProductCatalogueSetting:Kg,getForYouFeedSetting:Gg,prefixDeviceIdKey:s};try{const t=Ye();if(t.apiKey===e)return t;Qe(y)}catch(e){Qe(y)}return y},login:sy,loginWithAccessToken:my,logout:tm,secureLogout:async()=>{const e=Ye(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await tm()},resumeSession:async(e,t,n)=>{const r=Ye();let s;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&py(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),My.forEach((e=>e())),My=[]):(await tm(),My.forEach((e=>e())),My=[]));try{Jg("establishing");const n=await fy(e);if(null==n)throw new Ke(`${e.userId} has not been found`,8e5,"error");r.userId=n.userId,r.sessionHandler=t,s=r.accessTokenExpiryWatcher(),Ot(n)}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Bt()}(),await Ng(),0===My.length&&(My.push(Xm((e=>{nm("globalBan"),My.forEach((e=>e())),s()})),ey((e=>{nm(),My.forEach((e=>e())),s()})),om((e=>{e.userId===r.userId&&(nm("userDeleted"),My.forEach((e=>e())),s())})),Zm((e=>{Ih().setSessionState(e),tm(),My.forEach((e=>e()))})),Yp(ty),hg(ty),Mg(),mm(),Pm()),r.useLegacyUnreadCount?My.push(wm()):My.push(Tm())),!0},isConnected:()=>{var e,t;const n=Ye();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:Qg,renewal:oy,markerSync:Cy,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){By().setFileAccessType(e)},fetchLinkPreview:async e=>{const t=Ye();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getLinkPreviewMetadata:async e=>{const t=Ye(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Bg,getShareableLinkConfiguration:async()=>{var e,t;const n=Ye(),{data:r}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=r.domain)&&void 0!==e?e:"",i=null!==(t=r.patterns)&&void 0!==t?t:{};return{domain:s,patterns:i,isEnabled(e){const{key:t}=jy[e];return!!s&&!!i[t]},getPattern(e){const{key:t}=jy[e];return i[t]||null},generateLink(e,t){const{key:n,placeholder:r}=jy[e];return s&&i[n]?s+i[n].replace(`{${r}}`,t):null}}},getProductCatalogueSetting:Kg,getForYouFeedSetting:Gg,loginAsVisitor:ay,loginAsBot:async e=>{const t=Ye();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const r=await Pf();let s;try{const{users:i,userType:a}=await $y({params:{deviceId:r},options:{setAccessTokenCookie:!0}});[s]=i,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),im({user:s,userType:a})}catch(e){throw Ih().setSessionState("notLoggedIn"),e}return await Ng(),0===qy.length&&qy.push(ey((e=>{nm(),qy.forEach((e=>e())),n()})),Zm((e=>{Ih().setSessionState(e),tm(),qy.forEach((e=>e()))}))),!0},getCurrentUser:$t,getCurrentUserType:()=>{if(!rm)throw new Ke("Connect client first",8e5,"fatal");return rm},setCurrentUserType:sm,setAccessTokenHandler:e=>{const t=Ye();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Uf,getLiveViewerCountConfig:qg,getCoreUserSettings:jg,notifications:()=>new Yy,enableAutoSubscriptions:e=>{const t=kh();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=kh();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>kh().subscriptions(),onConnectionError:Jm,onClientDisconnected:e=>Jm((({code:t})=>{800211===t&&e()})),onClientBanned:Xm,onSessionStateChange:Th,onNetworkActivities:e=>_s().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ye();return Mt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Rt();if(!t)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ye();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;i=r?nv(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(Xy((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),s=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};Fp(i,a)||o({loading:!1,data:a})})(e)))),(()=>{const e=Be(tp);$e(e,(({error:e,data:t,loading:n,origin:r,cachedAt:i})=>{!function(e){return null!=e&&null!=e}(t)?o({loading:n,data:void 0,origin:r,error:e}):(i===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Py,setMarkerSyncEvents:Dy,pushMarkerSyncEvent:e=>Py.push(e),markerSyncTrigger:Ly,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{_y=!1,Dy([]),Ry.forEach((e=>e())),Ry=[]},getMarkerSyncConsistentMode:xy});const iv=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Km(e);n.cache?(Ff(r),t(r.follows[0])):t(r.follows[0])}))},av=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Wm(e);n.cache?(Ff(r),t(r.follows[0])):t(r.follows[0])}))},ov=e=>iv("follow.created",e),lv=e=>iv("follow.unfollowed",e),cv=e=>iv("follow.followerDeleted",e),dv=e=>iv("follow.requested",e),uv=e=>iv("follow.requestCanceled",e),hv=e=>iv("follow.accepted",e),fv=e=>iv("follow.requestDeclined",e),pv=async e=>{var t,n;const r=Ye();r.log("follow/getFollowInfo",e);const{data:s}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),i=r.cache&&Date.now(),a="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return r.cache&&nt(["followInfo","get",e],a,{cachedAt:i}),{data:a,cachedAt:i}};pv.locally=e=>{const t=Ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=tt(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const gv=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([pv(t.from),pv(t.to)]);e(n),e(r)},n=[iv("follow.created",t),iv("follow.requested",t),iv("follow.accepted",t),iv("follow.unfollowed",t),iv("follow.requestCanceled",t),iv("follow.requestDeclined",t),iv("follow.followerDeleted",t),av("local.follow.created",t),av("local.follow.requested",t),av("local.follow.accepted",t),av("local.follow.unfollowed",t),av("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mv=e=>av("local.follow.created",e),yv=e=>av("local.follow.unfollowed",e),vv=e=>av("local.follow.requested",e),bv=e=>av("local.follow.accepted",e),wv=e=>av("local.follow.requestDeclined",e);function Sv(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ev={exports:{}};Ev.exports=function e(t,n,r){function s(a,o){if(!n[a]){if(!t[a]){if(!o&&Sv)return Sv(a);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}o=n[a]={exports:{}},t[a][0].call(o.exports,(function(e){return s(t[a][1][e]||e)}),o,o.exports,e,t,n,r)}return n[a].exports}for(var i=Sv,a=0;a<r.length;a++)s(r[a]);return s}({1:[function(e,t,n){(function(r,s,i,a,o,l,c,d,u){var h=e("crypto");function f(e,t){var n;return void 0===(n="passthrough"!==(t=m(e,t)).algorithm?h.createHash(t.algorithm):new b).write&&(n.write=n.update,n.end=n.update),v(t,n).dispatch(e),n.update||n.end(""),n.digest?n.digest("buffer"===t.encoding?void 0:t.encoding):(e=n.read(),"buffer"!==t.encoding?e.toString(t.encoding):e)}(n=t.exports=f).sha1=function(e){return f(e)},n.keys=function(e){return f(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},n.MD5=function(e){return f(e,{algorithm:"md5",encoding:"hex"})},n.keysMD5=function(e){return f(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var p=h.getHashes?h.getHashes().slice():["sha1","md5"],g=(p.push("passthrough"),["buffer","hex","binary","base64"]);function m(e,t){var n={};if(n.algorithm=(t=t||{}).algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<p.length;++r)p[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=p[r]);if(-1===p.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+p.join(", "));if(-1===g.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+g.join(", "));return n}function y(e){if("function"==typeof e)return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function v(e,t,n){function r(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return n=n||[],{dispatch:function(t){return this["_"+(null===(t=e.replacer?e.replacer(t):t)?"null":typeof t)](t)},_object:function(t){var s,a=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(a);if(o=(o=o?o[1]:"unknown:["+a+"]").toLowerCase(),0<=(a=n.indexOf(t)))return this.dispatch("[CIRCULAR:"+a+"]");if(n.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return r("buffer:"),r(t);if("object"===o||"function"===o||"asyncfunction"===o)return a=Object.keys(t),e.unorderedObjects&&(a=a.sort()),!1===e.respectType||y(t)||a.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(a=a.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+a.length+":"),s=this,a.forEach((function(n){s.dispatch(n),r(":"),e.excludeValues||s.dispatch(t[n]),r(",")}));if(!this["_"+o]){if(e.ignoreUnknown)return r("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,s){s=void 0!==s?s:!1!==e.unorderedArrays;var i=this;if(r("array:"+t.length+":"),!s||t.length<=1)return t.forEach((function(e){return i.dispatch(e)}));var a=[];return s=t.map((function(t){var r=new b,s=n.slice();return v(e,r,s).dispatch(t),a=a.concat(s.slice(n.length)),r.read().toString()})),n=n.concat(a),s.sort(),this._array(s,!1)},_date:function(e){return r("date:"+e.toJSON())},_symbol:function(e){return r("symbol:"+e.toString())},_error:function(e){return r("error:"+e.toString())},_boolean:function(e){return r("bool:"+e.toString())},_string:function(e){r("string:"+e.length+":"),r(e.toString())},_function:function(t){r("fn:"),y(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return r("number:"+e.toString())},_xml:function(e){return r("xml:"+e.toString())},_null:function(){return r("Null")},_undefined:function(){return r("Undefined")},_regexp:function(e){return r("regex:"+e.toString())},_uint8array:function(e){return r("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return r("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return r("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return r("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return r("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return r("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return r("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return r("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return r("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return r("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return r("url:"+e.toString())},_map:function(t){return r("map:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_set:function(t){return r("set:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_file:function(e){return r("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return r("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return r("domwindow")},_bigint:function(e){return r("bigint:"+e.toString())},_process:function(){return r("process")},_timer:function(){return r("timer")},_pipe:function(){return r("pipe")},_tcp:function(){return r("tcp")},_udp:function(){return r("udp")},_tty:function(){return r("tty")},_statwatcher:function(){return r("statwatcher")},_securecontext:function(){return r("securecontext")},_connection:function(){return r("connection")},_zlib:function(){return r("zlib")},_context:function(){return r("context")},_nodescript:function(){return r("nodescript")},_httpparser:function(){return r("httpparser")},_dataview:function(){return r("dataview")},_signal:function(){return r("signal")},_fsevent:function(){return r("fsevent")},_tlswrap:function(){return r("tlswrap")}}}function b(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}n.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),v(t=m(e,t),n).dispatch(e)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,n){(function(e,t,r,s,i,a,o,l,c){!function(e){var t="undefined"!=typeof Uint8Array?Uint8Array:Array,n="+".charCodeAt(0),r="/".charCodeAt(0),s="0".charCodeAt(0),i="a".charCodeAt(0),a="A".charCodeAt(0),o="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===n||e===o?62:e===r||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<a+26?e-a:e<i+26?e-i+26:void 0}e.toByteArray=function(e){var n,r;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.length,i=(s="="===e.charAt(s-2)?2:"="===e.charAt(s-1)?1:0,new t(3*e.length/4-s)),a=0<s?e.length-4:e.length,o=0;function l(e){i[o++]=e}for(n=0;n<a;n+=4,0)l((16711680&(r=c(e.charAt(n))<<18|c(e.charAt(n+1))<<12|c(e.charAt(n+2))<<6|c(e.charAt(n+3))))>>16),l((65280&r)>>8),l(255&r);return 2==s?l(255&(r=c(e.charAt(n))<<2|c(e.charAt(n+1))>>4)):1==s&&(l((r=c(e.charAt(n))<<10|c(e.charAt(n+1))<<4|c(e.charAt(n+2))>>2)>>8&255),l(255&r)),i},e.fromByteArray=function(e){var t,n,r,s,i=e.length%3,a="";function o(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)a+=o((s=n=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+o(s>>12&63)+o(s>>6&63)+o(63&s);switch(i){case 1:a=(a+=o((n=e[e.length-1])>>2))+o(n<<4&63)+"==";break;case 2:a=(a=(a+=o((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+o(n>>4&63))+o(n<<2&63)+"="}return a}}(void 0===n?this.base64js={}:n)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(e,t,n){(function(t,r,s,i,a,o,l,c,d){var u=e("base64-js"),h=e("ieee754");function s(e,t,n){if(!(this instanceof s))return new s(e,t,n);var r,i,a,o,l=typeof e;if("base64"===t&&"string"==l)for(e=(o=e).trim?o.trim():o.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==l)r=k(e);else if("string"==l)r=s.byteLength(e,t);else{if("object"!=l)throw new Error("First argument needs to be a number, array or string.");r=k(e.length)}if(s._useTypedArrays?i=s._augment(new Uint8Array(r)):((i=this).length=r,i._isBuffer=!0),s._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(P(o=e)||s.isBuffer(o)||o&&"object"==typeof o&&"number"==typeof o.length)for(a=0;a<r;a++)s.isBuffer(e)?i[a]=e.readUInt8(a):i[a]=e[a];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!n)for(a=0;a<r;a++)i[a]=0;return i}function f(e,t,n,r){return s._charsWritten=M(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function p(e,t,n,r){return s._charsWritten=M(function(e){for(var t,n,r=[],s=0;s<e.length;s++)t=(n=e.charCodeAt(s))>>8,n%=256,r.push(n),r.push(t);return r}(t),e,n,r)}function g(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;s++)r+=String.fromCharCode(e[s]);return r}function m(e,t,n,r){var s;if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!((r=e.length)<=t))return n?(s=e[t],t+1<r&&(s|=e[t+1]<<8)):(s=e[t]<<8,t+1<r&&(s|=e[t+1])),s}function y(e,t,n,r){var s;if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!((r=e.length)<=t))return n?(t+2<r&&(s=e[t+2]<<16),t+1<r&&(s|=e[t+1]<<8),s|=e[t],t+3<r&&(s+=e[t+3]<<24>>>0)):(t+1<r&&(s=e[t+1]<<16),t+2<r&&(s|=e[t+2]<<8),t+3<r&&(s|=e[t+3]),s+=e[t]<<24>>>0),s}function v(e,t,n,r){if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 32768&(r=m(e,t,n,!0))?-1*(65535-r+1):r}function b(e,t,n,r){if(r||(j("boolean"==typeof n,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 2147483648&(r=y(e,t,n,!0))?-1*(4294967295-r+1):r}function w(e,t,n,r){return r||(j("boolean"==typeof n,"missing or invalid endian"),j(t+3<e.length,"Trying to read beyond buffer length")),h.read(e,t,n,23,4)}function S(e,t,n,r){return r||(j("boolean"==typeof n,"missing or invalid endian"),j(t+7<e.length,"Trying to read beyond buffer length")),h.read(e,t,n,52,8)}function E(e,t,n,r,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+1<e.length,"trying to write beyond buffer length"),F(t,65535)),!((s=e.length)<=n))for(var i=0,a=Math.min(s-n,2);i<a;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function I(e,t,n,r,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"trying to write beyond buffer length"),F(t,4294967295)),!((s=e.length)<=n))for(var i=0,a=Math.min(s-n,4);i<a;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function T(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+1<e.length,"Trying to write beyond buffer length"),N(t,32767,-32768)),e.length<=n||E(e,0<=t?t:65535+t+1,n,r,s)}function A(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"Trying to write beyond buffer length"),N(t,2147483647,-2147483648)),e.length<=n||I(e,0<=t?t:4294967295+t+1,n,r,s)}function C(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+3<e.length,"Trying to write beyond buffer length"),B(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||h.write(e,t,n,r,23,4)}function _(e,t,n,r,s){s||(j(null!=t,"missing value"),j("boolean"==typeof r,"missing or invalid endian"),j(null!=n,"missing offset"),j(n+7<e.length,"Trying to write beyond buffer length"),B(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||h.write(e,t,n,r,52,8)}n.Buffer=s,n.SlowBuffer=s,n.INSPECT_MAX_BYTES=50,s.poolSize=8192,s._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.isBuffer=function(e){return!(null==e||!e._isBuffer)},s.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"hex":n=e.length/2;break;case"utf8":case"utf-8":n=L(e).length;break;case"ascii":case"binary":case"raw":n=e.length;break;case"base64":n=x(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;default:throw new Error("Unknown encoding")}return n},s.concat=function(e,t){if(j(P(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new s(0);if(1===e.length)return e[0];if("number"!=typeof t)for(i=t=0;i<e.length;i++)t+=e[i].length;for(var n=new s(t),r=0,i=0;i<e.length;i++){var a=e[i];a.copy(n,r),r+=a.length}return n},s.prototype.write=function(e,t,n,r){isFinite(t)?isFinite(n)||(r=n,n=void 0):(c=r,r=t,t=n,n=c),t=Number(t)||0;var i,a,o,l,c=this.length-t;switch((!n||c<(n=Number(n)))&&(n=c),r=String(r||"utf8").toLowerCase()){case"hex":i=function(e,t,n,r){n=Number(n)||0;var i=e.length-n;(!r||i<(r=Number(r)))&&(r=i),j((i=t.length)%2==0,"Invalid hex string"),i/2<r&&(r=i/2);for(var a=0;a<r;a++){var o=parseInt(t.substr(2*a,2),16);j(!isNaN(o),"Invalid hex string"),e[n+a]=o}return s._charsWritten=2*a,a}(this,e,t,n);break;case"utf8":case"utf-8":a=this,o=t,l=n,i=s._charsWritten=M(L(e),a,o,l);break;case"ascii":case"binary":i=f(this,e,t,n);break;case"base64":a=this,o=t,l=n,i=s._charsWritten=M(x(e),a,o,l);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=p(this,e,t,n);break;default:throw new Error("Unknown encoding")}return i},s.prototype.toString=function(e,t,n){var r,s,i,a,o=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):o.length)===t)return"";switch(e){case"hex":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||r<n)&&(n=r);for(var s="",i=t;i<n;i++)s+=D(e[i]);return s}(o,t,n);break;case"utf8":case"utf-8":r=function(e,t,n){var r="",s="";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=U(s)+String.fromCharCode(e[i]),s=""):s+="%"+e[i].toString(16);return r+U(s)}(o,t,n);break;case"ascii":case"binary":r=g(o,t,n);break;case"base64":s=o,a=n,r=0===(i=t)&&a===s.length?u.fromByteArray(s):u.fromByteArray(s.slice(i,a));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=function(e,t,n){for(var r=e.slice(t,n),s="",i=0;i<r.length;i+=2)s+=String.fromCharCode(r[i]+256*r[i+1]);return s}(o,t,n);break;default:throw new Error("Unknown encoding")}return r},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.prototype.copy=function(e,t,n,r){if(t=t||0,(r=r||0===r?r:this.length)!==(n=n||0)&&0!==e.length&&0!==this.length){j(n<=r,"sourceEnd < sourceStart"),j(0<=t&&t<e.length,"targetStart out of bounds"),j(0<=n&&n<this.length,"sourceStart out of bounds"),j(0<=r&&r<=this.length,"sourceEnd out of bounds"),r>this.length&&(r=this.length);var i=(r=e.length-t<r-n?e.length-t+n:r)-n;if(i<100||!s._useTypedArrays)for(var a=0;a<i;a++)e[a+t]=this[a+n];else e._set(this.subarray(n,n+i),t)}},s.prototype.slice=function(e,t){var n=this.length;if(e=O(e,n,0),t=O(t,n,n),s._useTypedArrays)return s._augment(this.subarray(e,t));for(var r=t-e,i=new s(r,void 0,!0),a=0;a<r;a++)i[a]=this[a+e];return i},s.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},s.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},s.prototype.readUInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},s.prototype.readUInt16LE=function(e,t){return m(this,e,!0,t)},s.prototype.readUInt16BE=function(e,t){return m(this,e,!1,t)},s.prototype.readUInt32LE=function(e,t){return y(this,e,!0,t)},s.prototype.readUInt32BE=function(e,t){return y(this,e,!1,t)},s.prototype.readInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){return v(this,e,!0,t)},s.prototype.readInt16BE=function(e,t){return v(this,e,!1,t)},s.prototype.readInt32LE=function(e,t){return b(this,e,!0,t)},s.prototype.readInt32BE=function(e,t){return b(this,e,!1,t)},s.prototype.readFloatLE=function(e,t){return w(this,e,!0,t)},s.prototype.readFloatBE=function(e,t){return w(this,e,!1,t)},s.prototype.readDoubleLE=function(e,t){return S(this,e,!0,t)},s.prototype.readDoubleBE=function(e,t){return S(this,e,!1,t)},s.prototype.writeUInt8=function(e,t,n){n||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"trying to write beyond buffer length"),F(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,n){E(this,e,t,!0,n)},s.prototype.writeUInt16BE=function(e,t,n){E(this,e,t,!1,n)},s.prototype.writeUInt32LE=function(e,t,n){I(this,e,t,!0,n)},s.prototype.writeUInt32BE=function(e,t,n){I(this,e,t,!1,n)},s.prototype.writeInt8=function(e,t,n){n||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"Trying to write beyond buffer length"),N(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},s.prototype.writeInt16LE=function(e,t,n){T(this,e,t,!0,n)},s.prototype.writeInt16BE=function(e,t,n){T(this,e,t,!1,n)},s.prototype.writeInt32LE=function(e,t,n){A(this,e,t,!0,n)},s.prototype.writeInt32BE=function(e,t,n){A(this,e,t,!1,n)},s.prototype.writeFloatLE=function(e,t,n){C(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){C(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){_(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){_(this,e,t,!1,n)},s.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,j("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),j(t<=n,"end < start"),n!==t&&0!==this.length){j(0<=t&&t<this.length,"start out of bounds"),j(0<=n&&n<=this.length,"end out of bounds");for(var r=t;r<n;r++)this[r]=e}},s.prototype.inspect=function(){for(var e=[],t=this.length,r=0;r<t;r++)if(e[r]=D(this[r]),r===n.INSPECT_MAX_BYTES){e[r+1]="...";break}return"<Buffer "+e.join(" ")+">"},s.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(s._useTypedArrays)return new s(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var R=s.prototype;function O(e,t,n){return"number"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function k(e){return(e=~~Math.ceil(+e))<0?0:e}function P(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function D(e){return e<16?"0"+e.toString(16):e.toString(16)}function L(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else for(var s=n,i=(55296<=r&&r<=57343&&n++,encodeURIComponent(e.slice(s,n+1)).substr(1).split("%")),a=0;a<i.length;a++)t.push(parseInt(i[a],16))}return t}function x(e){return u.toByteArray(e)}function M(e,t,n,r){for(var s=0;s<r&&!(s+n>=t.length||s>=e.length);s++)t[s+n]=e[s];return s}function U(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function F(e,t){j("number"==typeof e,"cannot write a non-number as a number"),j(0<=e,"specified a negative value for writing an unsigned value"),j(e<=t,"value is larger than maximum value for type"),j(Math.floor(e)===e,"value has a fractional component")}function N(e,t,n){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(n<=e,"value smaller than minimum allowed value"),j(Math.floor(e)===e,"value has a fractional component")}function B(e,t,n){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(n<=e,"value smaller than minimum allowed value")}function j(e,t){if(!e)throw new Error(t||"Failed assertion")}s._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=R.get,e.set=R.set,e.write=R.write,e.toString=R.toString,e.toLocaleString=R.toString,e.toJSON=R.toJSON,e.copy=R.copy,e.slice=R.slice,e.readUInt8=R.readUInt8,e.readUInt16LE=R.readUInt16LE,e.readUInt16BE=R.readUInt16BE,e.readUInt32LE=R.readUInt32LE,e.readUInt32BE=R.readUInt32BE,e.readInt8=R.readInt8,e.readInt16LE=R.readInt16LE,e.readInt16BE=R.readInt16BE,e.readInt32LE=R.readInt32LE,e.readInt32BE=R.readInt32BE,e.readFloatLE=R.readFloatLE,e.readFloatBE=R.readFloatBE,e.readDoubleLE=R.readDoubleLE,e.readDoubleBE=R.readDoubleBE,e.writeUInt8=R.writeUInt8,e.writeUInt16LE=R.writeUInt16LE,e.writeUInt16BE=R.writeUInt16BE,e.writeUInt32LE=R.writeUInt32LE,e.writeUInt32BE=R.writeUInt32BE,e.writeInt8=R.writeInt8,e.writeInt16LE=R.writeInt16LE,e.writeInt16BE=R.writeInt16BE,e.writeInt32LE=R.writeInt32LE,e.writeInt32BE=R.writeInt32BE,e.writeFloatLE=R.writeFloatLE,e.writeFloatBE=R.writeFloatBE,e.writeDoubleLE=R.writeDoubleLE,e.writeDoubleBE=R.writeDoubleBE,e.fill=R.fill,e.inspect=R.inspect,e.toArrayBuffer=R.toArrayBuffer,e}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=4,h=new s(u);h.fill(0),t.exports={hash:function(e,t,n,r){for(var i=t(function(e,t){e.length%u!=0&&(n=e.length+(u-e.length%u),e=s.concat([e,h],n));for(var n,r=[],i=t?e.readInt32BE:e.readInt32LE,a=0;a<e.length;a+=u)r.push(i.call(e,a));return r}(e=s.isBuffer(e)?e:new s(e),r),8*e.length),a=(t=r,new s(n)),o=t?a.writeInt32BE:a.writeInt32LE,l=0;l<i.length;l++)o.call(a,i[l],4*l,!0);return a}}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(e,t,n){(function(t,r,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:u,sha256:h,md5:e("./md5")},g=64,m=new s(g);function y(e,t){var n=p[e=e||"sha1"],r=[];return n||v("algorithm:",e,"is not yet supported"),{update:function(e){return s.isBuffer(e)||(e=new s(e)),r.push(e),e.length,this},digest:function(e){var i=s.concat(r);return i=t?function(e,t,n){s.isBuffer(t)||(t=new s(t)),s.isBuffer(n)||(n=new s(n)),t.length>g?t=e(t):t.length<g&&(t=s.concat([t,m],g));for(var r=new s(g),i=new s(g),a=0;a<g;a++)r[a]=54^t[a],i[a]=92^t[a];return n=e(s.concat([r,n])),e(s.concat([i,n]))}(n,t,i):n(i),r=null,e?i.toString(e):i}}}function v(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}m.fill(0),n.createHash=function(e){return y(e)},n.createHmac=y,n.randomBytes=function(e,t){if(!t||!t.call)return new s(f(e));try{t.call(this,void 0,new s(f(e)))}catch(e){t(e)}};var b,w=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],S=function(e){n[e]=function(){v("sorry,",e,"is not implemented yet")}};for(b in w)S(w[b])}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,s=-1732584194,i=271733878,a=0;a<e.length;a+=16){var o=n,l=r,c=s,d=i;n=p(n,r,s,i,e[a+0],7,-680876936),i=p(i,n,r,s,e[a+1],12,-389564586),s=p(s,i,n,r,e[a+2],17,606105819),r=p(r,s,i,n,e[a+3],22,-1044525330),n=p(n,r,s,i,e[a+4],7,-176418897),i=p(i,n,r,s,e[a+5],12,1200080426),s=p(s,i,n,r,e[a+6],17,-1473231341),r=p(r,s,i,n,e[a+7],22,-45705983),n=p(n,r,s,i,e[a+8],7,1770035416),i=p(i,n,r,s,e[a+9],12,-1958414417),s=p(s,i,n,r,e[a+10],17,-42063),r=p(r,s,i,n,e[a+11],22,-1990404162),n=p(n,r,s,i,e[a+12],7,1804603682),i=p(i,n,r,s,e[a+13],12,-40341101),s=p(s,i,n,r,e[a+14],17,-1502002290),n=g(n,r=p(r,s,i,n,e[a+15],22,1236535329),s,i,e[a+1],5,-165796510),i=g(i,n,r,s,e[a+6],9,-1069501632),s=g(s,i,n,r,e[a+11],14,643717713),r=g(r,s,i,n,e[a+0],20,-373897302),n=g(n,r,s,i,e[a+5],5,-701558691),i=g(i,n,r,s,e[a+10],9,38016083),s=g(s,i,n,r,e[a+15],14,-660478335),r=g(r,s,i,n,e[a+4],20,-405537848),n=g(n,r,s,i,e[a+9],5,568446438),i=g(i,n,r,s,e[a+14],9,-1019803690),s=g(s,i,n,r,e[a+3],14,-187363961),r=g(r,s,i,n,e[a+8],20,1163531501),n=g(n,r,s,i,e[a+13],5,-1444681467),i=g(i,n,r,s,e[a+2],9,-51403784),s=g(s,i,n,r,e[a+7],14,1735328473),n=m(n,r=g(r,s,i,n,e[a+12],20,-1926607734),s,i,e[a+5],4,-378558),i=m(i,n,r,s,e[a+8],11,-2022574463),s=m(s,i,n,r,e[a+11],16,1839030562),r=m(r,s,i,n,e[a+14],23,-35309556),n=m(n,r,s,i,e[a+1],4,-1530992060),i=m(i,n,r,s,e[a+4],11,1272893353),s=m(s,i,n,r,e[a+7],16,-155497632),r=m(r,s,i,n,e[a+10],23,-1094730640),n=m(n,r,s,i,e[a+13],4,681279174),i=m(i,n,r,s,e[a+0],11,-358537222),s=m(s,i,n,r,e[a+3],16,-722521979),r=m(r,s,i,n,e[a+6],23,76029189),n=m(n,r,s,i,e[a+9],4,-640364487),i=m(i,n,r,s,e[a+12],11,-421815835),s=m(s,i,n,r,e[a+15],16,530742520),n=y(n,r=m(r,s,i,n,e[a+2],23,-995338651),s,i,e[a+0],6,-198630844),i=y(i,n,r,s,e[a+7],10,1126891415),s=y(s,i,n,r,e[a+14],15,-1416354905),r=y(r,s,i,n,e[a+5],21,-57434055),n=y(n,r,s,i,e[a+12],6,1700485571),i=y(i,n,r,s,e[a+3],10,-1894986606),s=y(s,i,n,r,e[a+10],15,-1051523),r=y(r,s,i,n,e[a+1],21,-2054922799),n=y(n,r,s,i,e[a+8],6,1873313359),i=y(i,n,r,s,e[a+15],10,-30611744),s=y(s,i,n,r,e[a+6],15,-1560198380),r=y(r,s,i,n,e[a+13],21,1309151649),n=y(n,r,s,i,e[a+4],6,-145523070),i=y(i,n,r,s,e[a+11],10,-1120210379),s=y(s,i,n,r,e[a+2],15,718787259),r=y(r,s,i,n,e[a+9],21,-343485551),n=v(n,o),r=v(r,l),s=v(s,c),i=v(i,d)}return Array(n,r,s,i)}function f(e,t,n,r,s,i){return v((t=v(v(t,e),v(r,i)))<<s|t>>>32-s,n)}function p(e,t,n,r,s,i,a){return f(t&n|~t&r,e,t,s,i,a)}function g(e,t,n,r,s,i,a){return f(t&r|n&~r,e,t,s,i,a)}function m(e,t,n,r,s,i,a){return f(t^n^r,e,t,s,i,a)}function y(e,t,n,r,s,i,a){return f(n^(t|~r),e,t,s,i,a)}function v(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}t.exports=function(e){return u.hash(e,h,16)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,t,n){(function(e,n,r,s,i,a,o,l,c){t.exports=function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n,r,s,i=Array(80),a=1732584193,o=-271733879,l=-1732584194,c=271733878,d=-1009589776,u=0;u<e.length;u+=16){for(var h=a,g=o,m=l,y=c,v=d,b=0;b<80;b++){i[b]=b<16?e[u+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(a,5),(w=o,r=l,s=c,(n=b)<20?w&r|~w&s:!(n<40)&&n<60?w&r|w&s|r&s:w^r^s)),f(f(d,i[b]),(n=b)<20?1518500249:n<40?1859775393:n<60?-1894007588:-899497514));d=c,c=l,l=p(o,30),o=a,a=w}a=f(a,h),o=f(o,g),l=f(l,m),c=f(c,y),d=f(d,v)}return Array(a,o,l,c,d)}function f(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function p(e,t){return e<<t|e>>>32-t}t.exports=function(e){return u.hash(e,h,20,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(e,t,n){(function(n,r,s,i,a,o,l,c,d){function u(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function h(e,t){var n,r=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),s=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),i=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var a,o,l=0;l<e.length;l+=16){for(var c=s[0],d=s[1],h=s[2],f=s[3],m=s[4],y=s[5],v=s[6],b=s[7],w=0;w<64;w++)i[w]=w<16?e[w+l]:u(u(u((o=i[w-2],p(o,17)^p(o,19)^g(o,10)),i[w-7]),(o=i[w-15],p(o,7)^p(o,18)^g(o,3))),i[w-16]),n=u(u(u(u(b,p(o=m,6)^p(o,11)^p(o,25)),m&y^~m&v),r[w]),i[w]),a=u(p(a=c,2)^p(a,13)^p(a,22),c&d^c&h^d&h),b=v,v=y,y=m,m=u(f,n),f=h,h=d,d=c,c=u(n,a);s[0]=u(c,s[0]),s[1]=u(d,s[1]),s[2]=u(h,s[2]),s[3]=u(f,s[3]),s[4]=u(m,s[4]),s[5]=u(y,s[5]),s[6]=u(v,s[6]),s[7]=u(b,s[7])}return s}var f=e("./helpers"),p=function(e,t){return e>>>t|e<<32-t},g=function(e,t){return e>>>t};t.exports=function(e){return f.hash(e,h,32,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,n){(function(e,t,r,s,i,a,o,l,c){n.read=function(e,t,n,r,s){var i,a,o=8*s-r-1,l=(1<<o)-1,c=l>>1,d=-7,u=n?s-1:0,h=n?-1:1;for(s=e[t+u],u+=h,i=s&(1<<-d)-1,s>>=-d,d+=o;0<d;i=256*i+e[t+u],u+=h,d-=8);for(a=i&(1<<-d)-1,i>>=-d,d+=r;0<d;a=256*a+e[t+u],u+=h,d-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(s?-1:1);a+=Math.pow(2,r),i-=c}return(s?-1:1)*a*Math.pow(2,i-r)},n.write=function(e,t,n,r,s,i){var a,o,l=8*i-s-1,c=(1<<l)-1,d=c>>1,u=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1;for(i=t<0||0===t&&1/t<0?1:0,t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(r=Math.pow(2,-a))<1&&(a--,r*=2),2<=(t+=1<=a+d?u/r:u*Math.pow(2,1-d))*r&&(a++,r/=2),c<=a+d?(o=0,a=c):1<=a+d?(o=(t*r-1)*Math.pow(2,s),a+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,s),a=0));8<=s;e[n+h]=255&o,h+=f,o/=256,s-=8);for(a=a<<s|o,l+=s;0<l;e[n+h]=255&a,h+=f,a/=256,l-=8);e[n+h-f]|=128*i}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(e,t,n){(function(e,n,r,s,i,a,o,l,c){var d,u,h;function f(){}(e=t.exports={}).nextTick=(u="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:h?(d=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<d.length&&d.shift()())}),!0),function(e){d.push(e),window.postMessage("process-tick","*")}):function(e){setTimeout(e,0)}),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1);var Iv,Tv=Ev.exports;class Av{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,r,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let i;"prev"===e&&(i=this.previousToken),"next"===e&&(i=this.nextToken);const a=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(s=a.paging)||void 0===s?void 0:s.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Cv extends Av{async getRequest(e,t){const{limit:n=W,userId:r}=e,s=Bf(e,["limit","userId"]),i=t?{token:t}:{limit:n},a=Ye().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:o}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:!1})});return o}}class _v{constructor(e,t){this.query=e,this.cacheKey=t}}!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Iv||(Iv={}));class Rv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.follows.map(Je("follow"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Je("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Iv.OnDeclined:case Iv.OnCanceled:case Iv.OnUnfollowed:case Iv.OnDeleted:r.data=r.data.filter((e=>e!==Je("follow")(t)));break;case Iv.OnRequested:case Iv.OnAccepted:case Iv.OnFollowed:r.data=[...new Set([Je("follow")(t),...r.data])]}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ov{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class kv{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof Ov?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof Ov)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof Ov)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(nv).map(rv);return!Fp(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Pv(e){return null!=e}const Dv=({userId:e})=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{const r=Xg(n);Ff(r);const s=tt(["follow","get",Je("follow")({from:r.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Lv extends kv{constructor(e,t){const n=Tv(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new Cv(e),n,r,t),this.query=e,this.queryStreamController=new Rv(this.query,this.cacheKey,this.notifyChange.bind(this),Km),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ov,action:Iv.OnFollowed},{fn:lv,action:Iv.OnUnfollowed},{fn:hv,action:Iv.OnAccepted},{fn:fv,action:Iv.OnDeclined},{fn:uv,action:Iv.OnCanceled},{fn:cv,action:Iv.OnDeleted},{fn:bv,action:Iv.OnAccepted},{fn:wv,action:Iv.OnDeclined},{fn:mv,action:Iv.OnFollowed},{fn:yv,action:Iv.OnUnfollowed},{fn:Dv({userId:this.query.userId}),action:Iv.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["follow","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=tt(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class xv extends Av{async getRequest(e,t){const{limit:n=W,userId:r}=e,s=Bf(e,["limit","userId"]),i=t?{token:t}:{limit:n},a=Ye().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:o}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:!1})});return o}}class Mv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.follows.map(Je("follow"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Je("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Iv.OnDeclined:case Iv.OnCanceled:case Iv.OnUnfollowed:case Iv.OnDeleted:r.data=r.data.filter((e=>e!==Je("follow")(t)));break;case Iv.OnRequested:case Iv.OnAccepted:case Iv.OnFollowed:r.data=[...new Set([Je("follow")(t),...r.data])]}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Uv=({userId:e})=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{const r=Xg(n);Ff(r);const s=tt(["follow","get",Je("follow")({from:e,to:r.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Fv extends kv{constructor(e,t){const n=Tv(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new xv(e),n,r,t),this.query=e,this.queryStreamController=new Mv(this.query,this.cacheKey,this.notifyChange.bind(this),Gm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:dv,action:Iv.OnRequested},{fn:hv,action:Iv.OnAccepted},{fn:fv,action:Iv.OnDeclined},{fn:uv,action:Iv.OnCanceled},{fn:ov,action:Iv.OnFollowed},{fn:lv,action:Iv.OnUnfollowed},{fn:cv,action:Iv.OnDeleted},{fn:vv,action:Iv.OnRequested},{fn:bv,action:Iv.OnAccepted},{fn:wv,action:Iv.OnDeclined},{fn:mv,action:Iv.OnFollowed},{fn:yv,action:Iv.OnUnfollowed},{fn:Uv({userId:this.query.userId}),action:Iv.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["follow","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=tt(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const Nv=(e,t,n,r,s,i)=>{const{forceDispatch:a,callbackDataSelector:o,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=Ye();let d;c||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],f=e=>{const{data:n}=e,r=Bf(e,["data"]);l&&!l(n,d)||t(Object.assign({data:o(n)},r)),d=nv(n)};return h.push(...s.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&Fp(d,t)||f({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=Be(r,e,!0);$e(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===z?(f({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),u=!0,h.forEach((e=>e()))):u||f({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Bv=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ye();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:i}=n,a={follows:s};t.cache&&(Ff(a,{cachedAt:r}),st(["followInfo","get",e],i[0],{cachedAt:r}));const o={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},l=Wm(o);return Ut("local.follow.unfollowed",l),n},unBlockUser:async e=>{const t=Ye();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:i}=n,a={follows:s};t.cache&&(Ff(a,{cachedAt:r}),st(["followInfo","get",e],i[0],{cachedAt:r}));const o=Wm(a);return Ut("local.follow.created",o),n},onUserDidBlock:Vm,onUserDidUnblock:Ym,follow:async e=>{const t=Ye();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const s=Wm(n);return"accepted"===n.follows[0].status?Ut("local.follow.created",s):Ut("local.follow.requested",s),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Ye();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Ye();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Ye();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Ff(n);const r=Wm(n);return Ut("local.follow.requestDeclined",r),!0},onUserFollowed:ov,onUserUnfollowed:lv,onFollowerDeleted:cv,onFollowerRequested:dv,onFollowRequestCanceled:uv,onFollowRequestAccepted:hv,onFollowRequestDeclined:fv,onFollowInfoUpdated:gv,onLocalUserFollowed:mv,onLocalUserUnfollowed:yv,onLocalFollowerRequested:vv,onLocalFollowRequestAccepted:bv,onLocalFollowRequestDeclined:wv,getFollowers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getFollowers(tmpid: ${i}) > listen`);const a=new Lv(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getFollowers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getFollowings(tmpid: ${i}) > listen`);const a=new Fv(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getFollowings(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getFollowInfo:(e,t)=>Nv(e,t,"userId",pv,[gv],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Rt();return Nv(t,e,"userId",pv,[gv],{forceDispatch:!0})}});function jv(e,t){return e.map((e=>{const n=tt(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=Rt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const $v=e=>{var t;return null!==(t=Object.keys(f).find((t=>e.needApprovalOnPostCreation===f[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===f[t].onlyAdminCanPost)))&&void 0!==t?t:p};function qv({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Bf(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:$v({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Kv=e=>{const t=qv({communities:e.communities}),n=e.users.map(fp),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=jv(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(fp),communities:s,communityUsers:r})},Gv=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(fp);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Wv=e=>{const t=qv({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=jv(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Hv=e=>{const{postSetting:t,storySetting:n}=e,r=Bf(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?f[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Vv=e=>{var t=Bf(e,["searchResult"]);const n=Kv(t);return Object.assign({},n)},Yv=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return jt(n)},cancel:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Ut("local.joinRequest.deleted",[s])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"approved"}),Ut("local.joinRequest.updated",[s])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=tt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(st(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Ut("local.joinRequest.updated",[s])),r.success})(e)}});class Qv extends Av{async getRequest(e,t){const{limit:n=20,communityId:r}=e,s=Bf(e,["limit","communityId"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},s),{options:i})});return a}}var zv;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(zv||(zv={}));class Jv extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===zv.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===zv.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===zv.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Xv=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Zv=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},eb=e=>{const t=Ye(),n=[Mt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class tb extends kv{constructor(e,t){const n=Tv(e),r=["joinRequest","collection",n];super(new Qv(e),n,r,t),this.query=e,this.queryStreamController=new Jv(this.query,this.cacheKey,this.notifyChange.bind(this),Gv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xv,action:zv.OnLocalJoinRequestCreated},{fn:Zv,action:zv.OnLocalJoinRequestUpdated},{fn:eb,action:zv.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=this.applyFilter(s.data.map((e=>tt(["joinRequest","get",e]))).filter(Pv).map((({data:e})=>e)).map(Yv));(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}const nb=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),rb=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(nb),users:e.users.map(fp)}),sb=async e=>{const t=Ye();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=rb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:s}},ib=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp),invitations:e.invitations.map(nb)}),ab=e=>Object.assign(Object.assign({},e),{get user(){const t=tt(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get createdBy(){const t=tt(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get target(){if("community"===e.targetType){const t=tt(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(st(["invitation","get",e],{status:"approved"}),Ut("local.invitation.updated",[s])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(st(["invitation","get",e],{status:"rejected"}),Ut("local.invitation.updated",[s])),r.success})(e._id)}}),ob=async e=>{const t=Ye();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),r=ib(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.invitations[0]?ab(r.invitations[0]):void 0,cachedAt:s}};var lb;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(lb||(lb={}));class cb extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class db extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.invitations.map(Je("invitation"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Je("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===lb.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===lb.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===lb.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ub=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},hb=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},fb=e=>{const t=Ye(),n=[Mt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class pb extends kv{constructor(e,t){const n=Tv(e),r=["invitation","collection",n];super(new cb(e),n,r,t),this.query=e,this.queryStreamController=new db(this.query,this.cacheKey,this.notifyChange.bind(this),rb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ub,action:lb.OnLocalInvitationCreated},{fn:hb,action:lb.OnLocalInvitationUpdated},{fn:fb,action:lb.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["invitation","get",e]))).filter(Pv).map((({data:e})=>ab(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}const gb=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),mb=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=tt(["category","get",e]);if(null==t?void 0:t.data)return gb(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=tt(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await sb({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getInvitations: (tmpid: ${i}) > listen`);const a=new pb(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getInvitations (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await ob({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ye();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),s=Gv(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const a="approved"===s.joinRequests[0].status?"success":"pending";if("success"===a&&n.cache){const n=null===(t=tt(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});st(["community","get",e],t)}}return Ut("v4.local.community.joined",s.joinRequests),"success"===a?{status:a}:{status:a,request:Yv(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getJoinRequests: (tmpid: ${i}) > listen`);const a=new tb(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getJoinRequests (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ye();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=Gv(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.joinRequests[0]?Yv(r.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class yb{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=tt(["story-expire",this._targetId]),this.cacheStoreSeenTime=tt(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=tt(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return tt(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=et(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:s}}=t;return n!==this._targetId||s||(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const vb=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:s,targetUpdatedAt:i,localFilter:a}=e,o=new yb(n,r,s);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:i,hasUnseen:o.getHasUnseenFlag(),syncingStoriesCount:o.syncingStoriesCount,failedStoriesCount:o.failedStoriesCount,localFilter:a,localLastExpires:o.localLastStoryExpires,localLastSeen:o.localLastStorySeenExpiresAt,localSortingDate:o.getLocalLastSortingDate()}},bb=async e=>{const t=Ye();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,s=Bf(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await Rp(n.data),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{channels:i}=r;return{data:Rg(i[0]),cachedAt:s}},wb=async e=>{const t=Ye();let n;t.log("channel/getChannel",e),Xf("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Rp(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&kp(r)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("channel",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:r}};wb.locally=e=>{var t;const n=Ye();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=et(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const Sb=Symbol("getWatcherUrls"),Eb=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=tt(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=tt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=tt(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Eb(n)})).filter(Pv):[]},getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return _g(Rg(n));const{data:r}=await wb(e.channelId);return _g(Rg(r))}if(e.userId===n.userId){const{data:t}=await bb({type:"live",postId:e.postId,videoStreamId:e.streamId});return rt(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Sb](){return e.watcherUrl}}),Ib=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=tt(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)},get childrenComment(){return e.children.map((e=>{const t=tt(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Pv).map((e=>Ib(e)))}});function Tb(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Ab(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Cb{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let _b=null;const Rb=()=>(_b||(_b=new Cb),_b),Ob={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},kb="-----BEGIN PRIVATE KEY-----";function Pb(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=String.fromCharCode(e)})),ye(n)}function Db(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Lb(e){let t=e;t=e.includes(kb)?e.substring(kb.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const n=Te(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);const s=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),r=Db(e.length),s=n.length+t.length+1+r.length+e.length,i=Db(s),a=new Uint8Array(1+i.length+s);let o=0;return a[o]=48,o+=1,a.set(i,o),o+=i.length,a.set(n,o),o+=n.length,a.set(t,o),o+=t.length,a[o]=4,o+=1,a.set(r,o),o+=r.length,a.set(e,o),a}(r);return await crypto.subtle.importKey("pkcs8",s.buffer,Ob,!1,["sign"])}async function xb({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=Rf.v4(),s=`nonceStr=${r}×tamp=${e}&data=${n}==`,i=(new TextEncoder).encode(s),a=await Lb("MIIEpQIBAAKCAQEAwAEc/oZgYIvKSUG/C3mONYLR4ZPgAjMEX4bJ+xqqakUDRtqlNO+eZs2blQ1Ko0DBkqPExyQezvjibH5W2UZBV5RaBTlTcNVKTToMBEGesAfaEcM3qUyQHxdbFYZv6P4sb14dcwxTQ8usmaV8ooiR1Fcaso5ZWYcZ8Hb46FbQ7OoVumsBtPWwfZ4f003o5VCl6AIM6lcLv9UDLlFVYhE+PeXpRHtfWlGqxMvqC9oinlwhL6nWv6VjQXW4nhcib72dPBzfHT7k/PMKto2SxALYdb68ENiAGuJLWi3AUHSyYCJK2w7wIlWfJUAI0v26ub10IpExr6D5QuW2577jjP93iwIDAQABAoIBAFWfqXhwIIatkFY+9Z1+ZcbDQimgsmMIsUiQaX6Lk7e0cxOj6czDlxYtVtaPiNtow2pLkjNkjkCqiP7tEHnwdK9DvylZOTa2R15NJpK3WLcTqVIGhsn/FL5owfvFah6zSsmXZParZm5zY9NZE03ALZhOB9/cz0e3kf/EbpfeL2mW7MApyiUt5i09ycchroOpcWp73ipIxvgigtZyUGFmsQicWhUs28F0D7w4Qfk76yG3nqXeb+BAMhCaIaa/k/aAxhiZG/ygEQWQrcC8gfe+jyicMAQPDEVS9YuUMGsLjIjKuVLZzp2xirQnhc2i2zVNEIvG6soprPOBEMQugzrtX5ECgYEA3b7KAbBIbDl1e4ZSCWhHdHkiWVZHaopsR/LhqDDNhXjWjq3AesgV6k0j9EdziMn/HmmOso0bz99GTV3JZf4A9ztTLumJlkHbdVtlgOqSjrFLj12rH9KXTheyIhWSpUmm8+WB1xasFbqpvJaGo7F3pd2Fqj1XR4mp5BO7c/t7LJ0CgYEA3aouEzXQ9THRKYocdfY69EI1Il1t/d/RSqqd9BxEjxBgxkM13ZiYIn/R4WW/nCUrlmhxG44Aa2Gob4Ahfsui2xKTg/g/3Zk/rAxAEGkfOLGoenaJMD41fH4wUq3FRYwkvnaMb9Hd6f/TlBHslIRa2NN58bSBGJCyBP2b59+2+EcCgYEAixDVRXvV37GlYUOa/XVdosk5Zoe6oDGRuQm0xbNdoUBoZvDHDvme7ONWEiQha/8qtVsD+CyQ7awcPfb8kK9c0bBt+bTS6d4BkTcxkEkMgtrkBVR8Nqfu5jXsLH4VCv4G61zbMhZw8+ut+az5YX2yCN7Frj9sFlxapMRPQmzMEe0CgYEAumsAzM8ZqNv4mAK65Mnr0rhLj1cbxcKRdUYACOgtEFQpzxN/HZnTeFAe5nx3pI3uFlRHq3DFEYnT6dHMWaJQmAULYpVIwMi9L6gtyJ9fzoI6uqMtxRDMUqKdaSsTGOY/kJ6KhQ/unXi1K3XXjR+yd1+C0q+HUm1+CYxvrZYLfskCgYEArsEy+IQOiqniJ0NE2vVUF+UK/IRZaic9YKcpov5Ot7Vvzm/MnnW4N1ljVskocETBWMmPUvNSExVjPebi+rxd8fa5kY8BJScPTzMFbunZn/wjtGdcM10qdlVQ9doG61A/9P3ezFKCfS4AvF/H/59LcSx2Bh28fp3/efiVIOpVd4Y=");return{signature:Pb(await crypto.subtle.sign(Ob,a,i)),nonceStr:r}}async function Mb(){const e=Rb(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),r=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),s=await xb({timestamp:n,rooms:r});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const i={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:r},a=Ye();return await a.http.post("/api/v3/user-event/room",i),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const r=n.retryCount+1;r>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:r})}})),!1}}const Ub=["live","recorded"];class Fb{constructor(e){this.storage=Rb(),this.client=Ye(),this.room=e}async createWatchSession(e){if(!Ub.includes(this.room.status))throw new Ge("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+Rf.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),r=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(r,1e3)};r()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await Mb(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const Nb=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=tt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=tt(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?jt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=tt(["room","get",e]))||void 0===t?void 0:t.data;if(n)return Nb(n)})).filter(Pv):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?jt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=tt(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return _g(Rg(n));const{data:r}=await wb(e.liveChannelId);return _g(Rg(r))}if(e.createdBy===n.userId){const{data:t}=await bb({type:"live",postId:e.referenceId,roomId:e.roomId});return rt(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>sb({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await ob({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new Fb(this)}}),Bb=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=tt(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),jb=e=>{const t=gm();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,r,s)=>{t.markProductAsClicked(e,n,r,s)},markAsViewed:(n,r,s)=>{t.markProductAsViewed(e,n,r,s)}}})},$b=e=>{var t,n,r;if(!e)return e;if("video"===e.type){const r=null===(n=null===(t=e.attributes)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.video;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==r?void 0:r.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==r?void 0:r.height)&&void 0!==e?e:0},getRotation:()=>{var e;return null!==(e=null==r?void 0:r.rotation)&&void 0!==e?e:0}})}if("image"===e.type){const t=null===(r=e.attributes)||void 0===r?void 0:r.metadata;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==t?void 0:t.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==t?void 0:t.height)&&void 0!==e?e:0}})}return e},qb=e=>zf(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=tt(["post","get",e]))||void 0===t?void 0:t.data})).filter(Pv).map(qb),analytics:{markAsViewed:()=>{gm().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{gm().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=tt(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?jb(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=tt(["comment","get",e]))||void 0===t?void 0:t.data;return n?Ib(n):null})).filter(Boolean)||[]},get creator(){if(!e.postedUserId)return;const t=tt(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?jt(t.data):void 0},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=tt(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?mb(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return $b(null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,r;const s=Tb(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return $b(null===(r=tt(["file","get",s]))||void 0===r?void 0:r.data)},getVideoThumbnailInfo(){var t,n;const r=Tb(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(r)return $b(null===(n=tt(["file","get",r]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!Ab(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const r=null===(n=tt(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return r?Eb(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const r=null===(n=tt(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return r?Bb(r):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=tt(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const r=null===(n=tt(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return r?Nb(r):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const r=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=r(e.data),i=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=tt(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>r(null==e?void 0:e.data))).find(Boolean);if(!i)return;const a=null===(n=tt(["event","get",i]))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign({},a),{get creator(){const e=tt(["user","get",a.userId]);if(null==e?void 0:e.data)return jt(e.data)},get targetCommunity(){var e;if(!a.originId)return;const t=null===(e=tt(["community","get",a.originId]))||void 0===e?void 0:e.data;return t?mb(t):void 0},get coverImage(){var e;if(a.coverImageFileId)return null===(e=tt(["file","get",a.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),Kb=(e,t)=>{"message"===e?Ut("local.message.updated",{messages:[t]}):"post"===e?Ut("post.updated",{posts:[t]}):"comment"===e?Ut("comment.updated",{comments:[t]}):"story"===e&&Ut("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Gb=async(e,t,n,r)=>{var s,i,a;const o=Ye();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:l}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(o.cache){const r=tt([e,"get",t]);if(!r||(null===(s=r.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(i=r.data.myReactions)&&void 0!==i?i:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(a=r.data.reactions[n])&&void 0!==a?a:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.addReaction",{comment:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("post"===e)return Ut("local.post.addReaction",{post:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("story"===e)return Ut("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:l.addedId}}),!0;if("message"===e)return st(["message","get",t],c),Ut("local.message.updated",{messages:[c]}),!0}return!0};Gb.optimistically=(e,t,n)=>{var r,s,i,a,o;const l=Ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=tt([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(i=c.data.reactions[n])&&void 0!==i?i:0)+1})});return st([e,"get",t],d,{cachedAt:z}),Kb(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==o&&o};const Wb=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=tt(["messageMarker","get",Je("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Hb=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var s,i;const a=Ye();if(a.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await a.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(a.cache){const r=tt([e,"get",t]);if(!r)return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(s=r.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(i=r.data.reactions[n])&&void 0!==i?i:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.removeReaction",{comment:l,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("post"===e)return Ut("local.post.removeReaction",{post:l,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("story"===e)return Ut("local.story.reactionRemoved",{story:l,reactor:{userId:a.userId,reactionName:n,reactionId:o.removedId}}),!0;if("message"===e)return st(["message","get",t],l),Ut("local.message.updated",{messages:[l]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Vb=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp)}),Yb=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=tt(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)}}),Qb=e=>Object.assign(Object.assign({},e),{users:e.users.map(fp)}),zb=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Qb(e);if(n.cache){Ff(r);const e=tt(["event","get",r.events[0].eventId]);t(e.data)}else t(r.events[0])}))},Jb=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Vb(e);if(n.cache){Ff(r);const e=tt(["eventResponse","get",r.eventResponses[0].userId]);t(e.data)}else t(r.eventResponses[0])}))},Xb=async e=>{const t=Ye();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),r=Vb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:Yb(r.eventResponses[0]),cachedAt:s}};var Zb;Xb.locally=e=>{const t=Ye();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=tt(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Zb||(Zb={}));class ew extends Av{async getRequest(e,t){const{limit:n=W,eventId:r}=e,s=Bf(e,["limit","eventId"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v1/events/${r}/rsvp`,{params:Object.assign(Object.assign({},s),{options:i})});return a}}class tw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.eventResponses.map(Je("eventResponse"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Je("eventResponse"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Zb.OnRSVPCreated&&(r.data=[...new Set([t.userId,...r.data])]),e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const nw=e=>zb("event.created",e),rw=e=>zb("event.updated",e),sw=e=>zb("event.deleted",e),iw=e=>zb("local.event.created",e),aw=e=>zb("local.event.updated",e),ow=e=>zb("local.event.deleted",e),lw=e=>Jb("event.rsvp.created",e),cw=e=>Jb("event.rsvp.updated",e),dw=e=>Jb("local.rsvp.created",e),uw=e=>Jb("local.rsvp.updated",e);class hw extends kv{constructor(e,t){const n=Tv(e),r=["eventResponse","collection",n];super(new ew(e),n,r,t),this.query=e,this.queryStreamController=new tw(this.query,this.cacheKey,this.notifyChange.bind(this),Vb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lw,action:Zb.OnRSVPCreated},{fn:cw,action:Zb.OnRSVPUpdated},{fn:dw,action:Zb.OnRSVPCreated},{fn:uw,action:Zb.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=s.data.map((e=>tt(["eventResponse","get",e]))).filter(Pv).map((({data:e})=>Yb(e)));(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const fw=(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getRSVPs: (tmpid: ${i}) > listen`);const a=new hw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getRSVPs (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},pw=e=>Object.assign(Object.assign({},e),{get creator(){const t=tt(["user","get",e.userId]);if(null==t?void 0:t.data)return jt(t.data)},get targetCommunity(){if(!e.originId)return;const t=tt(["community","get",e.originId]);return(null==t?void 0:t.data)?mb(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=tt(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=tt(["post","get",e.postId]);return(null==t?void 0:t.data)?qb(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=et(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?Nb(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/createRSVP",e,t);const{data:r}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Ut("local.rsvp.created",r);const s=Vb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:Yb(s.eventResponses[0]),cachedAt:i}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/updateRSVP",e,t);const{data:r}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Ut("local.rsvp.updated",r);const s=Vb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:Yb(s.eventResponses[0]),cachedAt:i}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Xb(e.eventId);return t},getRSVPs:(t,n)=>fw(Object.assign({eventId:e.eventId},t),n)}),gw={file:$b,ad:e=>{const t=gm(),{image9_16:n,image1_1:r}=e,s=Bf(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=tt(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const s=null===(n=tt(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:s})},get image1_1(){const e=tt(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=tt(["file","get",n]);if(e)return e.data||void 0}})},comment:Ib,post:qb,user:jt,category:gb,stream:Eb,story:e=>{const t=gm(),n=tt(["storyTarget","get",e.targetId]),r=tt(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const r=tt(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:s}=r;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=tt(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:s}=r;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==r?void 0:r.data))return mb(r.data)},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=tt(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=tt(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return jt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return vb(n.data)},get isSeen(){const t=tt(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,i=new Date(e.expiresAt).getTime();return Math.max(r,s)>=i}})},storyTarget:vb,message:e=>{const t=Bf(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Wb(e).readCount},get deliveredCount(){return Wb(e).deliveredCount},get creator(){var t;return null===(t=tt(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>Sy(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Gb("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Hb(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=tt(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return jt(n)}}),channel:_g,pinnedPost:e=>{var t;const n=tt(["post","get",e.referenceId]),r=null===(t=et(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return qb(n.data)},get target(){const e=tt(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map((e=>jt(e))),get event(){const t=tt(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:mb,invitation:ab,joinRequest:Yv,channelMember:Mp,room:Nb,event:pw,eventResponse:Yb,product:jb,poll:Bb},mw=async e=>{const t=Ye();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=Xg(r),i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),Ut("user.fetched",r),{data:s.users.map((e=>gw.user(e))),cachedAt:i}};mw.locally=e=>{var t;const n=Ye();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>tt(["user","get",e]))).filter(Boolean),s=r.map((({data:e})=>gw.user(e))),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const yw=async(e,t)=>{var n;const r=Ye();r.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:i}=await r.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),a=Xg(i);return r.cache&&Ff(a),Ut("user.flagged",i),null!==(n=a.users.find((t=>t.userId===e)))&&void 0!==n?n:a.users[0]},vw=e=>am("user.updated",e),bw=e=>am("user.flagged",e),ww=e=>am("user.unflagged",e),Sw=e=>am("user.flagCleared",e),Ew=e=>am("user.fetched",e),Iw=async e=>{const t=Ye();t.log("user/getUser",e),Xf("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),s=Xg(n);return t.cache&&Ff(s,{cachedAt:r}),Ut("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ie(null==t?void 0:t.code)&&Nf("user",e),t}};Iw.locally=e=>{const t=Ye();if(t.log("user/getUser.locally",e),!t.cache)return;const n=tt(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Tw extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Aw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Cw;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Cw||(Cw={}));class _w extends kv{constructor(e,t){const n=Tv(e),r=["user","collection",n];super(new Tw(e),n,r,t),this.query=e,this.queryStreamController=new Aw(this.query,this.cacheKey,this.notifyChange.bind(this),Xg),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:vw,action:Cw.OnUserUpdated},{fn:bw,action:Cw.OnUserFlagged},{fn:ww,action:Cw.OnUserUnflagged},{fn:Sw,action:Cw.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Rw extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}var Ow;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Ow||(Ow={}));class kw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return t=>{var n,r;const s=e===Iv.OnFollowed||e===Ow.OnUnblocked,i=e===Ow.OnBlocked;if(s||i){const e=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[],a=i?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));nt(this.cacheKey,Object.assign(Object.assign({},e),{data:a}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Pw=(e,t,n)=>r=>e((e=>{var s;if(!e)return e;const i=[n,"get",`${e[t]}`],a=null===(s=tt(i))||void 0===s?void 0:s.data;return a?r(a):void 0}));class Dw extends kv{constructor(e,t){const n=Tv(e),r=["blockedUsers","collection",n];super(new Rw(e),n,r,t),this.query=e,this.queryStreamController=new kw(this.query,this.cacheKey,this.notifyChange.bind(this),Mm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:Pw(mv,"to","user"),action:Iv.OnFollowed},{fn:Pw(ov,"to","user"),action:Iv.OnFollowed},{fn:e=>Vm((t=>{var n;if(t.from!==Ye().userId)return;const r=null===(n=tt(["user","get",t.to]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnBlocked},{fn:e=>Ym((t=>{var n;if(t.from!==Ye().userId)return;const r=null===(n=tt(["user","get",t.to]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Lw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return t=>{var n,r;if(t&&(e===Ow.OnBlocked||e===Ow.OnUnblocked)){const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],a=e===Ow.OnBlocked?[...new Set([...i,t.userId])]:i.filter((e=>e!==t.userId));nt(this.cacheKey,Object.assign(Object.assign({},s),{data:a}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xw extends Av{async getRequest(e,t){const{limit:n=H}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Mw extends kv{constructor(e){const t=`blocking-users-${Ye().userId}`,n={},r=["blockingUsers","collection",t];super(new xw(n),t,r,e),this.queryStreamController=new Lw(n,this.cacheKey,this.notifyChange.bind(this),Bm),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:e=>Vm((t=>{var n;if(t.to!==Ye().userId)return;const r=null===(n=tt(["user","get",t.from]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnBlocked},{fn:e=>Ym((t=>{var n;if(t.to!==Ye().userId)return;const r=null===(n=tt(["user","get",t.from]))||void 0===n?void 0:n.data;r&&e(r)})),action:Ow.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Uw extends Av{async getRequest(e,t){const{limit:n=W,displayName:r}=e,s=Bf(e,["limit","displayName"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:r,options:i,isDeleted:!1})});return a}}class Fw extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.users.map(Je("user"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Je("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Nw extends kv{constructor(e,t){var n;const r=Tv(e),s=["user","collection",r];super(new Uw(e),r,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Fw(this.query,this.cacheKey,this.notifyChange.bind(this),Xg),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:om,action:Cw.OnUserDeleted},{fn:vw,action:Cw.OnUserUpdated},{fn:bw,action:Cw.OnUserFlagged},{fn:ww,action:Cw.OnUserUnflagged},{fn:Sw,action:Cw.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["user","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Bw=async({viewId:e,viewedType:t,limit:n,token:r})=>{const s=Ye(),i={};r?i.token=r:i.limit=n;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,o=await s.http.get(a,{params:i});return Ff(o.data),o.data};var jw;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(jw||(jw={}));var $w=Object.freeze({__proto__:null,Relationship:Bv,getUserByIds:mw,updateUser:async(e,t)=>{const n=Ye();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=Xg(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),Ut("user.updated",r),{data:s.users.find((t=>t.userId===e)),cachedAt:i}},flagUser:yw,unflagUser:async e=>{const t=Ye();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=Xg(n);return t.cache&&Ff(r),Ut("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ye().log("user/getAllBlockedUsers");const e=Nm();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ye().log("user/getAllBlockingUsers");const e=qm();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:vw,onUserDeleted:om,onUserFlagged:bw,onUserUnflagged:ww,onUserFlagCleared:Sw,getUser:(e,t)=>Nv(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?gw.user(e.data):e.data}))),"userId",Iw,[Ew,vw,om,bw,ww,Sw]),getUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveUsers(tmpid: ${i}) > listen`);const a=new _w(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getBlockedUsers(tmpid: ${i}) > listen`);const a=new Dw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getBlockedUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e())),it(l)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getBlockingUsers(tmpid: ${r}) > listen`);const s=new Mw(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getBlockingUsers(tmpid: ${r}) > dispose`),i.forEach((e=>e())),it(a)}},searchUsers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveSearchUsers(tmpid: ${i}) > listen`);const a=new Nw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveSearchUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`liveSearchUsers(tmpid: ${i}) > listen`);const a=new Nw(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`liveSearchUsers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:s}=Ye(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(Y);const a=Date.now();r(`getReachUsers(tmpid: ${a}) > listen`);const{limit:o,viewId:l,viewedType:c}=e;return n=(e=!1)=>{var r,s,a;const d=null===(r=tt(i))||void 0===r?void 0:r.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=Be(Bw,{viewId:l,viewedType:c,limit:o||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});$e(h,(e=>{var r,s,a,o,l;let c=null!==(a=null===(s=null===(r=tt(i))||void 0===r?void 0:r.data)||void 0===s?void 0:s.data)&&void 0!==a?a:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};nt(i,d),(e=>{var r,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>tt(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:i,hasNextPage:!!(null===(s=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),je(V,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${a}) > dispose`),it(i)}},get AmityUserSearchMatchType(){return jw}});const qw=async e=>{const t=Ye();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Ff({files:[n]},{cachedAt:r}),{data:$b(n),cachedAt:r}};qw.locally=e=>{const t=Ye();if(t.log("file/getFile.locally",e),!t.cache)return;const n=tt(["file","get",e]);return n?{data:$b(n.data),cachedAt:n.cachedAt}:void 0};const Kw=async(e,t,n)=>{const r=Ye();r.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o.map((e=>$b(e))),cachedAt:l}},Gw=async(e,t,n)=>{const r=Ye();r.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const i=By().getFileAccessType();e.append("accessType",i);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/images",e,{headers:a,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o.map((e=>$b(e))),cachedAt:l}};var Ww=Object.freeze({__proto__:null,getFile:qw,uploadFile:async(e,t)=>{const n=Ye();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=By().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.upload.post("/api/v4/files",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ff({files:a},{cachedAt:o}),{data:a,cachedAt:o}},deleteFile:async e=>{const t=Ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),it(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Kw,uploadImage:Gw,updateAltText:async(e,t)=>{const n=Ye();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Ff({files:[r]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const r=Ye();r.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.upload.post("/api/v4/clips",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),l=r.cache&&Date.now();return r.cache&&Ff({files:o},{cachedAt:l}),{data:o,cachedAt:l}},uploadAudio:async(e,t)=>{const n=Ye();n.log("file/uploadAudio",e);const r=e.getAll("file");if(0===r.length)throw new Error("The formData object must have a `file` key with audio file.");const s=r[0],i=By().getFileAccessType();e.append("accessType",i),e.append("preferredFilename",s.name);const{data:a}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ff({files:a},{cachedAt:o}),{data:a,cachedAt:o}}});const Hw=async e=>{const t=Ye();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:s,displayName:i,sortBy:a}=n,o=Bf(n,["limit","queryToken","displayName","sortBy"]),l=s?{token:s}:r?{limit:r}:void 0,{data:c}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},o),{keyword:i,sortBy:a,options:l})}),{paging:d}=c,u=Bf(c,["paging"]),{roles:h}=u,f=t.cache&&Date.now();t.cache&&Ff(u,{cachedAt:f});const p=Le(d.next);return{data:h,cachedAt:f,prevPage:Le(d.previous),nextPage:p,paging:d}};Hw.locally=e=>{Ye().log("role/queryRoles.locally",e)};const Vw=async e=>{const t=Ye();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Ff({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Vw.locally=e=>{const t=Ye();if(t.log("role/getRole.locally",e),!t.cache)return;const n=tt(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Yw=async(e,t=!1)=>{const n=Ye();let r;n.log("message/getMessage",e),Xf("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await dp(t)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("message",e),t}const s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{messages:i}=r;return Ut("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Yw.locally=e=>{const t=Ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=tt(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Qw{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class zw{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Jw{constructor(e,t){this.postId=e,this.commentId=t}}class Xw{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Zw{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,Zw.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Qw?n=this.processResetTaskInternal(e):e instanceof zw?n=this.processCreateTaskInternal(e):e instanceof Jw&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Zw.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Xw(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.createdCommentIds.has(e.commentId)&&(!(e.createdAt<=t.latestCommentCreatedAt)&&(t.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}computeCommentCount(e){const t=this.commentChangeTracker.get(e);if(!t)return 0;const n=t.serverCommentCount+t.createdCommentIds.size-t.deletedCommentIds.size;return Math.max(0,n)}static publishUpdate(e,t){var n;const r=["post","get",e];rt(r,{localCommentCount:t});const s=null===(n=tt(r))||void 0===n?void 0:n.data;s&&Ut("local.post.updated",{posts:[s]})}}let eS;Zw.BATCH_SIZE=50;var tS=()=>(eS||(eS=new Zw),eS);const nS=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,s=Bf(e,["posts","postChildren","videoStreamings"]),i=qv({communities:s.communities}),a=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),o=jv(i,a);let l=[];const c=t.map((t=>{var n,i,a,o;const c=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,d=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,f;d.length>0&&Ab(d[0])&&(u=r,h=null===(i=d[0].data)||void 0===i?void 0:i.streamId,f=t.postId,l=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:f,postId:f}):e)):u);const p=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),g=0===p.length?(new Date).toISOString():p.map((e=>e.createdAt)).sort().at(-1);return tS().queueCommentChangeTask(new Qw(t.postId,g,null!==(a=t.commentsCount)&&void 0!==a?a:0)),Object.assign(Object.assign({},t),{childPosts:d,feedType:c,localCommentCount:null!==(o=t.localCommentCount)&&void 0!==o?o:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:l,posts:c,communities:o,communityUsers:a})},rS=e=>{var{searchResult:t,polls:n}=e,r=Bf(e,["searchResult","polls"]);const s=nS(r);return Object.assign(Object.assign({},s),{polls:n})},sS=async e=>{const t=Ye();let n;t.log("post/getPost",e),Xf("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("post",e),t}const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:i.find((t=>t.postId===e)),cachedAt:s}};sS.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=tt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const iS=async e=>{const t=Ye();let n;t.log("comment/getComment",e),Xf("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{comments:s}=n;return{data:gw.comment(s.find((t=>t.commentId===e))),cachedAt:r}};iS.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=tt(["comment","get",e]);return n?{data:gw.comment(n.data),cachedAt:n.cachedAt}:void 0};const aS=(e,t)=>{var n,r;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else if("comment"===t)i="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");i="story",s=e.stories[0].referenceId}return(null===(r=null===(n=tt([i,"get",s]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},oS=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},lS=(e,t,n,r=[])=>{const s=e.split(".")[1];let i=r;if(Ye().userId===t)if(["addReaction","reactionAdded"].includes(s))i.includes(n)||i.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);i=i.filter((e=>e!==n))}return i},cS=(e,t)=>{const n=e.split(".")[0],r=aS(t,n),s=lS(e,t.reactor.userId,t.reactor.reactionName,r);return oS(t,`${n}s`,s)},dS=(e,t)=>{var n,r;const s=e.split(".")[0];let i=aS(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(i=lS(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,i));const a=oS(t,"stories",i);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return a;const o=jv(t.communities,t.communityUsers);return Object.assign(Object.assign({},a),{communities:o})},uS=async(e,t,n)=>{var r,s,i;const a=Ye();if(a.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await a.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(a.cache){const l=tt([e,"get",t]);if(!l||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const c=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(s=l.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(i=l.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.addReaction",{comment:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0;if("post"===e)return Ut("local.post.addReaction",{post:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0;if("story"===e)return Ut("local.story.reactionAdded",{story:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.addedId}}),!0}return!0};uS.optimistically=(e,t,n)=>{var r,s,i,a,o;const l=Ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=tt([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(i=c.data.reactions[n])&&void 0!==i?i:0)+1})});return st([e,"get",t],d,{cachedAt:z}),Kb(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==o&&o};const hS=async(e,t,n)=>{var r,s;const i=Ye();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:a}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(i.cache){const o=tt([e,"get",t]);if(!o)return!0;const l=Object.assign(Object.assign({},o.data),{reactionsCount:Math.max(0,o.data.reactionsCount-1),myReactions:(null!==(r=o.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},o.data.reactions),{[n]:Math.max(0,(null!==(s=o.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ut("local.comment.removeReaction",{comment:l,reactor:{reactionId:a.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Ut("local.post.removeReaction",{post:l,reactor:{reactionId:a.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Ut("local.story.reactionRemoved",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:a.removedId}}),!0}return!0};hS.optimistically=(e,t,n)=>{var r,s,i,a;const o=Ye();if(o.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!o.cache)return;const l=tt([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const c=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(s=l.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(i=l.data.reactions[n])&&void 0!==i?i:0)-1)})});return st([e,"get",t],c,{cachedAt:z}),Kb(e,c),!(null===(a=null==c?void 0:c.myReactions)||void 0===a?void 0:a.includes(n))};const fS=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=tt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;nt(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>rt(["post","get",e],{isDeleted:!0})))},pS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s;if(n.cache){const i=nS(r),{communities:a}=i;if(Ff(i,void 0,!1),(null==a?void 0:a[0])&&!["post.updated"].includes(e)&&Ut("community.updated",{communities:a,categories:[],communityUsers:i.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=r.posts[0];fS(r);try{Xf("post",e)}catch(e){return}return s!==n.userId&&it(["post","get",e]),t(r.posts[0])}const o=tt(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=et(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===o.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=tt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&nt(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(o.data)}else t(r.posts[0])}))},gS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{if(n.cache){const{communities:n}=r;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Ut("community.updated",{communities:n,categories:[],communityUsers:r.communityUsers,feeds:[],files:[],users:[]});const s=tt(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&fS(r),t(s.data)}else t(r.posts[0])}))},mS=e=>pS("post.created",e),yS=e=>pS("post.updated",e),vS=e=>pS("post.deleted",e),bS=e=>pS("post.approved",e),wS=e=>pS("post.declined",e),SS=e=>pS("post.flagged",e),ES=e=>pS("post.unflagged",e),IS=e=>{const t=Ye();return Mt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Bf(cS("post.addReaction",n),["reactor"]);Ff(t);const r=tt(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},TS=e=>{const t=Ye();return Mt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Bf(cS("post.removeReaction",n),["reactor"]);Ff(t);const r=tt(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},AS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=aS(e,"comment");return oS(e,"comments",t)})(r):r;Ff(n,void 0,!1);const{comments:i}=n;if(i.length>0){const n=tt(["comment","get",i[0].commentId]);if(["comment.created"].includes(e)&&i[0].parentId){const e=tt(["comment","get",i[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(i[0].commentId)||nt(["comment","get",i[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,i[0].commentId])]})))}if(["comment.deleted"].includes(e)){if(i[0].parentId){const e=tt(["comment","get",i[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(i[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==i[0].commentId))])]});nt(["comment","get",i[0].parentId],t)}}const e=null===(s=et(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}t(gw.comment(n.data))}}else t(gw.comment(r.comments[0]))}))},CS=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{var s,i,a,o,l;if(n.cache){const n=r;Ff(n);const{comments:c}=n;if(c.length>0){const n=tt(["comment","get",c[0].commentId]);if(["local.comment.created"].includes(e)){if(c[0].parentId){const e=tt(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,c[0].commentId])]});nt(["comment","get",c[0].parentId],t),setTimeout((()=>{Ut("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(s=tt(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(i=c[0])||void 0===i?void 0:i.commentId]});nt(e,n)}}const e=null===(a=et(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(c[0].parentId){const e=tt(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==c[0].commentId))])]});nt(["comment","get",c[0].parentId],t),setTimeout((()=>{Ut("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(o=tt(e))||void 0===o?void 0:o.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=c[0])||void 0===t?void 0:t.commentId)}))});nt(e,n)}}const e=null===(l=et(["comment","query"]))||void 0===l?void 0:l.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>st(e,t,{cachedAt:-1})))}t(gw.comment(n.data))}}else t(gw.comment(r.comments[0]))}))},_S=e=>AS("comment.created",e),RS=e=>AS("comment.updated",e),OS=e=>AS("comment.deleted",e),kS=e=>AS("comment.flagged",e),PS=e=>AS("comment.unflagged",e),DS=e=>{const t=Ye();return Mt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Bf(cS("comment.addReaction",n),["reactor"]);Ff(t);const r=tt(["comment","get",n.comments[0].commentId]);e(gw.comment(r.data))}else e(gw.comment(n.comments[0]))}))},LS=e=>{const t=Ye();return Mt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Bf(cS("comment.removeReaction",n),["reactor"]);Ff(t);const r=tt(["comment","get",n.comments[0].commentId]);e(gw.comment(r.data))}else e(gw.comment(n.comments[0]))}))},xS=(e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Mt(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),Ff({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},MS=(e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Mt(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Bf(e,["reactor"]);Ff(n),Ff({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class US extends Av{async getRequest(e,t){const{limit:n=W,referenceType:r}=e,s=Bf(e,["limit","referenceType"]),i=t?{token:t}:{limit:n};Ye().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new Ge("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:a}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:i})});return a}}class FS extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Ye(),s=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=Bf(n,["reactions"]);Ff(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var r,s,i,a;const o=null!==(s=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==s?s:[];if(n)nt(this.cacheKey,{data:o.map(Je("reactor"))});else{const e=null===(i=tt(this.cacheKey))||void 0===i?void 0:i.data,t=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Je("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class NS extends kv{constructor(e,t){const n=Tv(e),r=["reaction","collection",n];super(new US(e),n,r,t),this.query=e,this.queryStreamController=new FS(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>xS(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>MS(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e)return Mt(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(r,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Mt(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Ye(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e)return Mt(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await dp(e);t.reactions[0]&&(Ff(t),Ff({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(r,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bf(e,["reactions"]);Ff(n),Ff({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Mt(r,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["reactor","get",e]))).filter(Boolean).map((({data:e})=>gw.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var BS=Object.freeze({__proto__:null,addReaction:uS,removeReaction:hS,onReactionAdded:(e,t,n)=>{const r=r=>{Je(e)(r)===t&&n(r)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await dp(e),s=tt(["message","get",n.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ff(n),i&&r(n.messages[0])};return Mt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?IS(r):DS(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{Je(e)(r)===t&&n(r)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await dp(e),s=tt(["message","get",n.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ff(n),i&&r(n.messages[0])};return Mt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?TS(r):LS(r)},onReactorAdded:xS,onReactorRemoved:MS,getReactions:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getReactions(tmpid: ${i}) > listen`);const a=new NS(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getReactions(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});function jS(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const $S=async()=>{var e;const t=Ye();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),r=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(it(["archivedChannel","get"]),r.forEach((e=>{e.channelId&&nt(["archivedChannel","get",e.channelId],e)}))),r.map((e=>e.channelId)).filter((e=>!!e))},qS=e=>{const t=Ye(),n=[Mt(t,"onMessageUpdated","message.updated",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])})),Mt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},KS=e=>{const t=Ye(),n=[Mt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])})),Mt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},GS=e=>{const t=Ye(),n=[Mt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await mp(t);Ff(n),e(n.messageFeeds[0])})),Mt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function WS(e,t){nt(["channel","get",e.channelId],zf(e,t))}const HS=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},VS=async(e,t=!1)=>{const n=Ye(),r=await yp(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Ze(r.data.updatedAt)});return t?setTimeout((()=>{Nf("subChannel",e)}),0):st(["subChannel","get",e],s),Ut("local.message-feed.deleted",{messageFeeds:[s]}),s},YS=e=>Mt(Ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),QS=()=>`LOCAL_${Of()}`;let zS;const JS=async(e,t)=>{const n=Ye();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,up(t)),s=await dp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{messages:a}=s;return Ut("local.message.updated",{messages:a}),{data:gw.message(a.find((t=>t.messageId===e))),cachedAt:i}};JS.optimistically=(e,t)=>{const n=Ye();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=tt(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return st(["message","get",e],s,{cachedAt:-1}),Ut("local.message.updated",{messages:[s]}),{data:gw.message(s),cachedAt:-1}};const XS=async(e,t)=>{const n=Ye();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,up(t)),s=await dp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{messages:a}=s;return Ut("local.message.updated",{messages:a}),{data:gw.message(a.find((t=>t.messageId===e))),cachedAt:i}};XS.optimistically=(e,t)=>{const n=Ye();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=tt(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return st(["message","get",e],s,{cachedAt:-1}),Ut("local.message.updated",{messages:[s]}),{data:gw.message(s),cachedAt:-1}};const ZS=async e=>{var t;const n=Ye();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=tt(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return Ut("local.message.deleted",{messages:[r]}),gw.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await dp(r);return Ut("local.message.deleted",{messages:[s.messages[0]]}),gw.message(s.messages[0])};ZS.optimistically=e=>{Ye().log("message/deleteMessage.optimistically",e);const t=tt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return st(["message","get",e],n,{cachedAt:-1}),Ut("local.message.deleted",{messages:[n]}),{data:gw.message(n),cachedAt:-1}};const eE=async e=>{const t=Ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Yw(e);return Ut("local.message.deleted",{messages:[n.data]}),gw.message(n.data)};eE.optimistically=e=>{Ye().log("message/softDeleteMessage.optimistically",e);const t=tt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return st(["message","get",e],n,{cachedAt:-1}),Ut("local.message.deleted",{messages:[n]}),{data:gw.message(n),cachedAt:-1}};const tE=async e=>{const t=Ye();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,s=Bf(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:De(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Bf(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},c),{userFeedMarkers:Gf(l)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];nt(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await mw(o));return{data:u,cachedAt:d,prevPage:Le(a.previous),nextPage:Le(a.next)}};tE.locally=e=>{var t;const n=Ye();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,s=Bf(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:o}=null!==(t=tt(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=tt(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:Le(null==a?void 0:a.paging.previous),nextPage:Le(null==a?void 0:a.paging.next)}};const nE=async e=>{const t=Ye();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,s=Bf(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:De(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Bf(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},c),{userFeedMarkers:Gf(l)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];nt(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await mw(o));return{data:u,cachedAt:d,prevPage:Le(a.previous),nextPage:Le(a.next)}};nE.locally=e=>{var t;const n=Ye();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,s=Bf(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:o}=null!==(t=tt(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=tt(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:Le(null==a?void 0:a.paging.previous),nextPage:Le(null==a?void 0:a.paging.next)}};const rE=e=>{const t=Ye();return Mt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},sE=e=>{const t=Ye();return Mt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},iE=e=>{const t=Ye();return Mt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await dp(t);Ff(n),e(n.messages[0])}))},aE=e=>{const t=Ye();return Mt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await dp(t,"message.reactionAdded");Ff(n),e(n.messages[0])}))},oE=e=>{const t=Ye();return Mt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await dp(t,"message.reactionRemoved");Ff(n),e(n.messages[0])}))},lE=e=>{const t=Ye();return Mt(t,"message/onMessageFetched","local.message.fetched",(t=>{Ff(t),e(t.messages[0])}))},cE=e=>{const t=Ye();return Mt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;rt(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=et(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{rt(e.key,{isDeleted:!0})}))}));const s=null===(n=tt(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class dE extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.messages.map(Je("message")),query:this.query});else{const n=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,i=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...i,...e.messages.map(Je("message"))])]:[...new Set([...e.messages.map(Je("message")),...i])]}))}}reactor(e){return t=>{var n,r,s,i;if("onCreate"===e){const e=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:i}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=i?i:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=i?i:t.messageId])]),nt(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(i=tt(this.cacheKey))||void 0===i?void 0:i.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));nt(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class uE extends Av{async getRequest(e,t){const n=hp(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class hE extends kv{constructor(e,t){const n=Tv(e),r=["message","collection",n];super(new uE(e),n,r,t),this.query=e,this.queryStreamController=new dE(this.query,this.cacheKey,this.notifyChange.bind(this),dp,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ey,action:"onCreate"},{fn:Iy,action:"onCreate"},{fn:KS,action:"onDelete"},{fn:qS,action:"onUpdate"},{fn:rE,action:"onFlagged"},{fn:sE,action:"onUnflagged"},{fn:iE,action:"onFlagCleared"},{fn:aE,action:"onReactionAdded"},{fn:oE,action:"onReactionRemoved"},{fn:Pw(Zy,"contentId","message"),action:"onUpdate"},{fn:Pw(ev,"contentId","message"),action:"onUpdate"},{fn:Pw(cE,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>np(e))).filter(Boolean).map((e=>gw.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=at(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}class fE extends Av{async getRequest(e,t){const{query:n,exactMatch:r,channelId:s,messageFeedId:i,userIds:a,tags:o,types:l,sortBy:c,orderBy:d,limit:u=W}=e,h=t?{token:t}:{limit:u,sortBy:c,orderBy:d},{data:f}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:r,channelId:s,messageFeedId:i,userIds:a,tags:o,types:l,options:h}});return f}}class pE extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await dp(e),r=Ye(),s=r.cache&&Date.now();r.cache&&(Ff(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{nt(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var r,s;if(n)return void nt(this.cacheKey,{data:e.messages.map(Je("message"))});const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[],o=e.messages.map(Je("message"));nt(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...a])]:[...new Set([...a,...o])]}))}}class gE extends kv{constructor(e,t){const n=Tv(e),r=["message","search",n];super(new fE(e),n,r,t),this.queryStreamController=new pE(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>np(e))).filter(Pv).map((e=>gw.message(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var mE=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ye();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Ye();if(!r.cache)return;zS=e.referenceId||QS();const s=Object.assign({messageId:zS,uniqueId:zS},e);r.log("message/createMessage.optimistically",s);const i=tt(["subChannel","get",e.subChannelId]);if(i&&(st(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},i.data),{messageCount:i.data.messageCount+1})),i.data.channelId===i.data.subChannelId)){const e=tt(["channel","get",i.data.channelId]);(null==e?void 0:e.data)&&st(["channel","get",i.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const a=(new Date).toISOString(),o=Object.assign({creatorId:r.userId,creatorPrivateId:Rt()._id,channelSegment:(null!==(n=null==i?void 0:i.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:a,updatedAt:a,syncState:"syncing",isDeleted:!1},s);return nt(["message","get",o.messageId],o,{cachedAt:-5}),Ut("local.message.created",{messages:[o]}),o})(e),r=e.referenceId||zS||QS();zS=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},up(e)),{referenceId:r})),s=await dp(n),{messages:i}=s,a=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:a}),Ut("local.message.created",{messages:[Object.assign(Object.assign({},i[0]),{syncState:"synced"})]}),{data:gw.message(i[0]),cachedAt:a}}catch(e){throw Ut("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:JS,editMessage:XS,deleteMessage:ZS,softDeleteMessage:eE,markAsDelivered:async(e,t)=>{const n=Ye();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:i,userFeedMarkers:a}=r,o=Bf(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=n.cache&&Date.now();return n.cache&&Ff(Object.assign({userMarkers:s,userEntityMarkers:Kf(i),userFeedMarkers:Gf(a)},o),{cachedAt:l}),!0},getReadUsers:tE,getDeliveredUsers:nE,flagMessage:async(t,n)=>{const r=Ye();r.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:a}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,i);if(r.cache){const e=await dp(a);Ff(e)}return Ut("message.flagged",a),!!a},unflagMessage:async e=>{const t=Ye();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await dp(n);Ff(e)}return Ut("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ye();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ey,onMessageCreatedLocal:Iy,onMessageUpdated:qS,onMessageDeleted:KS,onMessageFlagged:rE,onMessageUnflagged:sE,onMessageFlagCleared:iE,onMessageReactionAdded:aE,onMessageReactionRemoved:oE,onMessageFetched:lE,getMessage:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.message(e.data):n}))}),"messageId",Yw,[lE,qS,KS,rE,sE,iE,aE,oE,Pw(Zy,"contentId","message"),Pw(ev,"contentId","message"),Pw(cE,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMessages(tmpid: ${i}) > listen`);const a=new hE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMessages(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const i=new gE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},convertFromRaw:lp,prepareMessagePayload:dp,convertParams:up,convertQueryParams:hp});const yE=e=>{const t=Ye();return Mt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class vE extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Bf(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Bf(e,["limit"])))&&void 0!==n?n:{},{channelId:i,includeDeleted:a}=s,o=Bf(s,["channelId","includeDeleted"]),l=t?{token:t}:{limit:r},{data:c}=await this.http.get(`/api/v5/message-feeds/channel/${i}`,{params:Object.assign(Object.assign({},o),{isDeleted:rp(a),options:l})});return c}}class bE extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),nt(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class wE extends kv{constructor(e,t){const n=Tv(e),r=["subChannel","collection",n];super(new vE(e),n,r,t),this.query=e,this.queryStreamController=new bE(this.query,this.cacheKey,this.notifyChange.bind(this),mp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:YS,action:"onCreate"},{fn:Ty,action:"onCreate"},{fn:Ay,action:"onDelete"},{fn:e=>GS((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ye();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=Vf(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Hf(t.updatedAt)>Hf(e.subChannelUpdatedAt)&&nt(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{this.isRelatedCollection(t.subChannelId)&&(await bp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{this.isRelatedCollection(t.subChannelId)&&(await bp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Jy((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>tt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Pw(zy,"feedId","subChannel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{var n;const r=Ye();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(wp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=Ye(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await yp(t.subChannelId):await wp(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pw(yE,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yf))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=at(e,"isDeleted",!1)),t.sort(Tt),t}isRelatedCollection(e){var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const SE={},EE=async e=>{const t=await(async e=>{const t=yp.locally(e);if(t)return t.data.channelId;const{data:n}=await yp(e);return n.channelId})(e),n=Vt({channelId:t,subChannelId:e});SE[e]=Zt(n)};var IE=Object.freeze({__proto__:null,getSubChannelByIds:Ug,createSubChannel:async e=>{const t=Ye();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await mp(n.data),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),Ut("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ye();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await mp(r.data),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),Ut("message-feed.updated",r.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:VS,hardDeleteSubChannel:async e=>{Ye().log("channel/hardDeleteSubChannel",e);return await VS(e,!0)},softDeleteSubChannel:async e=>{Ye().log("channel/softDeleteSubChannel",e);return await VS(e,!1)},onSubChannelCreated:Ty,onSubChannelUpdated:GS,onSubChannelDeleted:Ay,getSubChannel:(e,t)=>{const n=Ye();let r;return Nv(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yf(e.data)}),s=Bf(n,["origin"]);return Fp(r,s)?void 0:(r=s,t(n))}),"subChannelId",yp,[YS,t=>GS((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ip(r),r.subChannelId===e&&t(r))})),Ay,Pw(zy,"feedId","subChannel"),t=>Jy((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(r=tt(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&t(s)})),Pw((t=>Ey((async n=>{n.subChannelId===e&&(await bp(n),t(n))}))),"subChannelId","subChannel"),Pw((t=>Iy((async n=>{n.subChannelId===e&&(await bp(n),t(n))}))),"subChannelId","subChannel"),Pw((t=>qS((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(wp(r),t(r))}))),"subChannelId","subChannel"),Pw((t=>KS((async r=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&r.subChannelId===e&&("message-preview-include-deleted"===s&&await wp(r),"message-preview-not-include-deleted"===s&&await yp(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Pw(yE,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:s}=Ye(),i=Date.now();r(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(Y);const a=new wE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getSubChannels(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markReadEngineOnLoginHandler:Mg,startMessageReceiptSync:async e=>(await EE(e),!0),stopMessageReceiptSync:e=>(SE[e]&&SE[e](),!0)});const TE=e=>{const t=Ye();return Mt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},AE=e=>{const t=Ye();return Mt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class CE extends Av{async getRequest(e,t){const{limit:n=W,displayName:r,membership:s}=e,i=Bf(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:r,filter:s,options:a})});return o}}class _E extends Ov{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class RE extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.channels.map(Je("channel"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Je("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof _E)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(Je("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Je("channel")):[Je("channel")(t)];r.data=r.data.filter((t=>!e.includes(t)))}nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const OE=e=>{const t=Ye();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){km().resolve(e.channelId,"userMessageFeedMarker")}},kE=e=>{const t=Ye();return Mt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},PE=e=>{const t=Ye();return Mt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class DE extends kv{constructor(e,t){const n=Tv(e),r=["channel","collection",n],s=DE.getPaginationController(e);super(s,n,r,t),this.query=e,this.queryStreamController=new RE(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ye();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await kp(e)}catch(e){console.error("Error while preparing unread count info",e)}return Rp(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;let a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Rg))&&void 0!==s?s:[];this.paginationController instanceof CE&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof CE?()=>this.loadPage({direction:"next"}):void 0,data:a,hasNextPage:this.paginationController instanceof CE&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;switch(n=at(n,"isDeleted",this.query.isDeleted),n=ot(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=ct(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(bt);break;case"lastCreated":n=n.sort(St);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(yt);break;default:n=n.sort(Tt)}return n}shouldAbort(e){var t,n;const r=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new _E(e):new CE(e)}getSubscriptions(){const e=[{fn:Pw((e=>Ey((t=>{var n,r;const s=km();(null===(n=tt(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const i=null===(r=tt(["channel","get",t.channelId]))||void 0===r?void 0:r.data;i?(WS(i,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Yp,action:"onDelete"},{fn:Kp,action:"onUpdate"},{fn:rg,action:"onMute"},{fn:e=>Jp((t=>{OE(t),e(t)})),action:"onJoin"},{fn:e=>eg(((t,n)=>{var r,s;const{userId:i}=Ye();if("member"===this.query.membership&&i===n.userId){const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;nt(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:ag,action:"onMemberAdded"},{fn:cg,action:"onMemberRemoved"},{fn:e=>Eg((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ig((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pw(Qy,"entityId","channel"),action:"onUpdate"},{fn:Pw(HS,"entityId","channel"),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{"no-message-preview"!==await DE.getMessagePreviewSetting()&&(await Ep(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=await DE.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ep(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await wb(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Ay((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Wf(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await wb(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>GS((async t=>{var n;if("no-message-preview"===await DE.getMessagePreviewSetting())return;(null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ip(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw(Ty,"channelId","channel"),action:"onUpdate"},{fn:kE,action:"onResolveChannel"},{fn:e=>PE((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=tt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pw(TE,"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Av?[...e,{fn:e=>jp((t=>{OE(t),e(t)})),action:"onCreate"}]:e}}const LE=()=>{var e;const t=Ye();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=et(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class xE extends Av{async getRequest(e,t){var n,r;const s=null!==(n=e.limit)&&void 0!==n?n:W,i=t?Number.parseInt(t,10):0;0===i&&await $S();const a=(null!==(r=et(["archivedChannel","get"]))&&void 0!==r?r:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),o=i*s,l=o+s,c=a.slice(o,l),d=l<a.length;return c.length>0&&await Og(c.map((e=>e.channelId))),{archives:c,paging:{next:d?String(i+1):void 0,previous:void 0}}}}class ME extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var r,s;const i=e.archives.map((e=>e.channelId));if(n)return void nt(this.cacheKey,{data:i,params:{}});const a=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,o=null!==(s=null==a?void 0:a.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},a),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if("onArchived"===e){const e=r.data.filter((e=>!t.includes(e)));r.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(r.data=r.data.filter((e=>!t.includes(e)))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class UE extends kv{constructor(e,t){const n=Tv(e),r=["archivedChannel","collection",n];super(new xE(e),n,r,t),this.queryStreamController=new ME(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>Eg((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Ig((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Kp((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Yp((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Rg))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class FE extends Av{async getRequest(e,t){const{query:n,exactMatch:r,isMemberOnly:s,types:i,tags:a,sortBy:o,orderBy:l,limit:c=H}=e,d=t?{token:t}:{limit:Math.min(100,Math.max(1,c))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:r,isMemberOnly:s,types:i,tags:a,sortBy:o,orderBy:l,options:d}});return u}}class NE extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Rp(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)return void nt(this.cacheKey,{data:e.channels.map(Je("channel"))});const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[],o=e.channels.map(Je("channel"));nt(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...a])]:[...new Set([...a,...o])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const BE=()=>Ye().getMessagePreviewSetting(!1);class jE extends kv{constructor(e,t){const n=Tv(e),r=["channel","search",n];super(new FE(e),n,r,t),this.queryStreamController=new NE(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["channel","get",e]))).filter(Boolean).map((e=>Rg(e.data))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}shouldAbort(e){var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Pw((e=>Ey((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((t=>{var n;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Yp,action:"onDelete"},{fn:Kp,action:"onUpdate"},{fn:rg,action:"onMute"},{fn:e=>Eg((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ig((t=>{const n=t.archives.map((e=>{var t;return null===(t=tt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pw(Qy,"entityId","channel"),action:"onUpdate"},{fn:Pw(HS,"entityId","channel"),action:"onUpdate"},{fn:Pw((e=>Ey((async t=>{var n;if("no-message-preview"===await BE())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Iy((async t=>{var n;if("no-message-preview"===await BE())return;if(Sp(t),this.shouldAbort(t.channelId))return;const r=null===(n=tt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(WS(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>qS((async t=>{"no-message-preview"!==await BE()&&(await Ep(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>KS((async t=>{const n=await BE();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ep(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await wb(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>Ay((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Wf(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await wb(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>GS((async t=>{var n;if("no-message-preview"===await BE())return;(null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ip(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>PE((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=tt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pw(TE,"channelId","channel"),action:"onUpdate"},{fn:Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class $E extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r}=e,s=Bf(e,["limit","includeDeleted"]),i=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:o}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:i,isDeleted:a})});return o}}class qE extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Je("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Je("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=Je("channelUsers")({channelId:this.query.channelId,userId:t.userId}),i=this.query.memberships,a=!i||i.includes(t.membership);"none"!==t.membership&&a?r.data.includes(s)||(r.data=[s,...r.data]):r.data=r.data.filter((e=>e!==s)),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class KE extends kv{constructor(e,t){const n=Tv(e),r=["channelUsers","collection",n];super(new $E(e),n,r,t),this.query=e,this.queryStreamController=new qE(this.query,this.cacheKey,this.notifyChange.bind(this),Rp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Jp,action:"onJoin"},{fn:eg,action:"onLeft"},{fn:ag,action:"onMemberAdded"},{fn:cg,action:"onMemberRemoved"},{fn:hg,action:"onChannelMemberBanned"},{fn:gg,action:"onChannelMemberUnbanned"},{fn:vg,action:"onChannelMemberRoleAdded"},{fn:Sg,action:"onChannelMemberRoleRemoved"},{fn:Cg,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{var r,s;const i=Xg(n);if(0===i.users.length)return;const a=i.users[0];Ff(i);const o=Je("channelUsers")({channelId:e,userId:a.userId}),l=null===(r=tt(["channelUsers","get",o]))||void 0===r?void 0:r.data;st(["channelUsers","get",o],Object.assign(Object.assign({},l),{user:a}));const c=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;c&&t(c,l)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(gw.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=lt(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?St:bt),t}}const GE=(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new KE(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}};var WE=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Ut("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Rp(r);n.cache&&Ff(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ye();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Ut("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Rp(r);n.cache&&Ff(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=lt(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?St:bt),n},getMembers:GE,searchMembers:(e,t,n)=>GE(e,t)});var HE=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Ye();r.log("channel/addRole",e,t,n);const{data:s}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),i=await Rp(s);r.cache&&Ff(i),Ut("local.channel-moderator.role-added",i);const{channelUsers:a}=i;return!!a.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Ye();r.log("channel/removeRole",e,t,n);const{data:s}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),i=await Rp(s);r.cache&&Ff(i),Ut("local.channel-moderator.role-removed",i);const{channelUsers:a}=i;return!!a.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ye();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Rp(r),{channelUsers:i}=s,a=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:a}),Ut("channel.banned",r),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const n=Ye();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Rp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i}),Ut("channel.unbanned",r);const{channelUsers:a}=s;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:i}},muteMembers:async(e,t,n=-1)=>{var r;const s=Ye();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:i}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:a}=i,o=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return Ut("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:o,actor:null!==(r=s.userId)&&void 0!==r?r:""}),a},unmuteMembers:async(e,t)=>{var n;const r=Ye();r.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:i}=s;return Ut("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=r.userId)&&void 0!==n?n:""}),i}}),VE=Object.freeze({__proto__:null,Membership:WE,Moderation:HE,getChannelByIds:Og,createChannel:bb,updateChannel:async(e,t)=>{const n=Ye();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Rp(r),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{channels:a}=s;return{data:xp(a.find((t=>t.channelId===e))),cachedAt:i}},deleteChannel:async e=>{const t=Ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await wb(e);return xp(n.data)},joinChannel:async e=>{const t=Ye();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await Rp(n);t.cache&&Ff(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ye();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await Rp(n);t.cache&&Ff(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ye();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Ke("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=r;return s},unmuteChannel:async e=>{const t=Ye();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},archiveChannel:async e=>{const t=Ye();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&nt(["archivedChannel","get",Je("archivedChannel")(n)],n),Ut("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ye();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const r=null===(t=tt(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=r?r:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&it(["archivedChannel","get",e],!0),Ut("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:$S,onChannelCreated:jp,onChannelUpdated:Kp,onChannelDeleted:Yp,onChannelJoined:Jp,onChannelLeft:eg,onChannelSetMuted:rg,onChannelMemberAdded:ag,onChannelMemberRemoved:cg,onChannelMemberBanned:hg,onChannelMemberUnbanned:gg,onChannelMemberRoleAdded:vg,onChannelMemberRoleRemoved:Sg,onChannelArchived:Eg,onChannelUnarchived:Ig,getChannel:(e,t)=>{const n=Ye();let r;return Nv(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Rg(e.data)}),s=Bf(n,["origin"]);return Fp(r,s)?void 0:(r=s,t(n))}),"channelId",wb,[Kp,Yp,Jp,eg,ag,cg,hg,gg,rg,Pw(Qy,"entityId","channel"),Pw(HS,"entityId","channel"),Pw((t=>Ey((async r=>{await(async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sp(r),r.channelId!==e)return;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;i&&(WS(i,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Pw((t=>Iy((async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sp(r),r.channelId!==e)return;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;i&&(WS(i,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Pw((t=>qS((async r=>{var s;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Ep(r),t(r))}))),"channelId","channel"),Pw((t=>KS((async r=>{var s;const i=null===(s=tt(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==r.messageId)return;const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(it(["messagePreviewChannel","get",e]),await wb(r.channelId)):await Ep(r),t(r))}))),"channelId","channel"),Pw((e=>Ay((async t=>{var r,s;const{channelId:i,subChannelId:a}=t,o=null===(r=tt(["messagePreviewChannel","get",i]))||void 0===r?void 0:r.data;if(!o||o.subChannelId!==a)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await wb(i);(null===(s=tt(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Pw((t=>GS((async r=>{var s,i;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ip(r);const a=null===(s=tt(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!a||a.subChannelId!==r.subChannelId)return;(null===(i=tt(["channel","get",e]))||void 0===i?void 0:i.data)&&t(r)}))),"channelId","channel"),Pw(Ty,"channelId","channel"),Pw(TE,"channelId","channel"),Pw((e=>AE((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getChannels(tmpid: ${a}) > listen`);const o=new DE(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getChannels(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Rt();if(!t)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Ye();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;i=r?nv(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(AE((e=>{const{data:t}=LE();Fp(i,t)||o({loading:!1,data:t})}))),(()=>{const e=Be((async()=>LE()));$e(e,(({error:e,data:t,loading:n,origin:r,cachedAt:i})=>{i===z?(o({data:t,origin:r,loading:!1,error:new Ge(Q,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const i=new UE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:r}=Ye();r||console.log(Y);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const i=new jE(e,t),a=i.startSubscription(),o=i.getCacheKey();return a.push((()=>{it(o)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Tp,isUnreadCountSupport:Ap,convertFromRaw:Cp,preUpdateChannelCache:_p,prepareChannelPayload:Rp});const YE=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));nt(["communityUsers","collection",e],n)}))},QE=async(e,t)=>{const n=Ye();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),i=Kv(s),a=n.cache&&Date.now();return n.cache&&(Ff(i,{cachedAt:a}),YE(i.communities,i.communityUsers)),{data:i.communities.map((e=>gw.community(e))),cachedAt:a}};QE.locally=e=>{const t=Ye();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>tt(["community","get",e]))).filter(Boolean),r=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:r,cachedAt:s.cachedAt}};const zE=async e=>{const t=Ye();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Kv(n),s=t.cache&&Date.now();t.cache&&(Ff(r,{cachedAt:s}),YE(r.communities,r.communityUsers));const{communities:i}=r;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};zE.locally=e=>{const t=Ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=tt(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const JE=(e,t)=>{const n=Ye();return Mt(n,e,e,(e=>{const r=Kv(e);if(n.cache){Ff(r);const e=tt(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},XE=e=>JE("community.created",e),ZE=e=>JE("community.updated",e),eI=e=>JE("community.deleted",e);class tI extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=Bf(e,["limit"]),i=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:rp(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:i})});return a}}class nI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var rI,sI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(rI||(rI={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(sI||(sI={}));class iI extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,excludingRoles:s}=e,i=Bf(e,["limit","includeDeleted","excludingRoles"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:l}=await this.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a,isDeleted:o})});return l}}class aI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{var t;const n=Je("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)r.data=r.data.filter((e=>e!==n));else if(!r.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}r.data=[n,...r.data]}})),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function oI(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function lI(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!oI(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!oI(e,t,"ADD_COMMUNITY_USER")))}const cI=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{const s=Kv(r),{communities:i,communityUsers:a}=s,o=jv(i,a);if(s.communities=o,n.cache){Ff(s,void 0,!1);const n=tt(["community","get",s.communities[0].communityId]),r=lI(e,s).map((e=>{const t=tt(["communityUsers","get",Je("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pv);t(n.data,r)}else t(s.communities[0],lI(e,s))}))},dI=(e,t)=>{const n=Ye();return Mt(n,e,e,(r=>{const s=Kv(r),{communities:i,communityUsers:a}=s,o=jv(i,a);if(s.communities=o,n.cache){Ff(s,void 0,!1);const n=tt(["community","get",s.communities[0].communityId]),r=lI(e,s).map((e=>{const t=tt(["communityUsers","get",Je("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pv);t(n.data,r)}else t(s.communities[0],lI(e,s))}))},uI=e=>cI("community.userBanned",e),hI=e=>cI("community.userChanged",e),fI=e=>cI("community.userUnbanned",e),pI=e=>cI("community.roleAdded",e),gI=e=>cI("community.roleRemoved",e),mI=e=>dI("local.community.userAdded",e),yI=e=>dI("local.community.userRemoved",e),vI=e=>cI("community.joined",e),bI=e=>cI("community.left",e),wI=e=>dI("local.community.joined",e),SI=e=>dI("local.community.left",e),EI=e=>{const t=Ye(),n=[Mt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},II=e=>{const t=Ye();return Mt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},TI=e=>{const t=Ye();return Mt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},AI=e=>t=>{const n=Ye();return Mt(n,"user.deleted","user.deleted",(n=>{var r,s;const i=Xg(n);if(0===i.users.length)return;const a=i.users[0];Ff(i);const o=Je("communityUsers")({communityId:e,userId:a.userId}),l=null===(r=tt(["communityUsers","get",o]))||void 0===r?void 0:r.data;nt(["communityUsers","get",o],Object.assign(Object.assign({},l),{user:a}));const c=null===(s=tt(["community","get",e]))||void 0===s?void 0:s.data;t(c,[Object.assign(Object.assign({},l),{user:a})])}))};class CI extends kv{constructor(e,t){const n=Tv(e),r=["communityUsers","collection",n];super(new iI(e),n,r,t),this.query=e,this.queryStreamController=new aI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vI,action:sI.OnCommunityJoined},{fn:wI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:SI,action:sI.OnCommunityLeft},{fn:uI,action:sI.OnCommunityUserBanned},{fn:hI,action:sI.OnCommunityUserChanged},{fn:pI,action:sI.OnCommunityUserRoleAdded},{fn:gI,action:sI.OnCommunityUserRoleRemoved},{fn:TI,action:sI.OnCommunityUserRoleAdded},{fn:II,action:sI.OnCommunityUserRoleRemoved},{fn:fI,action:sI.OnCommunityUserUnbanned},{fn:mI,action:sI.OnCommunityUserAdded},{fn:yI,action:sI.onCommunityUserRemoved},{fn:AI(this.query.communityId),action:sI.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["communityUsers","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class _I extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,excludingRoles:s}=e,i=Bf(e,["limit","includeDeleted","excludingRoles"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:l}=await this.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a,isDeleted:o})});return l}}class RI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Je("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Je("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var OI;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(OI||(OI={}));class kI extends kv{constructor(e,t){const n=Tv(e),r=["communityUsers","collection",n];super(new _I(e),n,r,t),this.query=e,this.queryStreamController=new RI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vI,action:OI.OnCommunityJoined},{fn:wI,action:OI.OnCommunityJoined},{fn:bI,action:OI.OnCommunityLeft},{fn:SI,action:OI.OnCommunityLeft},{fn:uI,action:OI.OnCommunityUserBanned},{fn:hI,action:OI.OnCommunityUserChanged},{fn:II,action:OI.OnCommunityUserRoleRemoved},{fn:gI,action:OI.OnCommunityUserRoleRemoved},{fn:fI,action:OI.OnCommunityUserUnbanned},{fn:AI(this.query.communityId),action:OI.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["communityUsers","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=ft(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var PI=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Ut("local.community.userAdded",r);const s=$f(r,"communityUsers");n.cache&&Ff(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Ut("local.community.userRemoved",r);const s=$f(r,"communityUsers");n.cache&&Ff(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let r=lt(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(r=r.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const s=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===s?St:bt),r},getMembers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new CI(e,(e=>{t(e)})),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const a=new kI(e,(e=>{t(e)})),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},onCommunityUserAdded:e=>cI("community.userAdded",e),onCommunityUserRemoved:e=>cI("community.userRemoved",e),onCommunityUserBanned:uI,onCommunityUserChanged:hI,onCommunityUserUnbanned:fI,onCommunityUserRoleAdded:pI,onCommunityUserRoleRemoved:gI,onLocalCommunityUserAdded:mI,onLocalCommunityUserRemoved:yI,onCommunityJoined:vI,onCommunityLeft:bI,onLocalCommunityJoined:wI,onLocalCommunityLeft:SI,onLocalCommunityJoin:EI});class DI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new tI(e),n,r,t),this.query=e,this.queryStreamController=new nI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:rI.OnCommunityDeleted},{fn:ZE,action:rI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:rI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=ut(n,this.query.membership,t)),n}}class LI extends Av{async getRequest(e,t){var n;const{limit:r=W}=e,s=Bf(e,["limit"]),i=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:rp(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:i})});return a}}class xI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var MI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(MI||(MI={}));class UI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new LI(e),n,r,t),this.query=e,this.queryStreamController=new xI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:XE,action:MI.OnCommunityCreated},{fn:eI,action:MI.OnCommunityDeleted},{fn:ZE,action:MI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:MI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=ut(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?bt:St)();return n=n.sort(r),n}}class FI extends Av{async getRequest(e,t){const{limit:n=W,includeDiscoverablePrivateCommunity:r}=e,s=Bf(e,["limit","includeDiscoverablePrivateCommunity"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:i,includeDiscoverablePrivateCommunity:null==r||r})});return a}}class NI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var BI;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(BI||(BI={}));class jI extends kv{constructor(e,t){const n=Tv(e),r=["trendingCommunity","collection",n];super(new FI(e),n,r,t),this.query=e,this.queryStreamController=new NI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:BI.OnCommunityDeleted},{fn:ZE,action:BI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:BI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class $I extends Av{async getRequest(e,t){const{limit:n=W,includeDiscoverablePrivateCommunity:r}=e,s=Bf(e,["limit","includeDiscoverablePrivateCommunity"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:i,includeDiscoverablePrivateCommunity:null==r||r})});return a}}class qI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&(Ff(t,{cachedAt:r}),YE(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.communities.map(Je("community"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Je("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var KI;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(KI||(KI={}));class GI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new $I(e),n,r,t),this.query=e,this.queryStreamController=new qI(this.query,this.cacheKey,this.notifyChange.bind(this),Kv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:eI,action:KI.OnCommunityDeleted},{fn:ZE,action:KI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:KI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>mb(e))))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class WI extends Av{async getRequest(e,t){var n;const{limit:r=W,communityMembershipStatus:s}=e,i=Bf(e,["limit","communityMembershipStatus"]),a={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:r}),{data:l}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},i),{filter:null!=s?s:"all",options:o,includeDiscoverablePrivateCommunity:null===(n=i.includeDiscoverablePrivateCommunity)||void 0===n||n})});return l}}function HI(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class VI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:HI(e)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...HI(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var YI;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(YI||(YI={}));class QI extends kv{constructor(e,t){const n=Tv(e),r=["community","collection",n];super(new WI(e),n,r,t),this.query=e,this.queryStreamController=new VI(this.query,this.cacheKey,this.notifyChange.bind(this),Vv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:XE,action:YI.OnCommunityCreated},{fn:eI,action:YI.OnCommunityDeleted},{fn:ZE,action:YI.OnCommunityUpdated},{fn:vI,action:sI.OnCommunityJoined},{fn:bI,action:sI.OnCommunityLeft},{fn:hI,action:sI.OnMemberCountChanged},{fn:wI,action:sI.OnCommunityJoined},{fn:SI,action:sI.OnCommunityLeft},{fn:Pw(EI,"targetId","community"),action:YI.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>tt(["community","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=ut(n,this.query.communityMembershipStatus,t)),n}}class zI extends Av{async getRequest(e,t){const{limit:n=W,communityIds:r}=e,s=Bf(e,["limit","communityIds"]),i=t?{token:t}:{limit:n},a=r.map((e=>encodeURIComponent(e))),{data:o}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:i,communityIds:a})});return o}}var JI;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(JI||(JI={}));class XI extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Je("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===JI.OnLocalJoinRequestUpdated){if(!r.data.find((e=>s.includes(e))))return}e===JI.OnLocalJoinRequestCreated&&(r.data=[...new Set([...s,...r.data])]),e===JI.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!s.includes(e)))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ZI extends kv{constructor(e,t){const n=Tv(e),r=["joinRequestList","collection",n];super(new zI(e),n,r,t),this.query=e,this.queryStreamController=new XI(this.query,this.cacheKey,this.notifyChange.bind(this),Gv),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xv,action:JI.OnLocalJoinRequestCreated},{fn:Zv,action:JI.OnLocalJoinRequestUpdated},{fn:eb,action:JI.OnLocalJoinRequestUpdated},{fn:EI,action:JI.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=this.applyFilter(s.data.map((e=>tt(["joinRequest","get",e]))).filter(Pv).map((({data:e})=>e)).map(Yv));(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}var eT;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(eT||(eT={}));var tT=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Ye();r.log("community/moderation/addRoles",e,t,n);const{data:s}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),i=Wv(s);r.cache&&Ff(i),Ut("local.community.roleAdded",i);const{communityUsers:a}=i;return!!a.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Ye();r.log("community/moderation/removeRoles",e,t,n);const{data:s}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),i=Wv(s);r.cache&&Ff(i),Ut("local.community.roleRemoved",i);const{communityUsers:a}=i;return!!a.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ye();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=$f(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ye();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=$f(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ff(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}}}),nT=Object.freeze({__proto__:null,Moderation:tT,Membership:PI,getCommunityByIds:QE,createCommunity:async e=>{const t=Ye();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Hv(e));Ut("community.created",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&(Ff(r,{cachedAt:s}),YE(r.communities,r.communityUsers));const{communities:i}=r;return{data:gw.community(i[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ye();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Hv(t));Ut("community.updated",r);const s=Kv(r),i=n.cache&&Date.now();n.cache&&(Ff(s,{cachedAt:i}),YE(s.communities,s.communityUsers));const{communities:a}=s;return{data:gw.community(a.find((t=>t.communityId===e))),cachedAt:i}},deleteCommunity:async e=>{const t=Ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await zE(e);return Ut("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),gw.community(n.data)},joinCommunity:async e=>{const t=Ye();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Ut("local.community.joined",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ye();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Ut("local.community.left",n);const r=Kv(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:XE,onCommunityUpdated:ZE,onCommunityDeleted:eI,searchCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchCommunities(tmpid: ${i}) > listen`);const a=new DI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunities(tmpid: ${i}) > listen`);const a=new UI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunity:(e,t)=>Nv(e,t,"communityId",zE,[ZE,eI,vI,bI,wI,SI,uI,fI,hI,Pw(EI,"targetId","community")],{callbackDataSelector:e=>e?gw.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getTrendingCommunities(tmpid: ${a}) > listen`);const o=new jI(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>it(c))),()=>{r(`getTrendingCommunities(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getRecommendedCommunities(tmpid: ${a}) > listen`);const o=new GI(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>it(c))),()=>{r(`getRecommendedCommunities(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`semanticSearchCommunities(tmpid: ${i}) > listen`);const a=new QI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`semanticSearchCommunities(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getJoinRequestList: (tmpid: ${i}) > listen`);const a=new ZI(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getJoinRequestList (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return eT}});const rT=async e=>{const t=Ye();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{categories:s}=n;return{data:gw.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:r}};rT.locally=e=>{const t=Ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=tt(["category","get",e]);return n?{data:gw.category(n.data),cachedAt:n.cachedAt}:void 0};const sT=async e=>{const t=Ye();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:s,includeDeleted:i}=n,a=Bf(n,["page","limit","includeDeleted"]),o=r?{token:r}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:rp(i),options:o})}),{paging:c}=l,d=Bf(l,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Ff(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:i,options:o})];nt(e,{categories:null==u?void 0:u.map(Je("category")),paging:c})}return{data:null!=u?u:[],cachedAt:h,paging:c}};sT.locally=e=>{var t,n;const r=Ye();if(r.log("category/queryCategories.locally",e),!r.cache)return;const s=null!=e?e:{},{page:i,limit:a=10}=s,o=Bf(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["category","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=tt(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>tt(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:f}:void 0};var iT=Object.freeze({__proto__:null,getCategory:rT,getCategories:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCategories(tmpid: ${i}) > listen`);const{limit:a}=e,o=Bf(e,["limit"]),l=null!=a?a:W,{policy:c=V}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,s;const i=null===(r=tt(u))||void 0===r?void 0:r.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!n&&a.length>0&&!(null==i?void 0:i.params.page))return;const d=Be(sT,Object.assign(Object.assign({},o),{limit:n?l:void 0,page:n||null==i?void 0:i.params.page}));$e(d,(({data:n,error:r,loading:s,paging:i})=>{const o={loading:s,error:r,params:{page:null==i?void 0:i.next},data:a};n&&(o.data=[...new Set([...a,...n.map(Je("category"))])]),nt(u,o),(n=>{var r,s;let i=null!==(r=n.data.map((e=>tt(["category","get",e]))).filter(Boolean).map((({data:e})=>gw.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(i=at(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(bt);break;case"lastCreated":i=i.sort(St);break;default:i=i.sort(vt)}t({onNextPage:h,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(o)}),je(c))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const aT=async e=>{const t=Ye();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:s}=n,i=Bf(n,["queryToken","dataTypes"]),a=(()=>{if(r)return{token:r}})(),{data:o}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},i),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:a})}),{paging:l}=o,c=Bf(o,["paging"]),d=$f(c,"communityUsers"),{posts:u}=d,{communities:h}=Kv(d),f=t.cache&&Date.now();if(t.cache){Ff(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},i),{options:a})];nt(e,{posts:u.map(Je("post")),paging:l})}return{data:u.map(gw.post),cachedAt:f,paging:l}};aT.locally=e=>{var t;const n=Ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const r=Bf(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},r)],{data:i,cachedAt:a}=null!==(t=tt(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.posts.length))return;const o=i.posts.map((e=>tt(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(gw.post),{paging:l}=i;return o.length===i.posts.length?{data:o,cachedAt:a,paging:l}:void 0};class oT extends Av{async getRequest(e,t){const{limit:n}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:s})});return i}}var lT;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(lT||(lT={}));class cT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===lT.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const dT=async e=>{const t=Ye();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.comments.map((e=>gw.comment(e))),cachedAt:s}};dT.locally=e=>{var t;const n=Ye();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>tt(["comment","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map((e=>gw.comment(e))),cachedAt:i.cachedAt}};const uT=e=>{const t=Ye();if(!t.cache)return;const n=Of();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const r=(new Date).toISOString(),s={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:r,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:r,updatedAt:r,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing"};return nt(["comment","get",s.commentId],s,{cachedAt:-5}),Ut("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},hT=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},fT=async e=>{const t=Ye();t.log("story/getStoryByStoryId",e);const n=tt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Xf("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=hT(n.data)}catch(t){throw ie(null==t?void 0:t.code)&&Nf("story",e),t}const s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.stories[0],cachedAt:s}};fT.locally=e=>{const t=Ye();t.log("story/getStorybyStoryId",e);const n=tt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Xf("story",e)}const r=t.cache&&Date.now(),s=tt(["story","get",e]);if(s)return{data:s.data,cachedAt:r}};const pT=async(e,t=!1)=>{var n,r,s;const i=Ye(),a=null===(n=tt(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==a?void 0:a.syncState)){const t=Object.assign(Object.assign({},a),{isDeleted:!0});return it(["comment","get",e]),Ut("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const o=await iS(e);await i.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const l=Object.assign(Object.assign({},o.data),{isDeleted:!0});if(t?Dt((()=>Nf("comment",e))):st(["comment","get",e],{isDeleted:!0}),"story"===o.data.referenceType){const e=await fT(o.data.referenceId);Ut("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(r=tt(["post","get",o.data.referenceId]))||void 0===r?void 0:r.data;if(t){const n=tS();n.queueCommentChangeTask(new Jw(t.postId,e)),!l.parentId&&(null===(s=l.children)||void 0===s?void 0:s.length)>0&&l.children.forEach((e=>{n.queueCommentChangeTask(new Jw(t.postId,e))}))}}return Ut("local.comment.deleted",{comments:[l],commentChildren:[],files:[],users:[],communityUsers:[]}),l},gT=async e=>{const t=Ye();let n;t.log("comment/getComment",e),Xf("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:r}};gT.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=tt(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mT=e=>CS("local.comment.deleted",e),yT=e=>{const t=Ye();return Mt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(st(["comment","get",n.commentId],n),e(Ib(n))):e(n)}))},vT=e=>{const t=Ye();return Mt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(st(["comment","get",n.commentId],n),e(Ib(n))):e(n)}))};class bT extends Av{async getRequest(e,t){var n;const{pageSize:r,limit:s,includeDeleted:i}=e,a=Bf(e,["pageSize","limit","includeDeleted"]),o=null!==(n=null!=r?r:s)&&void 0!==n?n:W,l={type:a.sortBy||e.limit||e.pageSize?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{pageSize:o,limit:o}),{data:d}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},a),{isDeleted:rp(i),options:c})});return d}}var wT;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(wT||(wT={}));class ST extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.comments.map(Je("comment"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Je("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===wT.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ET=e=>CS("local.comment.created",e);class IT extends kv{constructor(e,t){const n=Tv(e),r=["comments","collection",n];super(new bT(e),n,r,t),this.query=e,this.queryStreamController=new ST(this.query,this.cacheKey,this.notifyChange.bind(this),jS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE([{fn:ET,action:wT.OnCommentCreated},{fn:mT,action:wT.OnCommentDeleted},{fn:_S,action:wT.OnCommentCreated},{fn:RS,action:wT.OnCommentUpdated},{fn:OS,action:wT.OnCommentDeleted},{fn:kS,action:wT.OnCommentFlagged},{fn:PS,action:wT.OnCommentUnflagged},{fn:DS,action:wT.OnCommentReactionAdded},{fn:LS,action:wT.OnCommentReactionRemoved},{fn:yT,action:wT.OnCommentReactionAdded},{fn:vT,action:wT.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Vm(t),Ym(t))}return e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["comment","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.comment);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===r.length&&r.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=mt(t)),"firstCreated"===this.query.sortBy)t=t.sort(bt);else t=t.sort(St);return t}}var TT=Object.freeze({__proto__:null,getCommentByIds:dT,createComment:async e=>{const t=Ye();t.log("comment/createComment",e);const n=uT(e),r=null==n?void 0:n.commentId;try{const{data:n}=await t.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:r})),{comments:s}=n;if(0===s.length)throw new Error("Comment not created");const i=t.cache&&Date.now();if(t.cache&&Ff(n,{cachedAt:i}),["post","content"].includes(e.referenceType))tS().queueCommentChangeTask(new zw(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=tt(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=tt(["story","get",t.data]);(null==e?void 0:e.data)&&Ut("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return Ut("local.comment.created",{comments:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:gw.comment(s[0]),cachedAt:i}}catch(e){throw n&&Ut("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ye();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s}),Ut("comment.updated",r);const{comments:i}=r;return{data:gw.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:pT,softDeleteComment:async e=>{Ye().log("comment/softDeleteComment",e);return pT(e)},hardDeleteComment:async e=>{Ye().log("comment/hardDeleteComment",e);return pT(e,!0)},flagComment:async(t,n)=>{const r=Ye();r.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:a}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,i);return r.cache&&Ff(a),Ut("comment.flagged",a),!!a},unflagComment:async e=>{const t=Ye();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Ff(n),Ut("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:_S,onCommentUpdated:RS,onCommentDeleted:OS,onCommentFlagged:kS,onCommentUnflagged:PS,onCommentReactionAdded:DS,onCommentReactionRemoved:LS,getComment:(e,t)=>Nv(e,t,"commentId",gT,[mT,OS,kS,DS,LS,PS,RS,yT,vT]),getComments:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getComments(tmpid: ${i}) > listen`);const a=new IT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getComments(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});const AT=e=>gS("local.post.deleted",e),CT=e=>{const t=Ye();return Mt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(st(["post","get",n.postId],n),e(n)):e(n)}))},_T=e=>{const t=Ye();return Mt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(st(["post","get",n.postId],n),e(n)):e(n)}))},RT=e=>gS("local.post.updated",e),OT=e=>[_S,OS,ET,mT].map((t=>({fn:Pw((n=>((e,t,n)=>t((async t=>{var r;const s=null===(r=tt(n))||void 0===r?void 0:r.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:lT.OnPostUpdated}))),kT=e=>[{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},...OT(e)];class PT extends kv{constructor(e,t){const n=Tv(e),r=["customRankingGlobalFeed","collection",n];super(new oT(e),n,r,t),this.query=e,this.queryStreamController=new cT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class DT extends Av{async getRequest(e,t){const{limit:n,dataTypes:r}=e,s=Bf(e,["limit","dataTypes"]),i=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:i})});return a}}class LT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===lT.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xT extends kv{constructor(e,t){const n=Tv(e),r=["globalFeed","collection",n];super(new DT(e),n,r,t),this.query=e,this.queryStreamController=new LT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class MT extends Av{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:s,includeDeleted:i,matchingOnlyParentPost:a,limit:o=W,untilAt:l}=e,c=Bf(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),d=t?{token:t}:{limit:o},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:d,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:r,isDeleted:rp(i),matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length)})});return u}}class UT extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved||e===lT.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(e===lT.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}if(e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===lT.OnPostCreated||e===lT.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const FT=async e=>{const t=Ye();let n;t.log("post/getPost",e),Xf("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("post",e),t}const r=$f(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:i.find((t=>t.postId===e)),cachedAt:s}};FT.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=tt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class NT extends kv{constructor(e,t){const n=Tv(e),r=["userFeed","collection",n];super(new MT(e),n,r,t),this.query=e,this.queryStreamController=new UT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},{fn:Pw((e=>_S((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[],o=this.applyFilter(a).map(gw.post);if(!this.shouldNotify(o)&&"event"===e)return;const l=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:l,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=at(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Ct(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class BT extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,communityId:s,untilAt:i}=e,a=Bf(e,["limit","includeDeleted","communityId","untilAt"]),o=t?{token:t}:{limit:n},{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},a),{targetId:s,targetType:"community",isDeleted:rp(r),matchingOnlyParentPost:!0,options:o})});return l}}class jT extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(e===lT.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const $T=({cacheKey:e,resolveId:t})=>[_S,OS,ET,mT].map((n=>({fn:Pw((r=>((e,t,n,r)=>t((async t=>{var s;const i=null===(s=tt(n))||void 0===s?void 0:s.data;i&&i.data.includes(r?r(t.referenceId):t.referenceId)&&e(t)})))(r,n,e,t)),"referenceId","post"),action:lT.OnPostUpdated}))),qT=e=>[{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},...$T({cacheKey:e})],KT=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Je("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Pv))&&void 0!==n?n:[]};class GT extends kv{constructor(e,t){const n=Tv(e),r=["communityFeed","collection",n];super(new BT(e),n,r,t),this.query=e,this.queryStreamController=new jT(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(qT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);if(!this.shouldNotify(a)&&"event"===e)return;const o=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:o,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.tags&&(t=t.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=At(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Ct(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(bt);break;case"firstUpdated":t=t.sort(Et);break;case"lastUpdated":t=t.sort(It);break;default:t=t.sort(St)}return t}}class WT extends Ge{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class HT extends Av{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Qm.current()}async getRequest(e,t){var n,r,s,i,a;const o=void 0===t;let l=null;if(o&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,l=await this.cursor.get(),l&&Qm.isExpired(l.expiredAt)&&(await this.cursor.clear(),l=null)),o&&(null==l?void 0:l.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(r=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==r?r:"");return!Number.isNaN(t)&&t!==l.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const c=o&&l?l.cursor:t,d=await this.fetch(c);if(d.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=d.paging)||void 0===s?void 0:s.next)await this.persistCursor(d);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(a=null===(i=d.paging)||void 0===i?void 0:i.expiredAt)&&void 0!==a?a:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return d}async fetch(e){const t={limit:H};e&&(t.token=e);try{const{data:e}=await this.http.get(Z,{params:{options:t}});return e}catch(t){if(t instanceof Ge&&400300===t.code)throw new WT;if(t instanceof Ge&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(Z,{params:{options:{limit:H}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const r=null===(t=e.paging)||void 0===t?void 0:t.next,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!r||!s)return;const i=Date.parse(s);Number.isNaN(i)||await this.cursor.set({cursor:r,expiredAt:i})}}class VT extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.parentPostId&&!r.data.includes(t.parentPostId)||(e!==lT.OnPostDeleted&&e!==lT.OnPostDeclined||(r.data=r.data.filter((e=>e!==t.postId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const YT=["forYouFeed","collection"];class QT extends kv{constructor(e){const t=`for-you-feed-${Ye().userId}`,n={};super(new HT(n),t,YT,e),this.queryStreamController=new VT(n,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(kT(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var zT=Object.freeze({__proto__:null,queryGlobalFeed:aT,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${i}) > listen`);const a=new PT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getGlobalFeed(tmpid: ${i}) > listen`);const a=new xT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getGlobalFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getUserFeed(tmpid: ${i}) > listen`);const a=new NT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getUserFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunityFeed(tmpid: ${i}) > listen`);const a=new GT(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunityFeed(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getForYouFeed(tmpid: ${r}) > listen`);const s=new QT(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getForYouFeed(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},AmityForYouFeedDisabledError:WT});const JT=async e=>{const t=Ye();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{ie(null==t?void 0:t.code)&&Nf("post",e)})),t}const s=$f(r,"communityUsers"),i=t.cache&&Date.now();return t.cache&&Ff(s,{cachedAt:i}),{data:s.posts.map(gw.post),cachedAt:i}};JT.locally=e=>{var t;const n=Ye();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>tt(["post","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),i=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map(gw.post),cachedAt:i.cachedAt}};const XT=async(e,t=!1)=>{var n;const r=Ye(),s=await sS(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await zE(s.data.targetId),t=(null!==(n=et(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Ut("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{Nf("post",e)}),0):st(["post","get",e],{isDeleted:!0}),Ut("local.post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),gw.post(i)};class ZT extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r,matchingOnlyParentPost:s,untilAt:i}=e,a=Bf(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:o}=a,l={type:a.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{limit:n}),{data:d}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},a),{isDeleted:rp(r),matchingOnlyParentPost:null!=s?s:!(null==o?void 0:o.length),options:c})});return d}}class eA extends _v{constructor(e,t,n,r){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=r,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;let i=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=i.filter((t=>!Ct(t.createdAt,this.validatedUntilAt,e)));t.length<i.length&&(this.boundaryReached=!0),i=t}if(n)nt(this.cacheKey,{data:i.map(Je("post"))});else{const e=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===lT.OnPostCreated||e===lT.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Ct(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class tA extends kv{constructor(e,t){const n=Tv(e),r=["posts","collection",n];super(new ZT(e),n,r,t),this.query=e,this.queryStreamController=new eA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE(qT(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Vm(t),Ym(t))}return e}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);if(!this.shouldNotify(a)&&"event"===e)return;const o=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:o,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=at(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=dt(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Ct(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=gt(n)),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class nA extends Av{async getRequest(e,t){const n=Bf(e,["limit"]),{communityId:r,placement:s}=n,i=Bf(n,["communityId","placement"]),a=s?`/api/v1/pinned-posts/communities/${r}/${s}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(a,{params:Object.assign({},i)});return o}}class rA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(fp):[]});Ff(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.pins.map(Je("pin"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Je("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sA extends kv{constructor(e,t){const n=Tv(e),r=["pinnedPosts","collection",n];super(new nA(e),n,r,t),this.query=e,this.queryStreamController=new rA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE($T({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;let a=(null!==(s=i.data.map((e=>tt(["pin","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.pinnedPost);a=this.applyFilter(a),(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>St({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class iA extends Av{async getRequest(e,t){const n=Bf(e,["limit"]),{data:r}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return r}}class aA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(fp)});Ff(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.pins.map(Je("pin"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Je("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===lT.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oA extends kv{constructor(e,t){const n=Tv(e),r=["pinnedPosts","collection",n];super(new iA(e),n,r,t),this.query=e,this.queryStreamController=new aA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:AT,action:lT.OnPostDeleted},{fn:vS,action:lT.OnPostDeleted},...$T({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["pin","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.pinnedPost);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}}class lA extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:a}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:i})});return a}}function cA(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function dA(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class uA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:cA(e)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...cA(e)])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hA extends kv{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=Tv(n),s=["posts","collection",r];super(new lA(n),r,s,t),this.query=n,this.queryStreamController=new uA(this.query,this.cacheKey,this.notifyChange.bind(this),rS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yS,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:Pw((e=>_S((async t=>{const n=tt(this.cacheKey);dA(null==n?void 0:n.data).includes(t.referenceId)||(await sS(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{const n=tt(this.cacheKey);dA(null==n?void 0:n.data).includes(t.referenceId)||(await sS(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=ht(t,this.query.dataTypes)),t}}class fA extends Av{async getRequest(e,t){const{limit:n=W,matchingOnlyParentPost:r,hashtags:s,dataTypes:i,targetType:a="all"}=e,o=Bf(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),l={type:o.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},l),{token:t}):Object.assign(Object.assign({},l),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},o),{hashtags:s,dataTypes:i,targetType:a,matchingOnlyParentPost:null!=r?r:!(null==i?void 0:i.length),options:c})});return d}}class pA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.posts.map(Je("post"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Je("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=tt(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),nt(["post","get",e.postId],e)}e===lT.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==lT.OnPostCreated&&e!==lT.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),nt(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gA extends kv{constructor(e,t){const n=Tv(e),r=["posts","collection",n];super(new fA(e),n,r,t),this.query=e,this.queryStreamController=new pA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:mS,action:lT.OnPostCreated},{fn:yS,action:lT.OnPostUpdated},{fn:RT,action:lT.OnPostUpdated},{fn:vS,action:lT.OnPostDeleted},{fn:SS,action:lT.OnPostFlagged},{fn:ES,action:lT.OnPostUnflagged},{fn:bS,action:lT.OnPostApproved},{fn:wS,action:lT.OnPostDeclined},{fn:IS,action:lT.OnPostReactionAdded},{fn:TS,action:lT.OnPostReactionRemoved},{fn:CT,action:lT.OnPostReactionAdded},{fn:_T,action:lT.OnPostReactionRemoved},{fn:AT,action:lT.OnPostDeleted},{fn:Pw((e=>_S((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated},{fn:Pw((e=>OS((async t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await FT(t.referenceId),e(t))}))),"referenceId","post"),action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=ht(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(bt);else n=n.sort(St);return n}}class mA extends Ov{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class yA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:KT(e.rooms,e.posts)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...KT(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&nt(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const vA=e=>{const t=Ye();return Mt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Ff(t),e(t.rooms[0])}))},bA=e=>{const t=Ye();return Mt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Ff(t),e(t.rooms[0])}))},wA=e=>{const t=Ye();return Mt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Ff(t),e(t.rooms[0])}))},SA=e=>{const t=Ye();return Mt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Ff(t),e(t.rooms[0])}))},EA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},IA=async e=>{const t=Ye();let n;t.log("room/getRoomById",e),Xf("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("room",e),t}const r=t.cache&&Date.now();return t.cache&&Ff(n,{cachedAt:r}),{data:n.rooms[0],cachedAt:r}};IA.locally=e=>{const t=Ye();t.log("room/getRoomById.locally",e),Xf("room",e);const n=t.cache&&Date.now(),r=tt(["room","get",e]);if(r)return{data:r.data,cachedAt:n}};const TA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const r=ib(t);await IA(null===(n=r.invitations)||void 0===n?void 0:n[0].targetId),Ff(r),e(r.invitations[0])}))},AA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},CA=e=>{const t=Ye();return Mt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=ib(t);Ff(n),e(n.invitations)}))},_A=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},RA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:r,users:s}=t;Ff({rooms:r,users:s});const i=t.eventActor.userInternalId;e({room:Nb(r[0]),actorInternalId:i,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===i)))||void 0===n?void 0:n.userId})}))},OA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},kA=e=>{const t=Ye();return Mt(t,"room/onRoomTerminated","room.terminated",(t=>{Ff(t),e(t.rooms[0])}))},PA=e=>{const t=Ye();return Mt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Ff(t),e(t.rooms[0])}))},DA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:r,users:s}=t;Ff({rooms:r,users:s});const i=t.eventActor.userInternalId;e({room:Nb(r[0]),actorInternalId:i,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===i)))||void 0===n?void 0:n.userId})}))},LA=e=>{const t=Ye();return Mt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Ff(t),e(t.rooms[0])}))},xA=e=>{const t=Ye();return Mt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Ff(t),e(t.rooms[0])}))};var MA;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(MA||(MA={}));const UA=e=>t=>e((e=>{t(e.room)}));class FA extends Av{async getRequest(e,t){const{limit:n=W,includeDeleted:r}=e,s=Bf(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0},a=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:o}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:rp(r),options:a})});return o}}class NA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.rooms.map(Je("room"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Je("room"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===MA.OnRoomDeleted&&(r.data=r.data.filter((e=>e!==t._id))),e===MA.OnRoomCreated&&(r.data=[...new Set([t._id,...r.data])]),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class BA extends kv{constructor(e,t){const n=Tv(e),r=["rooms","collection",n];super(new FA(e),n,r,t),this.query=e,this.queryStreamController=new NA(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vA,action:MA.OnRoomStartBroadcasting},{fn:wA,action:MA.OnRoomEndBroadcasting},{fn:SA,action:MA.OnRoomUpdated},{fn:bA,action:MA.OnRoomUpdated},{fn:kA,action:MA.OnRoomUpdated},{fn:UA(_A),action:MA.OnRoomUpdated},{fn:UA(RA),action:MA.OnRoomUpdated},{fn:UA(DA),action:MA.OnRoomUpdated},{fn:xA,action:MA.OnRoomUpdated},{fn:UA(OA),action:MA.OnRoomUpdated},{fn:Pw(TA,"targetId","room"),action:MA.OnRoomUpdated},{fn:PA,action:MA.OnRoomDidUpdate},{fn:LA,action:MA.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["room","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(Nb);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=at(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=at(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(bt);else t=t.sort(St);return t}}var jA=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ye();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Ut("local.room.created",n);const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{rooms:s}=n;return{data:Nb(s[0]),cachedAt:r}},updateRoom:async(e,t)=>{const n=Ye();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:r}=await n.http.put(`/api/v1/rooms/${e}`,t);Ut("local.room.updated",r);const s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{rooms:i}=r;return{data:Nb(i[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ye();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Ut("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ye();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Ut("local.room.stopped",n);const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{rooms:s}=n;return{data:s[0],cachedAt:r}},getBroadcasterData:async e=>{const t=Ye();t.log("room/getBroadcasterData",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Ye();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=Ye();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Ut("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ye();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Ut("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:Fb,WatchSessionStorage:Cb,getWatchSessionStorage:Rb,syncWatchSessions:Mb,updateCohostPermission:async(e,t,n)=>{const r=Ye();r.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await r.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});Ut("local.room.didUpdate",s);const i=r.cache&&Date.now();r.cache&&Ff(s,{cachedAt:i});const{rooms:a}=s;return{data:Nb(a[0]),cachedAt:i}},onRoomStartBroadcasting:vA,onRoomWaitingReconnect:bA,onRoomEndBroadcasting:wA,onRoomRecordedAvailable:SA,onRoomCoHostInvited:EA,onRoomCoHostInviteAccepted:TA,onRoomCoHostInviteRejected:AA,onRoomCoHostInviteCanceled:CA,onRoomParticipantJoined:_A,onRoomParticipantLeft:RA,onRoomParticipantStageLeft:e=>{const t=Ye();return Mt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:r}=t;Ff({rooms:n,users:r}),e({room:Nb(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:OA,onRoomTerminated:kA,onRoomDidUpdate:PA,onRoomCreated:e=>{const t=Ye();return Mt(t,"room/onRoomCreated","local.room.created",(t=>{Ff(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ye();return Mt(t,"room/onRoomUpdated","local.room.updated",(t=>{Ff(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ye();return Mt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Ff(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ye();return Mt(t,"room/onRoomStopped","local.room.stopped",(t=>{Ff(t),e(t.rooms[0])}))},onRoomParticipantRemoved:DA,onRoomLeft:e=>{const t=Ye();return Mt(t,"room/onRoomLeft","local.room.left",(t=>{Ff(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:LA,getRoom:(e,t)=>Nv(e,t,"_id",IA,[wA,vA,bA,kA,SA,UA(_A),UA(RA),UA(DA),xA,UA(OA),Pw(TA,"targetId","room"),PA,LA],{callbackDataSelector:e=>e?gw.room(e):e}),getRooms:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getRooms(tmpid: ${i}) > listen`);const a=new BA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getRooms(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});class $A extends kv{constructor(e){const t={limit:100},n=Tv(t),r=["liveRoomPosts","collection",n];super(new mA(t),n,r,e),this.query=t,this.queryStreamController=new yA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wA,action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){return e}}class qA extends Ov{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:r}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return r}}class KA extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:KT(e.rooms,e.posts)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...KT(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&nt(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class GA extends kv{constructor(e,t){const n=Tv(e),r=["communityLiveRoomPosts","collection",n];super(new qA(e),n,r,t),this.query=e,this.queryStreamController=new KA(this.query,this.cacheKey,this.notifyChange.bind(this),nS),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wA,action:lT.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["post","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){return e}}var WA=Object.freeze({__proto__:null,getPostByIds:JT,createPost:async e=>{const t=Ye();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=nS(a),l=t.cache&&Date.now();t.cache&&Ff(o,{cachedAt:l});const{posts:c}=o;return{data:gw.post(c[0]),cachedAt:l}},editPost:async(e,t)=>{const n=Ye();n.log("user/editPost",t);const{attachments:r}=t,s=r&&r.length>0&&t.attachmentProductTags?r.map((e=>{var n;const r=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return r?Object.assign(Object.assign({},e),{productTags:r}):e})):r,{data:i}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),a=$f(i,"communityUsers"),o=n.cache&&Date.now();n.cache&&Ff(a,{cachedAt:o}),Ut("local.post.updated",a);const{posts:l}=a;return{data:gw.post(l.find((t=>t.postId===e))),cachedAt:o}},deletePost:XT,softDeletePost:async e=>{Ye().log("post/softDeletePost",e);const t=await XT(e,!1);return gw.post(t)},hardDeletePost:async e=>{Ye().log("post/hardDeletePost",e);const t=await XT(e,!0);return gw.post(t)},approvePost:async e=>{const t=Ye();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Ut("post.approved",n),"community"===n.posts[0].targetType&&Ut("community.updated",n);const r=$f(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:gw.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ye();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Ut("community.updated",n),Ut("post.declined",n);const r=$f(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:gw.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const r=Ye();r.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),i={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:a}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,i);return r.cache&&Ff($f(a,"communityUsers")),Ut("post.flagged",a),!!a},unflagPost:async e=>{const t=Ye();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Ff($f(n,"communityUsers")),Ut("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ye();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Ye();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=$f(a,"communityUsers"),l=t.cache&&Date.now();t.cache&&Ff(o,{cachedAt:l});const{posts:c}=o;return{data:gw.post(c[0]),cachedAt:l}},createAudioPost:async e=>{const t=Ye();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:r}=e,s=Bf(e,["attachments","attachmentProductTags"]),i=n&&n.length>0&&r?n.map((e=>{const t=null==r?void 0:r.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:a}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:i}));Ut("post.created",a);const o=nS(a),l=t.cache&&Date.now();return t.cache&&Ff(o,{cachedAt:l}),{data:qb(null==o?void 0:o.posts[0]),cachedAt:l}},createMixedMediaPost:async e=>{var t;const n=Ye();n.log("post/createMixedMediaPost",e);const{attachments:r,attachmentProductTags:s}=e,i=Bf(e,["attachments","attachmentProductTags"]),a=r&&r.length>0&&e.attachmentProductTags?r.map((t=>{var n;const r=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return r?Object.assign(Object.assign({},t),{productTags:r}):t})):r,{data:o}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},i),{attachments:a}));Ut("post.created",o);const l=nS(o),c=n.cache&&Date.now();return n.cache&&Ff(l,{cachedAt:c}),{data:qb(null===(t=null==l?void 0:l.posts)||void 0===t?void 0:t[0]),cachedAt:c}},createRoomPost:async e=>{const t=Ye();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Ut("post.created",n);const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:gw.post(i[0]),cachedAt:s}},createEventPost:async e=>{const t=Ye();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Ut("post.created",n);const r=nS(n),s=t.cache&&Date.now();t.cache&&Ff(r,{cachedAt:s});const{posts:i}=r;return{data:gw.post(i[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ye();n.log("post/pinProduct",e);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=nS(r),i=n.cache&&Date.now();return n.cache&&Ff(r,{cachedAt:i}),Ut("local.post.updated",r),{data:qb(null==s?void 0:s.posts[0]),cachedAt:i}},unpinProduct:async e=>{const t=Ye();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),r=nS(n),s=t.cache&&Date.now();return t.cache&&Ff(n,{cachedAt:s}),Ut("local.post.updated",n),{data:qb(null==r?void 0:r.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ye();n.log("post/updateProductTags",e);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=nS(r),i=n.cache&&Date.now();return n.cache&&Ff(r,{cachedAt:i}),Ut("local.post.updated",r),{data:qb(null==s?void 0:s.posts[0]),cachedAt:i}},onPostCreated:mS,onPostUpdated:yS,onPostDeleted:vS,onPostApproved:bS,onPostDeclined:wS,onPostFlagged:SS,onPostUnflagged:ES,onPostReactionAdded:IS,onPostReactionRemoved:TS,getPost:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.post(e.data):n}))}),"postId",sS,[bS,wS,CT,_T,t=>vS((n=>{var r;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=tt(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),nt(["post","get",e.postId],e),s=e)}t(s)})),SS,e=>IS((t=>{e(t)})),e=>TS((t=>{e(t)})),ES,yS,RT,AT,Pw((t=>_S((async n=>{n.referenceId===e&&(await sS(e),t(n))}))),"referenceId","post"),Pw((t=>OS((async n=>{n.referenceId===e&&(await sS(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getPosts(tmpid: ${i}) > listen`);const a=new tA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getPinnedPosts(tmpid: ${i}) > listen`);const a=new sA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getPinnedPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getGlobalPinnedPosts(tmpid: ${i}) > listen`);const a=new oA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getGlobalPinnedPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`semanticSearchPosts(tmpid: ${i}) > listen`);const a=new hA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`semanticSearchPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchPostsByHashtag(tmpid: ${i}) > listen`);const a=new gA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchPostsByHashtag(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ye();n||console.log(Y);const r=Date.now();t(`getLiveRoomPosts(tmpid: ${r}) > listen`);const s=new $A(e),i=s.startSubscription(),a=s.getCacheKey();return i.push((()=>it(a))),()=>{t(`getLiveRoomPosts(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getCommunityLiveRoomPosts(tmpid: ${i}) > listen`);const a=new GA(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getCommunityLiveRoomPosts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});const HA=async e=>{const t=Ye();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}};HA.locally=e=>{const t=Ye();if(t.log("stream/getStream",e),!t.cache)return;const n=tt(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const VA=e=>{const t=Ye();return Mt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Ff(t),e(t.videoStreamings[0])}))},YA=e=>{const t=Ye();return Mt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Ff(t),e(t.videoStreamings[0])}))},QA=e=>{const t=Ye();return Mt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Ff(t),e(t.videoStreamings[0])}))},zA=e=>{const t=Ye();return Mt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Ff(t),e(t.videoStreamings[0])}))},JA=e=>{const t=Ye();return Mt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Ff(t),e(t.videoStreamings[0])}))},XA=e=>{const t=Ye();return Mt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>HA(e))));const s=null===(n=tt(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},ZA=(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.stream(e.data):n}))}),"streamId",HA,[QA,VA,YA,zA,JA,cE]);ZA.locally=e=>{const t=Ye();if(t.log("stream/getStreamById",e),!t.cache)return;const n=tt(["stream","get",e]);return n?{data:gw.stream(n.data),cachedAt:n.cachedAt}:void 0};class eC extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},r),{options:s})});return Object.assign(Object.assign({},i.results),{paging:i.paging})}}class tC extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Ff(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.videoStreamings.map(Je("stream")),query:this.query});else{const n=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,i=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...i,...e.videoStreamings.map(Je("stream"))])]:[...new Set([...e.videoStreamings.map(Je("stream")),...i])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class nC extends kv{constructor(e,t){const n=Tv(e),r=["streams","collection",n],s=new eC(e);super(s,n,r,t),this.applyFilter=e=>{let t=at(e,"isDeleted",this.query.isDeleted);return t=t.sort("lastCreated"===this.query.sortBy?St:bt),t},this.query=e,this.queryStreamController=new tC(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>tt(["stream","get",e]))).filter(Boolean).map((e=>gw.stream(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:()=>this.loadPage({initial:!1,direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QA,action:"onStreamRecorded"},{fn:VA,action:"onStreamStarted"},{fn:YA,action:"onStreamStopped"},{fn:zA,action:"onStreamFlagged"},{fn:JA,action:"onStreamTerminated"},{fn:cE,action:"onStreamViewerBanned"},{fn:XA,action:"onStreamViewerUnbanned"}])}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var rC=Object.freeze({__proto__:null,createStream:async e=>{const t=Ye();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:gw.stream(s[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{videoStreamings:i}=r;return{data:gw.stream(i.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ye();t.log("stream/deleteStream",e);const n=await HA(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=r,i=Object.assign(Object.assign({},n.data),{isDeleted:!0});return st(["stream","get",e],i),s},disposeStream:async e=>{const t=Ye();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{videoStreamings:i}=r;return{data:gw.stream(i.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:VA,onStreamStopped:YA,onStreamRecorded:QA,onStreamFlagged:zA,onStreamTerminated:JA,onStreamViewerBanned:cE,onStreamViewerUnbanned:XA,getStreamById:ZA,getStreams:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getStreams(tmpid: ${a}) > listen`);const o=new nC(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getStreams(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});const sC=async()=>{const e=Ye();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return nt(["get","presenceSetting"],t),t};class iC{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await iC.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await sC()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const r=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(r/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,r)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=Ye();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const aC=new Map,oC=e=>{let t=aC.get(e);return t||(t=new iC(e),aC.set(e,t)),t};var lC=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,r;const s=Ye();s.log("room/getWatchingUsers",{roomId:e});const{data:i}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),a=null!==(t=null==i?void 0:i.viewers.map((e=>e.userId)))&&void 0!==t?t:[],o=[];for(let e=0;e<a.length;e+=100)o.push(a.slice(e,e+100));const l=await Promise.all(o.map((e=>mw(e)))),c=[];return l.forEach((e=>{e.data&&c.push(...e.data)})),{data:c,cachedAt:null!==(r=null===(n=l[0])||void 0===n?void 0:n.cachedAt)&&void 0!==r?r:Date.now()}},getRoomUserCount:async e=>{const t=Ye();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return nt(["get","watchingCount",e],n),n},startHeartbeat:e=>{oC(e).start()},stopHeartbeat:e=>{oC(e).stop(),(e=>{const t=aC.get(e);t&&(t.destroy(),aC.delete(e))})(e)}});const cC=async e=>{const t=Ye();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{polls:s}=n,i=s.find((t=>t.pollId===e));return{data:Bb(i),cachedAt:r}};cC.locally=e=>{const t=Ye();if(t.log("poll/getPoll",e),!t.cache)return;const n=tt(["poll","get",e]);return n?{data:Bb(n.data),cachedAt:n.cachedAt}:void 0};const dC=e=>{const t=Ye();return Mt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Ff(n),e(n.polls[0])}))},uC=e=>{const t=Ye();return Mt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Ff(n),e(n.polls[0])}))};var hC=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ye();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{polls:s}=n;return{data:Bb(s[0]),cachedAt:r}},closePoll:async e=>{const t=Ye();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r}),Ut("poll.updated",n);const{polls:s}=n,i=s.find((t=>t.pollId===e));return{data:Bb(i),cachedAt:r}},deletePoll:async e=>{const t=Ye();t.log("poll/deletePoll",e);const n=await cC(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=r,i=Object.assign(Object.assign({},n.data),{isDeleted:!0});return st(["poll","get",e],i),Ut("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const n=Ye();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Ff(r,{cachedAt:s});const{polls:i}=r,a=i.find((t=>t.pollId===e));return Ut("poll.updated",r),{data:Bb(a),cachedAt:s}},unvotePoll:async e=>{const t=Ye();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r}),Ut("poll.updated",n)},onPollUpdated:dC,onPollDeleted:uC,getPoll:(e,t)=>Nv(e,t,"pollId",cC,[dC,uC])});function fC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pC={exports:{}};!function(e,t){var n,r,s,i,a;n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return n.alwaysNormalize?(i.path=a.normalizePath(i.path),a.buildURLFromParts(i)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var c={scheme:o.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=o.netLoc,"/"!==i.path[0]))if(i.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+i.path;c.path=a.normalizePath(u)}else c.path=o.path,i.params||(c.params=o.params,i.query||(c.query=o.query));return null===c.path&&(c.path=n.alwaysNormalize?a.normalizePath(i.path):i.path),a.buildURLFromParts(c)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(pC);var gC=pC.exports;function mC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function yC(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mC(Object(n),!0).forEach((function(t){vC(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mC(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function vC(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bC(){return bC=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bC.apply(this,arguments)}const wC=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let SC=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e}({}),EC=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),IC=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({});const TC=function(){},AC={trace:TC,debug:TC,log:TC,warn:TC,info:TC,error:TC};let CC=AC;function _C(e,...t){t.forEach((function(t){CC[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):TC}(t)}))}const RC=CC,OC=/^(\d+)x(\d+)$/,kC=/(.+?)=(".*?"|.*?)(?:,|$)/g;class PC{constructor(e){"string"==typeof e&&(e=PC.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&("X-"===t.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(2*e,2*e+2),16);return n}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=OC.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const n={};for(kC.lastIndex=0;null!==(t=kC.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));n[t[1].trim()]=e}return n}}function DC(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class LC{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const n=t.attr;for(const t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){RC.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=bC(new PC({}),n,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);wC(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(wC(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&wC(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class xC{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var MC="audio",UC="video",FC="audiovideo";class NC{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[MC]:null,[UC]:null,[FC]:null},this.baseurl=e}setByteRange(e,t){const n=e.split("@",2),r=[];1===n.length?r[0]=t?t.byteRangeEndOffset:0:r[0]=parseInt(n[1]),r[1]=parseInt(n[0])+r[0],this._byteRange=r}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=gC.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class BC extends NC{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new xC,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!wC(this.programDateTime))return null;const e=wC(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,n,r,s,i=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,n),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[MC]=null,e[UC]=null,e[FC]=null}}class jC extends NC{constructor(e,t,n,r,s){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new xC,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const i=e.enumeratedString("BYTERANGE");i&&this.setByteRange(i,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class $C{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t,this.advanced=this.endSN>e.endSN||t>0||0===t&&n>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&wC(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function qC(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function KC(e){const t=e.split(":");let n=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),n=qC(s)):n=function(e){const t=GC(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}(s)}}return n}function GC(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var WC={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},HC="org.w3.clearkey",VC="com.apple.streamingkeydelivery",YC="com.microsoft.playready",QC="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function zC(e){switch(e){case VC:return WC.FAIRPLAY;case YC:return WC.PLAYREADY;case QC:return WC.WIDEVINE;case HC:return WC.CLEARKEY}}var JC="edef8ba979d64acea3c827dcd51d21ed";function XC(e){switch(e){case WC.FAIRPLAY:return VC;case WC.PLAYREADY:return YC;case WC.WIDEVINE:return QC;case WC.CLEARKEY:return HC}}function ZC(e){const{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[WC.FAIRPLAY,WC.WIDEVINE,WC.PLAYREADY,WC.CLEARKEY].filter((e=>!!t[e])):[];return!r[WC.WIDEVINE]&&n&&r.push(WC.WIDEVINE),r}const e_="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function t_(e,t,n){return Uint8Array.prototype.slice?e.slice(t,n):new Uint8Array(Array.prototype.slice.call(e,t,n))}const n_=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,r_=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,s_=(e,t)=>{const n=t;let r=0;for(;n_(e,t);){r+=10;r+=i_(e,t+6),r_(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)},i_=(e,t)=>{let n=0;return n=(127&e[t])<<21,n|=(127&e[t+1])<<14,n|=(127&e[t+2])<<7,n|=127&e[t+3],n},a_=(e,t)=>n_(e,t)&&i_(e,t+6)+10<=e.length-t,o_=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,l_=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=i_(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}},c_=e=>{let t=0;const n=[];for(;n_(e,t);){const r=i_(e,t+6);t+=10;const s=t+r;for(;t+8<s;){const r=l_(e.subarray(t)),s=d_(r);s&&n.push(s),t+=r.size+10}r_(e,t)&&(t+=10)}return n},d_=e=>"PRIV"===e.type?u_(e):"W"===e.type[0]?f_(e):h_(e),u_=e=>{if(e.size<2)return;const t=g_(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}},h_=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const n=g_(e.data.subarray(t),!0);t+=n.length+1;const r=g_(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=g_(e.data.subarray(1));return{key:e.type,data:t}},f_=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const n=g_(e.data.subarray(t),!0);t+=n.length+1;const r=g_(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=g_(e.data);return{key:e.type,data:t}},p_=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),n=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}},g_=(e,t=!1)=>{const n=y_();if(n){const r=n.decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let s,i,a,o="",l=0;for(;l<r;){if(s=e[l++],0===s&&t)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],o+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&a)<<0)}}return o};let m_;function y_(){return m_||void 0===self.TextDecoder||(m_=new self.TextDecoder("utf-8")),m_}const v_=function(e){let t="";for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r="0"+r),t+=r}return t},b_=Math.pow(2,32)-1,w_=[].push,S_={video:1,audio:2,id3:3,text:4};function E_(e){return String.fromCharCode.apply(null,e)}function I_(e,t){const n=e[t]<<8|e[t+1];return n<0?65536+n:n}function T_(e,t){const n=A_(e,t);return n<0?4294967296+n:n}function A_(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function C_(e,t,n){e[t]=n>>24,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=255&n}function __(e,t){const n=[];if(!t.length)return n;const r=e.byteLength;for(let s=0;s<r;){const i=T_(e,s),a=i>1?s+i:r;if(E_(e.subarray(s+4,s+8))===t[0])if(1===t.length)n.push(e.subarray(s+8,a));else{const r=__(e.subarray(s+8,a),t.slice(1));r.length&&w_.apply(n,r)}s=a}return n}function R_(e){const t=[],n=e[0];let r=8;const s=T_(e,r);r+=4;r+=0===n?8:16,r+=2;let i=e.length+0;const a=I_(e,r);r+=2;for(let n=0;n<a;n++){let n=r;const a=T_(e,n);n+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return RC.warn("SIDX has hierarchical references (not supported)"),null;const l=T_(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+o-1}}),i+=o,n+=4,r=n}return{earliestPresentationTime:0,timescale:s,version:n,referencesCount:a,references:t}}function O_(e){const t=[],n=__(e,["moov","trak"]);for(let e=0;e<n.length;e++){const r=n[e],s=__(r,["tkhd"])[0];if(s){let e=s[0],n=0===e?12:20;const i=T_(s,n),a=__(r,["mdia","mdhd"])[0];if(a){e=a[0],n=0===e?12:20;const s=T_(a,n),o=__(r,["mdia","hdlr"])[0];if(o){const e=E_(o.subarray(8,12)),n={soun:MC,vide:UC}[e];if(n){const e=__(r,["mdia","minf","stbl","stsd"])[0];let a;e&&(a=E_(e.subarray(12,16))),t[i]={timescale:s,type:n},t[n]={timescale:s,id:i,codec:a}}}}}}return __(e,["moov","mvex","trex"]).forEach((e=>{const n=T_(e,4),r=t[n];r&&(r.default={duration:T_(e,12),flags:T_(e,20)})})),t}function k_(e){const t=__(e,["schm"])[0];if(t){const n=E_(t.subarray(4,8));if("cbcs"===n||"cenc"===n)return __(e,["schi","tenc"])[0]}return RC.error("[eme] missing 'schm' box"),null}function P_(e){const t=T_(e,0);let n=8;1&t&&(n+=4),4&t&&(n+=4);let r=0;const s=T_(e,4);for(let i=0;i<s;i++){if(256&t){r+=T_(e,n),n+=4}512&t&&(n+=4),1024&t&&(n+=4),2048&t&&(n+=4)}return r}function D_(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function L_(e,t){const n=[],r=t.samples,s=t.timescale,i=t.id;let a=!1;return __(r,["moof"]).map((o=>{const l=o.byteOffset-8;__(o,["traf"]).map((o=>{const c=__(o,["tfdt"]).map((e=>{const t=e[0];let n=T_(e,4);return 1===t&&(n*=Math.pow(2,32),n+=T_(e,8)),n/s}))[0];return void 0!==c&&(e=c),__(o,["tfhd"]).map((c=>{const d=T_(c,4),u=16777215&T_(c,0);let h=0;const f=0!=(16&u);let p=0;const g=0!=(32&u);let m=8;d===i&&(0!=(1&u)&&(m+=8),0!=(2&u)&&(m+=4),0!=(8&u)&&(h=T_(c,m),m+=4),f&&(p=T_(c,m),m+=4),g&&(m+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),n=t<0?e:e.substring(0,t);return"hvc1"===n||"hev1"===n||"dvh1"===n||"dvhe"===n}(t.codec)),__(o,["trun"]).map((i=>{const o=i[0],c=16777215&T_(i,0),d=0!=(1&c);let u=0;const f=0!=(4&c),g=0!=(256&c);let m=0;const y=0!=(512&c);let v=0;const b=0!=(1024&c),w=0!=(2048&c);let S=0;const E=T_(i,4);let I=8;d&&(u=T_(i,I),I+=4),f&&(I+=4);let T=u+l;for(let l=0;l<E;l++){if(g?(m=T_(i,I),I+=4):m=h,y?(v=T_(i,I),I+=4):v=p,b&&(I+=4),w&&(S=0===o?T_(i,I):A_(i,I),I+=4),t.type===UC){let t=0;for(;t<v;){const i=T_(r,T);if(T+=4,x_(a,r[T])){M_(r.subarray(T,T+i),a?2:1,e+S/s,n)}T+=i,t+=i+4}}e+=m/s}})))}))}))})),n}function x_(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function M_(e,t,n,r){const s=U_(e);let i=0;i+=t;let a=0,o=0,l=!1,c=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);const e=s.length-i;if(!l&&4===a&&i<s.length){l=!0;if(181===s[i++]){const e=I_(s,i);if(i+=2,49===e){const e=T_(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],o=31&t,l=64&t,c=l?2+3*o:0,d=new Uint8Array(c);if(l){d[0]=t;for(let e=1;e<c;e++)d[e]=s[i++]}r.push({type:e,payloadType:a,pts:n,bytes:d})}}}}}else if(5===a&&o<e){if(l=!0,o>16){const e=[];for(let t=0;t<16;t++){const n=s[i++].toString(16);e.push(1==n.length?"0"+n:n),3!==t&&5!==t&&7!==t&&9!==t||e.push("-")}const t=o-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];r.push({payloadType:a,pts:n,uuid:e.join(""),userData:g_(l),userDataBytes:l})}}else if(o<e)i+=o;else if(o>e)break}}function U_(e){const t=e.byteLength,n=[];let r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(n.push(r+2),r+=2):r++;if(0===n.length)return e;const s=t-n.length,i=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===n[0]&&(a++,n.shift()),i[r]=e[a];return i}function F_(e,t,n){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,s,i;if(t){r=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){const n=t[e];if(16!==n.byteLength)throw new RangeError("Invalid key");s.set(n,16*e)}}else r=0,s=new Uint8Array;r>0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return n&&n.byteLength>0&&new DataView(a.buffer).setUint32(0,n.byteLength,!1),function(e,...t){const n=t.length;let r=8,s=n;for(;s--;)r+=t[s].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=255&r,i.set(e,4),s=0,r=8;s<n;s++)i.set(t[s],r),r+=t[s].byteLength;return i}([112,115,115,104],new Uint8Array([r,0,0,0]),e,i,s,a,n||new Uint8Array)}let N_={};class B_{static clearKeyUriToKeyIdMap(){N_={}}constructor(e,t,n,r=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case VC:case QC:case YC:case HC:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||RC.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}(e);return new B_(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=KC(this.uri);if(t)switch(this.keyFormat){case QC:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case YC:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=F_(e,null,t);const n=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(n)),s=r.substring(r.indexOf("<"),r.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=qC(e).subarray(0,16);!function(e){const t=function(e,t,n){const r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=N_[this.uri];if(!e){const t=Object.keys(N_).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),N_[this.uri]=e}this.keyId=e}return this}}const j_=/\{\$([a-zA-Z0-9-_]+)\}/g;function $_(e){return j_.test(e)}function q_(e,t,n){if(null!==e.variableList||e.hasVariableRefs)for(let r=n.length;r--;){const s=n[r],i=t[s];i&&(t[s]=K_(e,i))}}function K_(e,t){if(null!==e.variableList||e.hasVariableRefs){const n=e.variableList;return t.replace(j_,(t=>{const r=t.substring(2,t.length-1),s=null==n?void 0:n[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function G_(e,t,n){let r,s,i=e.variableList;if(i||(e.variableList=i={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(n).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${n}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in i?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=s||""}function W_(e,t,n){const r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function H_(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const V_={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},Y_=H_();function Q_(e,t){var n;return null!=(n=null==Y_?void 0:Y_.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&n}const z_=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,J_=/#EXT-X-MEDIA:(.*)/g,X_=/^#EXT(?:INF|-X-TARGETDURATION):/m,Z_=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),eR=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class tR{static findGroup(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(r.id===t)return r}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}static resolve(e,t){return gC.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return X_.test(e)}static parseMasterPlaylist(e,t){const n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:$_(e)},r=[];let s;for(z_.lastIndex=0;null!=(s=z_.exec(e));)if(s[1]){var i;const e=new PC(s[1]);q_(n,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=K_(n,s[2]),o={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:tR.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),sR((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=tR.convertAVC1ToAVCOTI(o.videoCodec)),null!=(i=o.unknownCodecs)&&i.length||r.push(o),n.levels.push(o)}else if(s[3]){const e=s[3],r=s[4];switch(e){case"SESSION-DATA":{const e=new PC(r);q_(n,e,["DATA-ID","LANGUAGE","VALUE","URI"]);const t=e["DATA-ID"];t&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[t]=e);break}case"SESSION-KEY":{const e=nR(r,t,n);e.encrypted&&e.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(e)):RC.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const e=new PC(r);q_(n,e,["NAME","VALUE","QUERYPARAM"]),G_(n,e,t)}break;case"CONTENT-STEERING":{const e=new PC(r);q_(n,e,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:tR.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":n.startTimeOffset=rR(r)}}const a=r.length>0&&r.length<n.levels.length;return n.levels=a?r:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,n){let r;const s={},i=n.levels,a={AUDIO:i.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:i.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(J_.lastIndex=0;null!==(r=J_.exec(e));){const e=new PC(r[1]),i=e.TYPE;if(i){const r=a[i],l=s[i]||[];s[i]=l,q_(n,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",instreamId:e["INSTREAM-ID"],name:e.NAME||e.LANGUAGE||"",type:i,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:e.LANGUAGE,url:e.URI?tR.resolve(e.URI,t):""};if(null!=r&&r.length){const e=tR.findGroup(r,c.groupId)||r[0];iR(c,e,"audioCodec"),iR(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,n,r,s,i){const a=new $C(t),o=a.fragments;let l,c,d,u=null,h=0,f=0,p=0,g=0,m=null,y=new BC(r,t),v=-1,b=!1;for(Z_.lastIndex=0,a.m3u8=e,a.hasVariableRefs=$_(e);null!==(l=Z_.exec(e));){b&&(b=!1,y=new BC(r,t),y.start=p,y.sn=h,y.cc=g,y.level=n,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));const e=l[1];if(e){y.duration=parseFloat(e);const t=(" "+l[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(wC(y.duration)){y.start=p,d&&lR(y,d,a),y.sn=h,y.level=n,y.cc=g,y.urlId=s,o.push(y);const e=(" "+l[3]).slice(1);y.relurl=K_(a,e),aR(y,m),m=y,p+=y.duration,h++,f=0,b=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);m?y.setByteRange(e,m):y.setByteRange(e)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(eR),!l){RC.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<l.length&&void 0===l[c];c++);const e=(" "+l[c]).slice(1),s=(" "+l[c+1]).slice(1),p=l[c+2]?(" "+l[c+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(s);break;case"SKIP":{const e=new PC(s);q_(a,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(wC(t)){a.skippedSegments=t;for(let e=t;e--;)o.unshift(null);h+=t}const n=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(a.recentlyRemovedDateranges=n.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||p)&&y.tagList.push(p?[s,p]:[s]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{const e=new PC(s);q_(a,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),q_(a,e,e.clientAttrs);const t=new LC(e,a.dateRanges[e.ID]);t.isValid||a.skippedSegments?a.dateRanges[t.id]=t:RC.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new PC(s);q_(a,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?W_(a,e,i):G_(a,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=nR(s,t,a);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={}),d[e.keyFormat]&&(d=bC({},d)),d[e.keyFormat]=e}else RC.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=rR(s);break;case"MAP":{const e=new PC(s);if(q_(a,e,["BYTERANGE","URI"]),y.duration){const s=new BC(r,t);oR(s,e,n,d),u=s,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else oR(y,e,n,d),u=y,b=!0;break}case"SERVER-CONTROL":{const e=new PC(s);a.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new PC(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const n=f>0?e[e.length-1]:void 0,r=f++,i=new PC(s);q_(a,i,["BYTERANGE","URI"]);const o=new jC(i,y,t,r,n);e.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new PC(s);q_(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new PC(s);q_(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:RC.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(o.pop(),p-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(aR(y,m),y.cc=g,a.fragmentHint=y,d&&lR(y,d,a));const w=o.length,S=o[0],E=o[w-1];if(p+=a.skippedSegments*a.targetduration,p>0&&w&&E){a.averagetargetduration=p/w;const e=E.sn;a.endSN="initSegment"!==e?e:0,a.live||(E.endList=!0),S&&(a.startCC=S.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=g,v>0&&function(e,t){let n=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=n.programDateTime-1e3*t.duration,n=t}}(o,v),a}}function nR(e,t,n){var r,s;const i=new PC(e);q_(n,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=i.METHOD)?r:"",o=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,d=null!=(s=i.KEYFORMAT)?s:"identity";o&&i.IV&&!l&&RC.error(`Invalid IV: ${i.IV}`);const u=o?tR.resolve(o,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new B_(a,u,d,h,l)}function rR(e){const t=new PC(e).decimalFloatingPoint("TIME-OFFSET");return wC(t)?t:null}function sR(e,t){["video","audio","text"].forEach((n=>{const r=e.filter((e=>function(e,t){const n=V_[t];return!!n&&!0===n[e.slice(0,4)]}(e,n)));if(r.length){const s=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${n}Codec`]=s.length>0?s[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}function iR(e,t,n){const r=t[n];r&&(e[n]=r)}function aR(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),wC(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function oR(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function lR(e,t,n){e.levelkeys=t;const{encryptedFragments:r}=n;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}var cR="manifest",dR="level",uR="audioTrack",hR="subtitleTrack",fR="main",pR="audio",gR="subtitle";function mR(e){const{type:t}=e;switch(t){case uR:return pR;case hR:return gR;default:return fR}}function yR(e,t){let n=e.url;return void 0!==n&&0!==n.indexOf("data:")||(n=t.url),n}class vR{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(SC.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(SC.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,n=t.pLoader,r=t.loader,s=new(n||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:cR,url:n,deliveryDirectives:null})}onLevelLoading(e,t){const{id:n,level:r,url:s,deliveryDirectives:i}=t;this.load({id:n,level:r,responseType:"text",type:dR,url:s,deliveryDirectives:i})}onAudioTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:i}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:uR,url:s,deliveryDirectives:i})}onSubtitleTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:i}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:hR,url:s,deliveryDirectives:i})}load(e){var t;const n=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url)return void RC.trace("[playlist-loader]: playlist request ongoing");RC.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===cR?n.manifestLoadPolicy.default:bC({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===dR&&null!==e.level?t=this.hls.levels[e.level].details:e.type===uR&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===hR&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,n=t.targetduration;if(e&&n){const t=1e3*Math.max(3*e,.8*n);r=bC({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},o={onSuccess:(e,t,n,r)=>{const s=this.getInternalLoader(n);this.resetInternalLoader(n.type);const i=e.data;0===i.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),tR.isMediaPlaylist(i)?this.handleTrackOrLevelPlaylist(e,t,n,r||null,s):this.handleMasterPlaylist(e,t,n,r)):this.handleManifestParsingError(e,n,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,n,r){const s=this.hls,i=e.data,a=yR(e,n),o=tR.parseMasterPlaylist(i,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,n,o.playlistParsingError,r,t);const{contentSteering:l,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=tR.parseMasterPlaylistMedia(i,a,o);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(RC.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new PC({}),bitrate:0,url:""}))}s.trigger(SC.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,n,r,s){const i=this.hls,{id:a,level:o,type:l}=n,c=yR(e,n),d=wC(a)?a:0,u=wC(o)?o:d,h=mR(n),f=tR.parseLevelPlaylist(e.data,c,u,h,d,this.variableList);if(l===cR){const e={attrs:new PC({}),bitrate:0,details:f,name:"",url:c};i.trigger(SC.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:c,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,s)}handleManifestParsingError(e,t,n,r,s){this.hls.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.MANIFEST_PARSING_ERROR,fatal:t.type===cR,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,n=!1,r,s){let i=`A network ${n?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===dR?i+=`: ${e.level} id: ${e.id}`:e.type!==uR&&e.type!==hR||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(i);RC.warn(`[playlist-loader]: ${i}`);let o=IC.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case cR:o=n?IC.MANIFEST_LOAD_TIMEOUT:IC.MANIFEST_LOAD_ERROR,l=!0;break;case dR:o=n?IC.LEVEL_LOAD_TIMEOUT:IC.LEVEL_LOAD_ERROR,l=!1;break;case uR:o=n?IC.AUDIO_TRACK_LOAD_TIMEOUT:IC.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case hR:o=n?IC.SUBTITLE_TRACK_LOAD_TIMEOUT:IC.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const d={type:EC.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:s};if(r){const n=(null==t?void 0:t.url)||e.url;d.response=yC({url:n,data:void 0},r)}this.hls.trigger(SC.ERROR,d)}handlePlaylistLoaded(e,t,n,r,s,i){const a=this.hls,{type:o,level:l,id:c,groupId:d,deliveryDirectives:u}=r,h=yR(t,r),f=mR(r),p="number"==typeof r.level&&f===fR?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:e,reason:e.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:n})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const g=e.playlistParsingError;if(g)a.trigger(SC.ERROR,{type:EC.NETWORK_ERROR,details:IC.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:g,reason:g.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:n});else switch(e.live&&i&&(i.getCacheAge&&(e.ageHeader=i.getCacheAge()||0),i.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case cR:case dR:a.trigger(SC.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:n,networkDetails:s,deliveryDirectives:u});break;case uR:a.trigger(SC.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:u});break;case hR:a.trigger(SC.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:u})}}}function bR(e,t){let n;try{n=new Event("addtrack")}catch(e){n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=e,t.dispatchEvent(n)}function wR(e,t){const n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(n){RC.debug(`[texttrack-utils]: ${n}`);try{const n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){RC.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===n&&(e.mode=n)}function SR(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function ER(e,t,n,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,n){const r=[],s=function(e,t){if(t<e[0].startTime)return 0;const n=e.length-1;if(t>e[n].endTime)return-1;let r=0,s=n;for(;r<=s;){const i=Math.floor((s+r)/2);if(t<e[i].startTime)s=i-1;else{if(!(t>e[i].startTime&&r<n))return i;r=i+1}}return e[r].startTime-t<t-e[s].startTime?r:s}(e,t);if(s>-1)for(let i=s,a=e.length;i<a;i++){const s=e[i];if(s.startTime>=t&&s.endTime<=n)r.push(s);else if(s.startTime>n)return r}return r}(e.cues,t,n);for(let t=0;t<s.length;t++)r&&!r(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}var IR="org.id3",TR="com.apple.quicktime.HLS",AR="https://aomedia.org/emsg/ID3";function CR(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const _R=(()=>{const e=CR();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function RR(e,t){return e.getTime()/1e3-t}class OR{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(SR(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const n=e[t];if("metadata"===n.kind&&"id3"===n.label)return bR(n,this.media),n}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:r}}}=this;if(!n&&!r)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const i=CR();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===AR&&!n||!r)continue;const a=c_(s[e].data);if(a){const n=s[e].pts;let r=n+s[e].duration;r>_R&&(r=_R);r-n<=0&&(r=n+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!o_(s)){this.updateId3CueEnds(n,t);const e=new i(n,r,"");e.value=s,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var n;const r=null==(n=this.id3Track)?void 0:n.cues;if(r)for(let n=r.length;n--;){const s=r[n];s.type===t&&s.startTime<e&&s.endTime===_R&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=i;if(s&&(a||o)){let e;e="audio"===r?e=>e.type===IR&&o:"video"===r?e=>e.type===AR&&a:e=>e.type===IR&&o||e.type===AR&&a,ER(s,t,n,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:n,id3Track:r}=this,{dateRanges:s}=t,i=Object.keys(s);if(r){const e=Object.keys(n).filter((e=>!i.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(n[s].cues).forEach((e=>{r.removeCue(n[s].cues[e])})),delete n[s]}}const a=t.fragments[t.fragments.length-1];if(0===i.length||!wC(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=CR();for(let e=0;e<i.length;e++){const t=i[e],r=s[t],a=n[t],u=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1;const f=RR(r.startDate,o);let p=_R;const g=r.endDate;if(g)p=RR(g,o),h=!0;else if(r.endOnNext&&!h){const e=i.reduce(((e,t)=>{const n=s[t];return n.class===r.class&&n.id!==t&&n.startDate>r.startDate&&e.push(n),e}),[]).sort(((e,t)=>e.startDate.getTime()-t.startDate.getTime()))[0];e&&(p=RR(e.startDate,o),h=!0)}const m=Object.keys(r.attr);for(let e=0;e<m.length;e++){const n=m[e];if("ID"===(d=n)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;let s=u[n];if(s)h&&!a.durationKnown&&(s.endTime=p);else{let e=r.attr[n];s=new l(f,p,""),DC(n)&&(c=e,e=Uint8Array.from(c.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),s.value={key:n,data:e},s.type=TR,s.id=t,this.id3Track.addCue(s),u[n]=s}}n[t]={cues:u,dateRange:r,durationKnown:h}}var c,d}}class kR{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:i,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&n||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:i*r);const c=r;return l+Math.min(1*this.stallCount,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,n=this.levelDetails;if(null===e||null===t||null===n)return null;const r=n.edge,s=e-t-this.edgeStalled,i=r-n.totalduration,a=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(i,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(SC.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(SC.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var n;t.details===IC.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(n=this.levelDetails)&&n.live&&RC.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const n=this.computeLatency();if(null===n)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s)return;const i=this.targetLatency;if(null===i)return;const a=n-i,o=a<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&o&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),n=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,n))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const PR=["NONE","TYPE-0","TYPE-1",null];var DR="",LR="YES",xR="v2";class MR{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class UR{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>e)).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return null==(e=this.audioGroupIds)?void 0:e[this.urlId]}get textGroupId(){var e;return null==(e=this.textGroupIds)?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function FR(e,t){const n=t.startPTS;if(wC(n)){let r,s=0;t.sn>e.sn?(s=n-e.start,r=e):(s=e.start-n,r=t),r.duration!==s&&(r.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function NR(e,t,n,r,s,i){r-n<=0&&(RC.warn("Fragment should have a positive duration",t),r=n+t.duration,i=s+t.duration);let a=n,o=r;const l=t.startPTS,c=t.endPTS;if(wC(l)){const e=Math.abs(l-n);wC(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(n,l),n=Math.min(n,l),s=Math.min(s,t.startDTS),o=Math.min(r,c),r=Math.max(r,c),i=Math.max(i,t.endDTS)}const d=n-t.start;0!==t.start&&(t.start=n),t.duration=r-t.start,t.startPTS=n,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=i;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let h;const f=u-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)FR(p[h],p[h-1]);for(h=f;h<p.length-1;h++)FR(p[h],p[h+1]);return e.fragmentHint&&FR(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function BR(e,t){let n=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){n=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,i=0;if(function(e,t,n){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,i=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=i;e++){const s=l[a+e];let i=o[e];r&&!i&&e<r&&(i=t.fragments[e]=s),s&&i&&n(s,i)}}(e,t,((e,r)=>{e.relurl&&(i=e.cc-r.cc),wC(e.startPTS)&&wC(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,r.urlId=e.urlId,e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)})),n){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){RC.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,n){const r=bC({},e);n&&n.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const n=new LC(t[e].attr,r[e]);n.isValid?r[e]=n:RC.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(i){RC.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=i}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,n){if(e&&t){let r=0;for(let s=0,i=e.length;s<=i;s++){const i=e[s],a=t[s+r];i&&a&&i.index===a.index&&i.fragment.sn===a.fragment.sn?n(i,a):r--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?NR(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):jR(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function jR(e,t){const n=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;n<0||n>=r.length||$R(t,r[n].start)}function $R(e,t){if(t){const n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function qR(e,t,n){var r;return null!=e&&e.details?KR(null==(r=e.details)?void 0:r.partList,t,n):null}function KR(e,t,n){if(e)for(let r=e.length;r--;){const s=e[r];if(s.index===n&&s.fragment.sn===t)return s}return null}function GR(e){switch(e.details){case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_TIMEOUT:case IC.LEVEL_LOAD_TIMEOUT:case IC.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function WR(e,t){const n=GR(t);return e.default[(n?"timeout":"error")+"Retry"]}function HR(e,t){const n="linear"===e.backoff?1:Math.pow(2,t);return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function VR(e){return yC(yC({},e),{errorRetry:null,timeoutRetry:null})}function YR(e,t,n,r){return!!e&&t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(r)||!!n)}const QR=function(e,t){let n=0,r=e.length-1,s=null,i=null;for(;n<=r;){s=(n+r)/2|0,i=e[s];const a=t(i);if(a>0)n=s+1;else{if(!(a<0))return i;r=s-1}}return null};function zR(e,t,n=0,r=0){let s=null;if(e?s=t[e.sn-t[0].sn+1]||null:0===n&&0===t[0].start&&(s=t[0]),s&&0===JR(n,r,s))return s;const i=QR(t,JR.bind(null,n,r));return!i||i===e&&s?s:i}function JR(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function XR(e,t,n){const r=1e3*Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return(n.endProgramDateTime||0)-r>e}var ZR=0,eO=2,tO=5,nO=0,rO=1,sO=2;function iO(e,t,n){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const r=e.details;if(t.details===IC.FRAG_GAP&&r&&t.frag){const e=t.frag.start,n=zR(null,r.fragments,e);if(n&&!n.gap)return!0}if(n&&e.errors.length<n.errors.length){const n=e.errors[e.errors.length-1];if(r&&n.frag&&t.frag&&Math.abs(n.frag.start-t.frag.start)>3*r.targetduration)return!0}return!1}class aO{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=RC.log.bind(RC,`${t}:`),this.warn=RC.warn.bind(RC,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const n=null==t?void 0:t.renditionReports;if(n){let r=-1;for(let s=0;s<n.length;s++){const i=n[s];let a;try{a=new self.URL(i.URI,t.url).href}catch(e){RC.warn(`Could not construct new URL for Rendition Report: ${e}`),a=i.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=n[r],s=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let i=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);i>=0&&e>t.partTarget&&(i+=1)}return new MR(s,i>=0?i:void 0,DR)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,n){const{details:r,stats:s}=t,i=self.performance.now(),a=s.loading.first?Math.max(0,i-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=n&&n.live){if(r.reloaded(n),n&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:"MISSED"}`),n&&r.fragments.length>0&&BR(n,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,i=r.endSN,c=r.lastPartIndex,d=s===i,u=e?0:c;-1!==c?(o=d?i+1:s,l=d?u:c+1):o=i+1;const h=r.age,f=h+r.ageHeader;let p=Math.min(f-r.partTarget,1.5*r.targetduration);if(p>0){if(n&&p>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${p} with playlist age: ${r.age}`),p=0;else{const e=Math.floor(p/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(p%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${p} skip sn ${e} to part ${l}`)}r.tuneInGoal=p}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!d)return void this.loadPlaylist(a)}else r.canBlockReload&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));const c=this.hls.mainForwardBufferInfo,d=c?c.end-c.len:0,u=function(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&n*s>t){const e=1e3*r[r.length-1].duration;e<n&&(n=e)}}else n/=2;return Math.round(n)}(r,1e3*(r.edge-d));r.updated&&i>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=u);let h=this.requestScheduled-i;h=Math.max(0,h),this.log(`reload live playlist ${e} in ${Math.round(h)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),h)}else this.clearTimer()}getDeliveryDirectives(e,t,n,r){let s=function(e,t){const{canSkipUntil:n,canSkipDateRanges:r,endSN:s}=e;return n&&(void 0!==t?t-s:0)<n?r?xR:LR:DR}(e,n);return null!=t&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,s=DR),new MR(n,r,s)}checkRetry(e){const t=e.details,n=GR(e),r=e.errorAction,{action:s,retryCount:i=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===tO||!r.resolved&&s===eO);if(o){var l;if(this.requestScheduled=-1,i>=a.maxNumRetry)return!1;if(n&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=HR(a,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}let oO;class lO extends aO{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const n=[],r={};let s;t.levels.forEach((e=>{var t;const i=e.attrs;-1!==(null==(t=e.audioCodec)?void 0:t.indexOf("mp4a.40.34"))&&(oO||(oO=/chrome|firefox/i.test(navigator.userAgent)),oO&&(e.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:d,SUBTITLES:u}=i,h=`${`${c||"."}-`}${e.bitrate}-${d}-${l}-${o}`;s=r[h],s?s.addFallback(e):(s=new UR(e),r[h]=s,n.push(s)),cO(s,"audio",a),cO(s,"text",u)})),this.filterAndSortMediaOptions(n,t)}filterAndSortMediaOptions(e,t){let n=[],r=[],s=!1,i=!1,a=!1,o=e.filter((({audioCodec:e,videoCodec:t,width:n,height:r,unknownCodecs:o})=>(s||(s=!(!n||!r)),i||(i=!!t),a||(a=!!e),!(null!=o&&o.length)&&(!e||Q_(e,"audio"))&&(!t||Q_(t,"video")))));if((s||i)&&a&&(o=o.filter((({videoCodec:e,width:t,height:n})=>!!e||!(!t||!n)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||Q_(e.audioCodec,"audio"))),dO(n)),t.subtitles&&(r=t.subtitles,dO(r));const l=o.slice(0);o.sort(((e,t)=>e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"]?(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1:e.bitrate!==t.bitrate?e.bitrate-t.bitrate:e.attrs["FRAME-RATE"]!==t.attrs["FRAME-RATE"]?e.attrs.decimalFloatingPoint("FRAME-RATE")-t.attrs.decimalFloatingPoint("FRAME-RATE"):e.attrs.SCORE!==t.attrs.SCORE?e.attrs.decimalFloatingPoint("SCORE")-t.attrs.decimalFloatingPoint("SCORE"):s&&e.height!==t.height?e.height-t.height:0));let c=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){c=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${c.bitrate}`);break}const d=a&&!i,u={levels:o,audioTracks:n,subtitleTracks:r,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:i,altAudio:!d&&n.some((e=>!!e.url))};this.hls.trigger(SC.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const n=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}const n=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,i=t[e],a=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,n===e&&i.details&&r&&s===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${n}${s?" with Pathway "+s:""}`);const o=bC({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete o._attrs,delete o._urlId,this.hls.trigger(SC.LEVEL_SWITCHING,o);const l=i.details;if(!l||l.live){const e=this.switchParams(i.uri,null==r?void 0:r.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===dR&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===fR){const e=this._levels[t.level];void 0!==e&&(e.loadError=0)}}onLevelLoaded(e,t){var n;const{level:r,details:s}=t,i=this._levels[r];var a;if(!i)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===i.fragmentError&&(i.loadError=0),this.playlistLoaded(r,t,i.details)):null!=(n=t.deliveryDirectives)&&n.skip&&(s.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const n=this.currentLevel;if(!n)return;const r=this.hls.audioTracks[t.id].groupId;if(n.audioGroupIds&&n.audioGroupId!==r){let e=-1;for(let t=0;t<n.audioGroupIds.length;t++)if(n.audioGroupIds[t]===r){e=t;break}-1!==e&&e!==n.urlId&&(n.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){const r=n.urlId;let s=n.uri;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const i=n.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${i?" Pathway "+i:""} URI ${r+1}/${n.url.length} ${s}`),this.clearTimer(),this.hls.trigger(SC.LEVEL_LOADING,{url:s,level:t,id:r,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){const n=(e,n)=>n!==t,r=this._levels.filter(((r,s)=>s!==e||(r.url.length>1&&void 0!==t?(r.url=r.url.filter(n),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(n)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(n)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1))));this.hls.trigger(SC.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){t.forEach(((e,t)=>{const{details:n}=e;null!=n&&n.fragments&&n.fragments.forEach((e=>{e.level=t}))})),this._levels=t}}function cO(e,t,n){n&&("audio"===t?(e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds[e.url.length-1]=n):"text"===t&&(e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds[e.url.length-1]=n))}function dO(e){const t={};e.forEach((e=>{const n=e.groupId||"";e.id=t[n]=t[n]||0,t[n]++}))}var uO="NOT_LOADED",hO="APPENDING",fO="PARTIAL",pO="OK";class gO{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.BUFFER_APPENDED,this.onBufferAppended,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.BUFFER_APPENDED,this.onBufferAppended,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const n=this.activePartLists[t];if(n)for(let t=n.length;t--;){const r=n[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:n}=this,r=Object.keys(n);for(let s=r.length;s--;){const i=n[r[s]];if((null==i?void 0:i.body.type)===t&&i.buffered){const t=i.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const i=this.fragments[r];if(!i)return;if(s>=i.body.sn)return;if(!i.buffered&&!i.loaded)return void(i.body.type===n&&this.removeFragment(i.body));const a=i.range[e];a&&a.time.some((e=>{const n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(i.body),n}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:n,part:r}=e;if(!t||"initSegment"===n.sn)return;const s=yO(n),i=this.fragments[s];if(!i||i.buffered&&n.gap)return;const a=!n.relurl;Object.keys(t).forEach((e=>{const s=n.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;i.range[e]=this.getBufferedTimes(n,r,l,o)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),mO(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}removeParts(e,t){const n=this.activePartLists[t];n&&(this.activePartLists[t]=n.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const n=yO(e);let r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,n,r){const s={time:[],partial:n},i=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||i;for(let e=0;e<r.length;e++){const t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(l>=t&&o<=n){s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(i<n&&a>t)s.partial=!0,s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(a,r.end(e))});else if(a<=t)break}return s}getPartialFragment(e){let t,n,r,s=null,i=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const c=o[l];c&&mO(c)&&(n=c.body.start-a,r=c.body.end+a,e>=n&&e<=r&&(t=Math.min(e-n,r-e),i<=t&&(s=c.body,i=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||mO(t))}getState(e){const t=yO(e),n=this.fragments[t];return n?n.buffered?mO(n)?fO:pO:hO:uO}isTimeBuffered(e,t,n){let r,s;for(let i=0;i<n.length;i++){if(r=n.start(i)-this.bufferPadding,s=n.end(i)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:n,part:r}=t;if("initSegment"===n.sn||n.bitrateTest)return;const s=r?null:t,i=yO(n);this.fragments[i]={body:n,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:n,part:r,timeRanges:s}=t;if("initSegment"===n.sn)return;const i=n.type;if(r){let e=this.activePartLists[i];e||(this.activePartLists[i]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,i,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=yO(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,n,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;const o=a.body;o.type!==n||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=yO(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const t=e.sn;this.activePartLists[e.type]=n.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function mO(e){var t,n,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(n=e.range.audio)?void 0:n.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function yO(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const vO=Math.pow(2,17);class bO{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const n=e.url;if(!n)return Promise.reject(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(n?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,i=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(SO(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new i(r),c=wO(e),d=VR(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:vO};e.stats=l.stats,l.load(c,u,{onSuccess:(t,n,r,s)=>{this.resetLoader(e,l);let i=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(i.slice(0,16)),i=i.slice(16)),a({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,r,s,i)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:yC({url:n,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:i}))},onAbort:(t,n,r)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(n,r,s,i)=>{t&&t({frag:e,part:null,payload:s,networkDetails:i})}})}))}loadPart(e,t,n){this.abort();const r=this.config,s=r.fLoader,i=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(SO(e,t));const l=this.loader=e.loader=s?new s(r):new i(r),c=wO(e,t),d=VR(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:vO};t.stats=l.stats,l.load(c,u,{onSuccess:(r,s,i,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:r.data,networkDetails:o};n(c),a(c)},onError:(n,r,s,i)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:yC({url:c.url,data:void 0},n),error:new Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:s,stats:i}))},onAbort:(n,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:n}))},onTimeout:(n,r,s)=>{this.resetLoader(e,l),o(new EO({type:EC.NETWORK_ERROR,details:IC.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:n}))}})}))}updateStatsFromPart(e,t){const n=e.stats,r=t.stats,s=r.total;if(n.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),i=Math.min(Math.round(n.loaded/s),r),a=(r-i)*Math.round(n.loaded/i);n.total=n.loaded+a}else n.total=Math.max(n.loaded,n.total);const i=n.loading,a=r.loading;i.start?i.first+=a.first-a.start:(i.start=a.start,i.first=a.first),i.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function wO(e,t=null){const n=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},s=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(wC(s)&&wC(i)){var a;let t=s,n=i;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=i-s;e%16&&(n=i+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=n}return r}function SO(e,t){const n=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:EC.MEDIA_ERROR,details:IC.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new EO(r)}class EO extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class IO{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const n=this.keyUriToKeyInfo[t].loader;if(n){if(e&&e!==n.context.frag.type)return;n.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=IC.KEY_LOAD_ERROR,n,r,s){return new EO({type:EC.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:n,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:n,cc:r}=e;for(let e=0;e<t.length;e++){const s=t[e];if(r<=s.cc&&("initSegment"===n||"initSegment"===s.sn||n<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var n,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const n=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,n))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let a=this.keyUriToKeyInfo[i];if(null!=(n=a)&&n.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[i]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,IC.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(n);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,n)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(n)}loadKeyHTTP(e,t){const n=this.config,r=new(0,n.loader)(n);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,i)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=n.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{const{frag:a,keyInfo:o,url:l}=n;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(a,IC.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,n,r,s)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,yC({url:a.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,IC.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,c)}))}resetLoader(e){const{frag:t,keyInfo:n,url:r}=e,s=n.loader;t.keyLoader===s&&(t.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}const TO={length:0,start:()=>0,end:()=>0};class AO{static isBuffered(e,t){try{if(e){const n=AO.getBuffered(e);for(let e=0;e<n.length;e++)if(t>=n.start(e)&&t<=n.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,n){try{if(e){const r=AO.getBuffered(e),s=[];let i;for(i=0;i<r.length;i++)s.push({start:r.start(i),end:r.end(i)});return this.bufferedInfo(s,t,n)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.sort((function(e,t){const n=e.start-t.start;return n||t.end-e.end}));let r=[];if(n)for(let t=0;t<e.length;t++){const s=r.length;if(s){const i=r[s-1].end;e[t].start-i<n?e[t].end>i&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,i=0,a=t,o=t;for(let e=0;e<r.length;e++){const l=r[e].start,c=r[e].end;if(t+n>=l&&t<c)a=l,o=c,i=o-t;else if(t+n<l){s=l;break}}return{len:i,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return RC.log("failed to get media.buffered",e),TO}}}class CO{constructor(e,t,n,r=0,s=-1,i=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=s,this.partial=i}}function _O(e,t){let n=null;for(let r=0,s=e.length;r<s;r++){const s=e[r];if(s&&s.cc===t){n=s;break}}return n}function RO(e,t){if(e){const n=e.start+t;e.start=e.startPTS=n,e.endPTS=n+e.duration}}function OO(e,t){const n=t.fragments;for(let t=0,r=n.length;t<r;t++)RO(n[t],e);t.fragmentHint&&RO(t.fragmentHint,e),t.alignedSliding=!0}function kO(e,t,n){t&&(!function(e,t,n){if(function(e,t,n){return!(!t.details||!(n.endCC>n.startCC||e&&e.cc<n.startCC))}(e,n,t)){const e=function(e,t,n=0){const r=e.fragments,s=t.fragments;if(!s.length||!r.length)return void RC.log("No fragments to align");const i=_O(r,s[0].cc);if(i&&(!i||i.startPTS))return i;RC.log("No frag in previous level to align on")}(n.details,t);e&&wC(e.start)&&(RC.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),OO(e.start,t))}}(e,n,t),!n.alignedSliding&&t.details&&function(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;const n=t.fragments[0].programDateTime,r=e.fragments[0].programDateTime,s=(r-n)/1e3+t.fragments[0].start;s&&wC(s)&&(RC.log(`Adjusting PTS using programDateTime delta ${r-n}ms, sliding:${s.toFixed(3)} ${e.url} `),OO(s,e))}(n,t.details),n.alignedSliding||!t.details||n.skippedSegments||jR(t.details,n))}function PO(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const n=e.fragments,r=t.fragments;if(!n.length||!r.length)return;const s=r[Math.round(r.length/2)-1],i=_O(n,s.cc)||n[Math.round(n.length/2)-1],a=s.programDateTime,o=i.programDateTime;if(null===a||null===o)return;OO((o-a)/1e3-(i.start-s.start),e)}class DO{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class LO{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class xO{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(4*e);return n}initTable(){const e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],s=n[1],i=n[2],a=n[3],o=this.invSubMix,l=o[0],c=o[1],d=o[2],u=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let n=p^p<<1^p<<2^p<<3^p<<4;n=n>>>8^255&n^99,e[f]=n,t[n]=f;const o=h[f],g=h[o],m=h[g];let y=257*h[n]^16843008*n;r[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,i[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*g^257*o^16843008*f,l[n]=y<<24|y>>>8,c[n]=y<<16|y>>>16,d[n]=y<<8|y>>>24,u[n]=y,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const i=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),d=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(a=0;a<i;a++)a<s?y=l[a]=t[a]:(v=y,a%s==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=u[a/s|0]<<24):s>6&&a%s==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-s]^v)>>>0);for(o=0;o<i;o++)a=i-o,v=3&o?l[a]:l[a-4],c[o]=o<4||a<=4?v:f[d[v>>>24]]^p[d[v>>>16&255]]^g[d[v>>>8&255]]^m[d[255&v]],c[o]=c[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,n){const r=this.keySize+6,s=this.invKeySchedule,i=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],c=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(n);let h=u[0],f=u[1],p=u[2],g=u[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,S,E,I,T,A,C,_,R,O,k,P;const D=this.networkToHostOrderSwap;for(;t<m.length;){for(C=D(m[t]),_=D(m[t+1]),R=D(m[t+2]),O=D(m[t+3]),E=C^s[0],I=O^s[1],T=R^s[2],A=_^s[3],k=4,P=1;P<r;P++)v=o[E>>>24]^l[I>>16&255]^c[T>>8&255]^d[255&A]^s[k],b=o[I>>>24]^l[T>>16&255]^c[A>>8&255]^d[255&E]^s[k+1],w=o[T>>>24]^l[A>>16&255]^c[E>>8&255]^d[255&I]^s[k+2],S=o[A>>>24]^l[E>>16&255]^c[I>>8&255]^d[255&T]^s[k+3],E=v,I=b,T=w,A=S,k+=4;v=i[E>>>24]<<24^i[I>>16&255]<<16^i[T>>8&255]<<8^i[255&A]^s[k],b=i[I>>>24]<<24^i[T>>16&255]<<16^i[A>>8&255]<<8^i[255&E]^s[k+1],w=i[T>>>24]<<24^i[A>>16&255]<<16^i[E>>8&255]<<8^i[255&I]^s[k+2],S=i[A>>>24]<<24^i[E>>16&255]<<16^i[I>>8&255]<<8^i[255&T]^s[k+3],y[t]=D(v^h),y[t+1]=D(S^f),y[t+2]=D(w^p),y[t+3]=D(b^g),h=C,f=_,p=R,g=O,t+=4}return y.buffer}}class MO{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?t_(e,0,t-n):e}(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,n){return this.useSoftware?new Promise(((r,s)=>{this.softwareDecrypt(new Uint8Array(e),t,n);const i=this.flush();i?r(i.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,n)}softwareDecrypt(e,t,n){const{currentIV:r,currentResult:s,remainderData:i}=this;this.logOnce("JS AES decrypt"),i&&(e=D_(i,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;r&&(n=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new xO),o.expandKey(t);const l=s;return this.currentResult=o.decrypt(a.buffer,0,n),this.currentIV=t_(a,-16).buffer,l||null}webCryptoDecrypt(e,t,n){const r=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new LO(r,t)),this.fastAesKey.expandKey().then((t=>{if(!r)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new DO(r,new Uint8Array(n)).decrypt(e.buffer,t)})).catch((r=>(RC.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,n))))}onWebCryptoError(e,t,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const n=e.length-e.length%16;return n!==e.length&&(t=t_(e,0,n),this.remainderData=t_(e,n)),t}logOnce(e){this.logEnabled&&(RC.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const UO=function(e){let t="";const n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},FO="STOPPED",NO="IDLE",BO="KEY_LOADING",jO="FRAG_LOADING",$O="FRAG_LOADING_WAITING_RETRY",qO="WAITING_TRACK",KO="PARSING",GO="PARSED",WO="ENDED",HO="ERROR",VO="WAITING_INIT_PTS",YO="WAITING_LEVEL";class QO extends class{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}{constructor(e,t,n,r,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=FO,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=r,this.log=RC.log.bind(RC,`${r}:`),this.warn=RC.warn.bind(RC,`${r}:`),this.hls=e,this.fragmentLoader=new bO(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new MO(e.config),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=FO}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const n=t.partList;if(null!=n&&n.length){const e=n[n.length-1];return AO.isBuffered(this.media,e.start+e.duration/2)}const r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levels[this.levelLastLoaded])?void 0:e.details}onMediaAttached(e,t){const n=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),n.addEventListener("seeking",this.onvseeking),n.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===FO&&this.startLoad(r.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:n,mediaBuffer:r,state:s}=this,i=n?n.currentTime:0,a=AO.bufferInfo(r||n,i,e.maxBufferHole);if(this.log(`media seeking to ${wC(i)?i.toFixed(3):i}, state: ${s}`),this.state===WO)this.resetLoadingState();else if(t){const n=e.maxFragLookUpTolerance,r=t.start-n,s=t.start+t.duration+n;if(!a.len||s<a.start||r>a.end){const e=i>s;(i<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}n&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,this.playlistType,!0),this.lastCurrentTime=i),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=i),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=FO,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const n=this.state;this.fragContextChanged(e)?(n===jO||!this.fragCurrent&&n===KO)&&(this.fragmentTracker.removeFragment(e),this.state=NO):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(SC.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==FO&&this.state!==HO&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:n}=this;if(n.getState(e)===hO){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&n.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===fO&&n.removeFragment(e))}flushMainBuffer(e,t,n=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:n};this.hls.trigger(SC.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:n}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){const i=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw n.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return n.trigger(SC.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:i,tdecrypt:s}}),t.payload=r,t}))}return t})).then((n=>{const{fragCurrent:r,hls:s,levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=NO,t.fragmentError=0,e.data=new Uint8Array(n.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),n.frag===r&&s.trigger(SC.FRAG_BUFFERED,{stats:a,frag:r,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==FO&&this.state!==HO&&(this.warn(t),this.resetFragmentLoading(e))}))}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var n,r,s,i;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===fR?"level":"track"} ${e.level} (frag:[${(null!=(n=e.startPTS)?n:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?UO(AO.getBuffered(a)):"(detached)"})`),this.state=NO,a&&(!this.loadedmetadata&&e.type==fR&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(i=this.fragPrevious)?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:n,part:r,partsLoaded:s}=e,i=!s||0===s.length||s.some((e=>!e)),a=new CO(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!i);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var s;const i=null==t?void 0:t.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&i.encryptedFragments.length&&this.keyLoader.loadClear(e,i.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${i.startSN}-${i.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=BO,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(SC.KEY_LOADED,e),this.state===BO&&(this.state=NO),e})),this.hls.trigger(SC.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=i.partList;if(s&&r){n>e.end&&i.fragmentHint&&(e=i.fragmentHint);const o=this.getNextPart(s,e,n);if(o>-1){const l=s[o];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=jO,c=a?a.then((n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(SC.FRAG_LOADING,{frag:e,part:l,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(s,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${i?"of ["+i.startSN+"-"+i.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),wC(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=jO;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?r:void 0),a]).then((([e])=>(!o&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(SC.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,n,r){return new Promise(((s,i)=>{var a;const o=[],l=null==(a=n.details)?void 0:a.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const i=r.part;this.hls.trigger(SC.FRAG_LOADED,r);const a=qR(n,e.sn,t.index+1)||KR(l,e.sn,t.index+1);if(!a)return s({frag:e,part:i,partsLoaded:o});c(a)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===IC.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(SC.ERROR,t)}else this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==KO)return void(this.fragCurrent||this.state===FO||this.state===HO||(this.state=NO));const{frag:n,part:r,level:s}=t,i=self.performance.now();n.stats.parsing.end=i,r&&(r.stats.parsing.end=i),this.updateLevelTiming(n,r,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:n}=this,{level:r,sn:s,part:i}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=i>-1?qR(a,s,i):null,l=o?o.fragment:function(e,t,n){if(null==e||!e.details)return null;const r=e.details;let s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t?s:t<r.startSN&&n&&n.sn===t?n:null)}(a,s,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,n,r,s){var i;if(!e||this.state!==KO)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=D_(a,o)),null==(i=l)||!i.length)return;const c={type:e.type,frag:t,part:n,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(SC.BUFFER_APPENDING,c),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!AO.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const n=t.currentTime,r=AO.bufferInfo(t,n,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-i,r.end-i),n+i);e.start-a>i&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const n=this.getLoadPosition();return wC(n)?this.getFwdBufferInfoAtPos(e,n,t):null}getFwdBufferInfoAtPos(e,t,n){const{config:{maxBufferHole:r}}=this,s=AO.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const i=this.fragmentTracker.getBufferedFrag(t,n);if(i&&s.nextStart<i.end)return AO.bufferInfo(e,t,Math.max(s.nextStart,r))}return s}getMaxBufferLength(e){const{config:t}=this;let n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,n=e||t.maxBufferLength;return t.maxMaxBufferLength>=n&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=fR){const n=this.fragmentTracker.getAppendedFrag(e,fR);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const n=t.fragments,r=n.length;if(!r)return null;const{config:s}=this,i=n[0].start;let a;if(t.live){const i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(t,n),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=i&&(a=n[0]);if(!a){const n=s.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,n,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const n=this.fragmentTracker.getState(e);return(n===pO||n===fO&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,s){const i=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,i&&e&&!e.gap&&n.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r);if(null!==t&&n.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,n){let r=-1,s=!1,i=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(i=i&&!o.independent,r>-1&&n<o.start)break;const l=o.loaded;l?r=-1:(s||o.independent||i)&&o.fragment===t&&(r=a),s=l}return r}loadedEndOfParts(e,t){const n=e[e.length-1];return n&&t>n.start&&n.loaded}getInitialLiveFragment(e,t){const n=this.fragPrevious;let r=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),r=function(e,t,n){if(null===t||!Array.isArray(e)||!e.length||!wC(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;n=n||0;for(let r=0;r<e.length;++r){const s=e[r];if(XR(t,n,s))return s}return null}(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=n.sn+1;if(s>=e.startSN&&s<=e.endSN){const i=t[s-e.startSN];n.cc===i.cc&&(r=i,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return QR(e,(e=>e.cc<t?1:e.cc>t?-1:0))}(t,n.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){const{config:r}=this;let{fragPrevious:s}=this,{fragments:i,endSN:a}=n;const{fragmentHint:o}=n,l=r.maxFragLookUpTolerance,c=n.partList,d=!!(r.lowLatencyMode&&null!=c&&c.length&&o);let u;if(d&&o&&!this.bitrateTest&&(i=i.concat(o),a=o.sn),e<t){u=zR(s,i,e,e>t-l?0:l)}else u=i[i.length-1];if(u){const e=u.sn-n.startSN,t=this.fragmentTracker.getState(u);if((t===pO||t===fO&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||c[0].fragment.sn>u.sn)){if(s&&u.level===s.level){const t=i[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==pO?t:null}}}return u}synchronizeToLiveEdge(e){const{config:t,media:n}=this;if(!n)return;const r=this.hls.liveSyncPosition,s=n.currentTime,i=e.fragments[0].start,a=e.edge,o=s>=i-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&n.duration>r&&(s<r||!o)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&n.readyState<4||s<a-i)&&(this.loadedmetadata||(this.nextLoadPosition=r),n.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),n.currentTime=r))}}alignPlaylists(e,t){const{levels:n,levelLastLoaded:r,fragPrevious:s}=this,i=null!==r?n[r]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const o=e.fragments[0].start,l=!t,c=e.alignedSliding&&wC(o);if(l||!c&&!o){kO(s,i,e);const n=e.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${a}`),n}return o}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let n=this.startPosition;if(n<t&&(n=-1),-1===n||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,s=r?this.startTimeOffset:e.startTimeOffset;null!==s&&wC(s)?(n=t+s,s<0&&(n+=e.totalduration),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Start time offset ${s} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${n}`),this.startPosition=n):e.live?n=this.hls.liveSyncPosition||t:this.startPosition=n=0,this.lastCurrentTime=n}this.nextLoadPosition=n}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===$O)||(this.state=NO)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;var r;if(this.fragContextChanged(n))return void this.warn(`Frag load error must match current frag to retry ${n.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===IC.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const i=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=i||{};if(i&&a===tO&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:n.level);const r=HR(l,o);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),i.resolved=!0,this.retryDate=self.performance.now()+r,this.state=$O}else l&&i?(this.resetFragmentErrors(e),o<l.maxNumRetry?s||(i.resolved=!0):RC.warn(`${t.details} reached or exceeded max retry (${o})`)):(null==i?void 0:i.action)===eO?this.state=YO:this.state=HO;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===KO||this.state===GO){const t=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,t),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===pR&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==FO&&(this.state=NO)}afterBufferFlushed(e,t,n){if(!e)return;const r=AO.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===WO&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=NO}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(t=this.levelLastLoaded)?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){var s;const i=n.details;if(!i)return void this.warn("level.details undefined");if(Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=r?0:NR(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(SC.LEVEL_PTS_UPDATED,{details:i,level:n,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1))n.fragmentError=0;else if(null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===n.fragmentError&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=GO,this.hls.trigger(SC.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){var t,n,r;"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(t=null!=(n=this.levelLastLoaded)?n:null==(r=this.fragCurrent)?void 0:r.level)?t:0),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function zO(){return self.SourceBuffer||self.WebKitSourceBuffer}function JO(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class XO{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&(e=D_(this.cachedData,e),this.cachedData=null);let n,r=s_(e,0),s=r?r.length:0;const i=this._audioTrack,a=this._id3Track,o=r?(e=>{const t=c_(e);for(let e=0;e<t.length;e++){const n=t[e];if(o_(n))return p_(n)}})(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&wC(o))&&(this.basePTS=ZO(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:IR,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(i,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,n=s):s=l}else a_(e,s)?(r=s_(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:IR,duration:Number.POSITIVE_INFINITY}),s+=r.length,n=s):s++;if(s===l&&n!==l){const t=t_(e,n);this.cachedData?this.cachedData=D_(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:JO(),id3Track:a,textTrack:JO()}}demuxSampleAes(e,t,n){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:JO(),id3Track:this._id3Track,textTrack:JO()}}destroy(){}}const ZO=(e,t,n)=>{if(wC(e))return 90*e;return 9e4*t+(n?9e4*n.baseTime/n.timescale:0)};function ek(e,t){return 255===e[t]&&240==(246&e[t+1])}function tk(e,t){return 1&e[t+1]?7:9}function nk(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function rk(e,t){return t+1<e.length&&ek(e,t)}function sk(e,t){if(rk(e,t)){const n=tk(e,t);if(t+n>=e.length)return!1;const r=nk(e,t);if(r<=n)return!1;const s=t+r;return s===e.length||rk(e,s)}return!1}function ik(e,t,n,r,s){if(!e.samplerate){const i=function(e,t,n,r){let s,i,a,o;const l=navigator.userAgent.toLowerCase(),c=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[n+2])>>>6);const u=(60&t[n+2])>>>2;if(!(u>d.length-1))return a=(1&t[n+2])<<2,a|=(192&t[n+3])>>>6,RC.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),i=u-3):(s=2,o=new Array(2),i=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),i=u):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?i=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),i=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&i)>>1,o[2]=(1&i)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${u}`})}(t,n,r,s);if(!i)return;e.config=i.config,e.samplerate=i.samplerate,e.channelCount=i.channelCount,e.codec=i.codec,e.manifestCodec=i.manifestCodec,RC.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function ak(e){return 9216e4/e}function ok(e,t,n,r,s){const i=r+s*ak(e.samplerate),a=function(e,t){const n=tk(e,t);if(t+n<=e.length){const r=nk(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}(t,n);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,c=Math.max(0,n+l-t.length);c?(o=new Uint8Array(l-s),o.set(t.subarray(n+s,t.length),0)):o=t.subarray(n+s,n+l);const d={unit:o,pts:i};return c||e.samples.push(d),{sample:d,length:l,missing:c}}const l=t.length-n;o=new Uint8Array(l),o.set(t.subarray(n,t.length),0);return{sample:{unit:o,pts:i},length:l,missing:-1}}const lk=/\/emsg[-/]ID3/i;let ck=null;const dk=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],uk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hk=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fk=[0,1,1,4];function pk(e,t,n,r,s){if(n+24>t.length)return;const i=gk(t,n);if(i&&n+i.frameLength<=t.length){const a=r+s*(9e4*i.samplesPerFrame/i.sampleRate),o={unit:t.subarray(n,n+i.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(o),{sample:o,length:i.frameLength,missing:0}}}function gk(e,t){const n=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,i=e[t+2]>>2&3;if(1!==n&&0!==s&&15!==s&&3!==i){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*dk[14*(3===n?3-r:3===r?3:4)+s-1],c=uk[3*(3===n?0:2===n?1:2)+i],d=3===o?1:2,u=hk[n][r],h=fk[r],f=8*u*h,p=Math.floor(u*l/c+a)*h;if(null===ck){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ck=e?parseInt(e[1]):0}return!!ck&&ck<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:d,frameLength:p,samplesPerFrame:f}}}function mk(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function yk(e,t){return t+1<e.length&&mk(e,t)}function vk(e,t){if(t+1<e.length&&mk(e,t)){const n=4,r=gk(e,t);let s=n;null!=r&&r.frameLength&&(s=r.frameLength);const i=t+s;return i===e.length||yk(e,i)}return!1}class bk{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(n,n+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const n=this.word>>>32-t;if(e>32&&RC.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,n=8,r=8;for(let s=0;s<e;s++)0!==r&&(t=this.readEG(),r=(n+t+256)%256),n=0===r?n:r}readSPS(){let e,t,n,r=0,s=0,i=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();const g=o();if(l(5),u(3),o(),f(),100===g||110===g||122===g||244===g||44===g||83===g||86===g||118===g||128===g){const e=c();if(3===e&&u(1),f(),f(),u(1),d())for(t=3!==e?8:12,n=0;n<t;n++)d()&&p(n<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(u(1),h(),h(),e=c(),n=0;n<e;n++)h();f(),u(1);const y=c(),v=c(),b=l(1);0===b&&u(1),u(1),d()&&(r=c(),s=c(),i=c(),a=c());let w=[1,1];if(d()&&d()){switch(o()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+a),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class wk{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new MO(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,n){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),i=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(i).then((s=>{const i=new Uint8Array(s);r.set(i,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}))}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length)return void n();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,n=new Int8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){const n=new Uint8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,s){const i=U_(s.data),a=this.getAvcEncryptedData(i);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(i,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}))}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,n=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(n>=s.length);n++){const i=s[n];if(!(i.data.length<=48||1!==i.type&&5!==i.type||(this.decryptAvcSample(e,t,n,r,i),this.decrypter.isSync())))return}}}}const Sk=188;class Ek{constructor(e,t,n){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=n}static probe(e){const t=Ek.syncOffset(e);return t>0&&RC.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let n=Math.min(940,e.length-Sk)+1,r=0;for(;r<n;){let s=!1,i=-1,a=0;for(let o=r;o<t;o+=Sk){if(71!==e[o]){if(a)return-1;break}if(a++,-1===i&&(i=o,0!==i&&(n=Math.min(i+18612,e.length-Sk)+1)),s||(s=0===Tk(e,o)),s&&a>1&&(0===i&&a>2||o+Sk>n))return i}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:S_[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,n,r){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Ek.createTrack("video"),this._audioTrack=Ek.createTrack("audio",r),this._id3Track=Ek.createTrack("id3"),this._txtTrack=Ek.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=n,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,n=!1,r=!1){let s;n||(this.sampleAes=null);const i=this._avcTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let c=i.pid,d=i.pesData,u=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=D_(this.remainderData,e)).length,this.remainderData=null),v<Sk&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};const b=Math.max(0,Ek.syncOffset(e));v-=(v-b)%Sk,v<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let w=0;for(let t=b;t<v;t+=Sk)if(71===e[t]){const r=!!(64&e[t+1]),v=Tk(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+Sk)continue}else w=t+4;switch(v){case c:r&&(d&&(s=_k(d))&&this.parseAVCPES(i,l,s,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(w,t+Sk)),d.size+=t+Sk-w);break;case u:if(r){if(f&&(s=_k(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+Sk)),f.size+=t+Sk-w);break;case h:r&&(p&&(s=_k(p))&&this.parseID3PES(o,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+Sk)),p.size+=t+Sk-w);break;case 0:r&&(w+=e[w]+1),y=this._pmtId=Ak(e,w);break;case y:{r&&(w+=e[w]+1);const s=Ck(e,w,this.typeSupported,n);c=s.avc,c>0&&(i.pid=c),u=s.audio,u>0&&(a.pid=u,a.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(o.pid=h),null===g||m||(RC.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=v}}else w++;if(w>0){const e=new Error(`Found ${w} TS packet/s that do not start with 0x47`);this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=d,a.pesData=f,o.pesData=p;const S={audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:n,id3Track:r,textTrack:s}=e,i=n.pesData,a=t.pesData,o=r.pesData;let l;if(i&&(l=_k(i))?(this.parseAVCPES(n,s,l,!0),n.pesData=null):n.pesData=i,a&&(l=_k(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&RC.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=_k(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,n){const r=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new wk(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((n=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{n(e)})):n(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{n(e)}))}))}destroy(){this._duration=0}parseAVCPES(e,t,n,r){const s=this.parseAVCNALu(e,n.data);let i,a=this.avcSample,o=!1;n.data=null,a&&s.length&&!e.audFound&&(Rk(a,e),a=this.avcSample=Ik(!1,n.pts,n.dts,"")),s.forEach((r=>{var s;switch(r.type){case 1:{let t=!1;i=!0;const s=r.data;if(o&&s.length>4){const e=new bk(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=a)&&l.frame&&!a.key&&(Rk(a,e),a=this.avcSample=null);a||(a=this.avcSample=Ik(!0,n.pts,n.dts,"")),a.frame=!0,a.key=t;break}case 5:i=!0,null!=(s=a)&&s.frame&&!a.key&&(Rk(a,e),a=this.avcSample=null),a||(a=this.avcSample=Ik(!0,n.pts,n.dts,"")),a.key=!0,a.frame=!0;break;case 6:i=!0,M_(r.data,1,n.pts,t.samples);break;case 7:if(i=!0,o=!0,!e.sps){const t=r.data,n=new bk(t).readSPS();e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t],e.duration=this._duration;const s=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break;case 8:i=!0,e.pps||(e.pps=[r.data]);break;case 9:i=!1,e.audFound=!0,a&&Rk(a,e),a=this.avcSample=Ik(!1,n.pts,n.dts,"");break;case 12:i=!0;break;default:i=!1,a&&(a.debug+="unknown NAL "+r.type+" ")}if(a&&i){a.units.push(r)}})),r&&a&&(Rk(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let n,r=this.avcSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;n=e[e.length-1]}return n}parseAVCNALu(e,t){const n=t.byteLength;let r=e.naluState||0;const s=r,i=[];let a,o,l,c=0,d=-1,u=0;for(-1===r&&(d=0,u=31&t[0],r=0,c=1);c<n;)if(a=t[c++],r)if(1!==r)if(a)if(1===a){if(d>=0){const e={data:t.subarray(d,c-r-1),type:u};i.push(e)}else{const n=this.getLastNalUnit(e.samples);if(n&&(s&&c<=4-s&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-s)),o=c-r-1,o>0)){const e=new Uint8Array(n.data.byteLength+o);e.set(n.data,0),e.set(t.subarray(0,o),n.data.byteLength),n.data=e,n.state=0}}c<n?(l=31&t[c],d=c,u=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(d>=0&&r>=0){const e={data:t.subarray(d,n),type:u,state:r};i.push(e)}if(0===i.length){const n=this.getLastNalUnit(e.samples);if(n){const e=new Uint8Array(n.data.byteLength+t.byteLength);e.set(n.data,0),e.set(t,n.data.byteLength),n.data=e}}return e.naluState=r,i}parseAACPES(e,t){let n=0;const r=this.aacOverFlow;let s,i,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+o.byteLength);e.set(r.sample.unit,0),e.set(o,s),o=e}else{const i=s-t;r.sample.unit.set(o.subarray(0,t),i),e.samples.push(r.sample),n=r.missing}}for(s=n,i=o.length;s<i-1&&!rk(o,s);s++);if(s!==n){let e;const t=s<i-1;e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES";const n=new Error(e);if(RC.warn(`parsing error: ${e}`),this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:n,reason:e}),!t)return}if(ik(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!r)return void RC.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=ak(e.samplerate);a=r.sample.pts+t}}let l,c=0;for(;s<i;){if(l=ok(e,o,s,a,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!rk(o,s);s++);}}parseMPEGPES(e,t){const n=t.data,r=n.length;let s=0,i=0;const a=t.pts;if(void 0!==a)for(;i<r;)if(yk(n,i)){const t=pk(e,n,i,a,s);if(!t)break;i+=t.length,s++}else i++;else RC.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void RC.warn("[tsdemuxer]: ID3 PES unknown PTS");const n=bC({},t,{type:this._avcTrack?AR:IR,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function Ik(e,t,n,r){return{key:e,frame:!1,pts:t,dts:n,units:[],debug:r,length:0}}function Tk(e,t){return((31&e[t+1])<<8)+e[t+2]}function Ak(e,t){return(31&e[t+10])<<8|e[t+11]}function Ck(e,t,n,r){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},i=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<i;){const i=Tk(e,t);switch(e[t]){case 207:if(!r){RC.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===s.audio&&(s.audio=i);break;case 21:-1===s.id3&&(s.id3=i);break;case 219:if(!r){RC.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===s.avc&&(s.avc=i);break;case 3:case 4:!0!==n.mpeg&&!0!==n.mp3?RC.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:RC.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function _k(e){let t,n,r,s,i,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;){const e=new Uint8Array(o[0].length+o[1].length);e.set(o[0]),e.set(o[1],o[0].length),o[0]=e,o.splice(1,1)}t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(n=(t[4]<<8)+t[5],n&&n>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(i=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-i>54e5&&(RC.warn(`${Math.round((s-i)/9e4)}s delta between PTS and DTS, align them`),s=i)):i=s),r=t[8];let c=r+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,n=o.length;e<n;e++){t=o[e];let n=t.byteLength;if(c){if(c>n){c-=n;continue}t=t.subarray(c),n-=c,c=0}d.set(t,a),a+=n}return n&&(n-=r+3),{data:d,pts:s,dts:i,len:n}}return null}function Rk(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const n=t.samples,r=n.length;if(!r)return void t.dropped++;{const t=n[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&RC.log(e.pts+"/"+e.dts+":"+e.debug)}class Ok{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const kk=Math.pow(2,32)-1;class Pk{static init(){let e;for(e in Pk.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Pk.types)Pk.types.hasOwnProperty(e)&&(Pk.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Pk.HDLR_TYPES={video:t,audio:n};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Pk.STTS=Pk.STSC=Pk.STCO=s,Pk.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Pk.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Pk.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Pk.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Pk.FTYP=Pk.box(Pk.types.ftyp,i,o,i,a),Pk.DINF=Pk.box(Pk.types.dinf,Pk.box(Pk.types.dref,r))}static box(e,...t){let n=8,r=t.length;const s=r;for(;r--;)n+=t[r].byteLength;const i=new Uint8Array(n);for(i[0]=n>>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=255&n,i.set(e,4),r=0,n=8;r<s;r++)i.set(t[r],n),n+=t[r].byteLength;return i}static hdlr(e){return Pk.box(Pk.types.hdlr,Pk.HDLR_TYPES[e])}static mdat(e){return Pk.box(Pk.types.mdat,e)}static mdhd(e,t){t*=e;const n=Math.floor(t/(kk+1)),r=Math.floor(t%(kk+1));return Pk.box(Pk.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Pk.box(Pk.types.mdia,Pk.mdhd(e.timescale,e.duration),Pk.hdlr(e.type),Pk.minf(e))}static mfhd(e){return Pk.box(Pk.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Pk.box(Pk.types.minf,Pk.box(Pk.types.smhd,Pk.SMHD),Pk.DINF,Pk.stbl(e)):Pk.box(Pk.types.minf,Pk.box(Pk.types.vmhd,Pk.VMHD),Pk.DINF,Pk.stbl(e))}static moof(e,t,n){return Pk.box(Pk.types.moof,Pk.mfhd(e),Pk.traf(n,t))}static moov(e){let t=e.length;const n=[];for(;t--;)n[t]=Pk.trak(e[t]);return Pk.box.apply(null,[Pk.types.moov,Pk.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(Pk.mvex(e)))}static mvex(e){let t=e.length;const n=[];for(;t--;)n[t]=Pk.trex(e[t]);return Pk.box.apply(null,[Pk.types.mvex,...n])}static mvhd(e,t){t*=e;const n=Math.floor(t/(kk+1)),r=Math.floor(t%(kk+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Pk.box(Pk.types.mvhd,s)}static sdtp(e){const t=e.samples||[],n=new Uint8Array(4+t.length);let r,s;for(r=0;r<t.length;r++)s=t[r].flags,n[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Pk.box(Pk.types.sdtp,n)}static stbl(e){return Pk.box(Pk.types.stbl,Pk.stsd(e),Pk.box(Pk.types.stts,Pk.STTS),Pk.box(Pk.types.stsc,Pk.STSC),Pk.box(Pk.types.stsz,Pk.STSZ),Pk.box(Pk.types.stco,Pk.STCO))}static avc1(e){let t,n,r,s=[],i=[];for(t=0;t<e.sps.length;t++)n=e.sps[t],r=n.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(n));for(t=0;t<e.pps.length;t++)n=e.pps[t],r=n.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(n));const a=Pk.box(Pk.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),o=e.width,l=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return Pk.box(Pk.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Pk.box(Pk.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Pk.box(Pk.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return Pk.box(Pk.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]),Pk.box(Pk.types.esds,Pk.esds(e)))}static mp3(e){const t=e.samplerate;return Pk.box(Pk.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?Pk.box(Pk.types.stsd,Pk.STSD,Pk.mp3(e)):Pk.box(Pk.types.stsd,Pk.STSD,Pk.mp4a(e)):Pk.box(Pk.types.stsd,Pk.STSD,Pk.avc1(e))}static tkhd(e){const t=e.id,n=e.duration*e.timescale,r=e.width,s=e.height,i=Math.floor(n/(kk+1)),a=Math.floor(n%(kk+1));return Pk.box(Pk.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const n=Pk.sdtp(e),r=e.id,s=Math.floor(t/(kk+1)),i=Math.floor(t%(kk+1));return Pk.box(Pk.types.traf,Pk.box(Pk.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Pk.box(Pk.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i])),Pk.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Pk.box(Pk.types.trak,Pk.tkhd(e),Pk.mdia(e))}static trex(e){const t=e.id;return Pk.box(Pk.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const n=e.samples||[],r=n.length,s=12+16*r,i=new Uint8Array(s);let a,o,l,c,d,u;for(t+=8+s,i.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<r;a++)o=n[a],l=o.duration,c=o.size,d=o.flags,u=o.cts,i.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Pk.box(Pk.types.trun,i)}static initSegment(e){Pk.types||Pk.init();const t=Pk.moov(e),n=new Uint8Array(Pk.FTYP.byteLength+t.byteLength);return n.set(Pk.FTYP),n.set(t,Pk.FTYP.byteLength),n}}Pk.types=void 0,Pk.HDLR_TYPES=void 0,Pk.STTS=void 0,Pk.STSC=void 0,Pk.STCO=void 0,Pk.STSZ=void 0,Pk.VMHD=void 0,Pk.SMHD=void 0,Pk.STSD=void 0,Pk.FTYP=void 0,Pk.DINF=void 0;function Dk(e,t,n=1,r=!1){const s=e*t*n;return r?Math.round(s):s}function Lk(e,t=!1){return Dk(e,1e3,1/9e4,t)}let xk,Mk=null,Uk=null;class Fk{constructor(e,t,n,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,null===Mk){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mk=e?parseInt(e[1]):0}if(null===Uk){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Uk=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){RC.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){RC.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){RC.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const n=e.reduce(((e,n)=>{const r=n.pts-e;return r<-4294967296?(t=!0,Nk(e,n.pts)):r>0?e:n.pts}),e[0].pts);return t&&RC.debug("PTS rollover detected"),n}remux(e,t,n,r,s,i,a,o){let l,c,d,u,h,f,p=s,g=s;const m=e.pid>-1,y=t.pid>-1,v=t.samples.length,b=e.samples.length>0,w=a&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||a){this.ISGenerated||(d=this.generateIS(e,t,s,i));const n=this.isVideoContiguous;let r,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){RC.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,r=g}else-1===a&&(RC.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const n=this.getVideoStartPts(t.samples),r=(Nk(e.samples[0].pts,n)-n)/t.inputTimeScale;p+=Math.max(0,r),g+=Math.max(0,-r)}if(b){if(e.samplerate||(RC.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||o===pR?g:void 0),w){const r=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(RC.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,i)),l=this.remuxVideo(t,g,n,r)}}else w&&(l=this.remuxVideo(t,g,n,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(h=Bk(n,s,this._initPTS,this._initDTS)),r.samples.length&&(u=jk(r,s,this._initPTS))),{audio:c,video:l,initSegment:d,independent:f,text:u,id3:h}}generateIS(e,t,n,r){const s=e.samples,i=t.samples,a=this.typeSupported,o={},l=this._initPTS;let c,d,u,h=!l||r,f="audio/mp4";if(h&&(c=d=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Pk.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(u=e.inputTimeScale,l&&u===l.timescale?h=!1:c=d=s[0].pts-Math.round(u*n))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Pk.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(u=t.inputTimeScale,l&&u===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(u*n);d=Math.min(d,Nk(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(o).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:u},this._initDTS={baseTime:d,timescale:u}):c=u=void 0,{tracks:o,initPTS:c,timescale:u}}remuxVideo(e,t,n,r){const s=e.inputTimeScale,i=e.samples,a=[],o=i.length,l=this._initPTS;let c,d,u=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!n||null===u){u=t*s-(i[0].pts-Nk(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<o;e++){const t=i[e];t.pts=Nk(t.pts-y,u),t.dts=Nk(t.dts-y,u),t.dts<i[e>0?e-1:e].dts&&(m=!0)}m&&i.sort((function(e,t){const n=e.dts-t.dts,r=e.pts-t.pts;return n||r})),c=i[0].dts,d=i[i.length-1].dts;const v=d-c,b=v?Math.round(v/(o-1)):f||e.inputTimeScale/30;if(n){const e=c-u,t=e>b,n=e<-1;if((t||n)&&(t?RC.warn(`AVC: ${Lk(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):RC.warn(`AVC: ${Lk(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!n||u>=i[0].pts)){c=u;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,RC.log(`Video: First PTS/DTS adjusted: ${Lk(t,!0)}/${Lk(c,!0)}, delta: ${Lk(e,!0)} ms`)}}c=Math.max(0,c);let w=0,S=0;for(let e=0;e<o;e++){const t=i[e],n=t.units,r=n.length;let s=0;for(let e=0;e<r;e++)s+=n[e].data.length;S+=s,w+=r,t.length=s,t.dts=Math.max(t.dts,c),p=Math.min(t.pts,p),g=Math.max(t.pts,g)}d=i[o-1].dts;const E=S+4*w+8;let I;try{I=new Uint8Array(E)}catch(e){return void this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MUX_ERROR,details:IC.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating video mdat ${E}`})}const T=new DataView(I.buffer);T.setUint32(0,E),I.set(Pk.types.mdat,4);let A=!1,C=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=i[e],n=t.units;let l,c=0;for(let e=0,t=n.length;e<t;e++){const t=n[e],r=t.data,s=t.data.byteLength;T.setUint32(h,s),h+=4,I.set(r,h),h+=s,c+=4+s}if(e<o-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const n=this.config,a=e>0?t.dts-i[e-1].dts:b;if(l=e>0?t.pts-i[e-1].pts:b,n.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(n.maxBufferHole*s),i=(r?p+r*s:this.nextAudioPts)-t.pts;i>e?(f=i-a,f<0?f=a:A=!0,RC.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(t.pts-t.dts);C=Math.min(C,f),R=Math.max(R,f),_=Math.min(_,l),O=Math.max(O,l),a.push(new $k(t.key,f,c,d))}if(a.length)if(Mk){if(Mk<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Uk&&O-_<R-C&&b/R<.025&&0===a[0].cts){RC.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,n=a.length;t<n;t++){const r=e+a[t].duration,s=e+a[t].cts;if(t<n-1){const e=r+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=r}}f=A||!f?b:f,this.nextAvcDts=u=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const k={data1:Pk.moof(e.sequenceNumber++,c,bC({},e,{samples:a})),data2:I,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,k}remuxAudio(e,t,n,r,s){const i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),o="aac"===e.segmentCodec?1024:1152,l=o*a,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==s;let f=e.samples,p=d?0:8,g=this.nextAudioPts||-1;const m=t*i,y=c.baseTime*i/c.timescale;if(this.isAudioContiguous=n=n||f.length&&g>0&&(r&&Math.abs(m-g)<9e3||Math.abs(Nk(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=Nk(e.pts-y,m)})),!n||g<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;g=0===s?0:r&&!h?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let n=0,r=g;n<f.length;n++){const s=f[n],a=s.pts,o=a-r,c=Math.abs(1e3*o/i);if(o<=-t*l&&h)0===n&&(RC.warn(`Audio frame @ ${(a/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/i)} ms.`),this.nextAudioPts=g=r=a);else if(o>=t*l&&c<1e4&&h){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===n&&(this.nextAudioPts=g=r),RC.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/i).toFixed(3)}s due to ${Math.round(1e3*o/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(r,0);let i=Ok.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(RC.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),i=s.unit.subarray()),f.splice(n,0,{unit:i,pts:t}),r+=l,n++}}s.pts=r,r+=l}}let v,b=null,w=null,S=0,E=f.length;for(;E--;)S+=f[E].unit.byteLength;for(let t=0,r=f.length;t<r;t++){const r=f[t],s=r.unit;let i=r.pts;if(null!==w){u[t-1].duration=Math.round((i-w)/a)}else{if(n&&"aac"===e.segmentCodec&&(i=g),b=i,!(S>0))return;S+=p;try{v=new Uint8Array(S)}catch(e){return void this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MUX_ERROR,details:IC.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(v.buffer).setUint32(0,S),v.set(Pk.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,u.push(new $k(!0,o,l,0)),w=i}const I=u.length;if(!I)return;const T=u[u.length-1];this.nextAudioPts=g=w+a*T.duration;const A=d?new Uint8Array(0):Pk.moof(e.sequenceNumber++,b/a,bC({},e,{samples:u}));e.samples=[];const C=b/i,_=g/i,R={data1:A,data2:v,startPTS:C,endPTS:_,startDTS:C,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,R}remuxEmptyAudio(e,t,n,r){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,c=(null!==a?a:r.startDTS*s)+l,d=r.endDTS*s+l,u=1024*i,h=Math.ceil((d-c)/u),f=Ok.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(RC.warn("[mp4-remuxer]: remux empty Audio"),!f)return void RC.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const p=[];for(let e=0;e<h;e++){const t=c+e*u;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,n,!1)}}function Nk(e,t){let n;if(null===t)return e;for(n=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=n;return e}function Bk(e,t,n,r){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let a=0;a<s;a++){const s=e.samples[a];s.pts=Nk(s.pts-n.baseTime*i/n.timescale,t*i)/i,s.dts=Nk(s.dts-r.baseTime*i/r.timescale,t*i)/i}const a=e.samples;return e.samples=[],{samples:a}}function jk(e,t,n){const r=e.samples.length;if(!r)return;const s=e.inputTimeScale;for(let i=0;i<r;i++){const r=e.samples[i];r.pts=Nk(r.pts-n.baseTime*s/n.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const i=e.samples;return e.samples=[],{samples:i}}class $k{constructor(e,t,n,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=n,this.cts=r,this.flags=new qk(e)}}class qk{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}function Kk(e,t){const n=null==e?void 0:e.codec;return n&&n.length>4?n:"hvc1"===n||"hev1"===n?"hvc1.1.6.L120.90":"av01"===n?"av01.0.04M.08":"avc1"===n||t===UC?"avc1.42e01e":"mp4a.40.5"}try{xk=self.performance.now.bind(self.performance)}catch(e){RC.debug("Unable to use Performance API on this environment"),xk="undefined"!=typeof self&&self.Date.now}const Gk=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,n,r){const s=this.videoTrack=JO("video",1),i=this.audioTrack=JO("audio",1),a=this.txtTrack=JO("text",1);if(this.id3Track=JO("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=O_(e);if(o.video){const{id:e,timescale:t,codec:n}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=n}if(o.audio){const{id:e,timescale:t,codec:n}=o.audio;i.id=e,i.timescale=t,i.codec=n}a.id=S_.text,s.sampleDuration=0,s.duration=i.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return __(e=e.length>16384?e.subarray(0,16384):e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let n=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=D_(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},n=__(e,["moof"]);if(!n)return t;if(n.length<2)return t.remainder=e,t;const r=n[n.length-1];return t.valid=t_(e,0,r.byteOffset-8),t.remainder=t_(e,r.byteOffset-8),t}(n);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=n;const i=this.extractID3Track(r,t);return s.samples=L_(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:i,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return n.samples=L_(e,t),{videoTrack:t,audioTrack:JO(),id3Track:r,textTrack:JO()}}extractID3Track(e,t){const n=this.id3Track;if(e.samples.length){const r=__(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let n="",r="",s=0,i=0,a=0,o=0,l=0,c=0;if(0===t){for(;"\0"!==E_(e.subarray(c,c+1));)n+=E_(e.subarray(c,c+1)),c+=1;for(n+=E_(e.subarray(c,c+1)),c+=1;"\0"!==E_(e.subarray(c,c+1));)r+=E_(e.subarray(c,c+1)),c+=1;r+=E_(e.subarray(c,c+1)),c+=1,s=T_(e,12),i=T_(e,16),o=T_(e,20),l=T_(e,24),c=28}else if(1===t){c+=4,s=T_(e,c),c+=4;const t=T_(e,c);c+=4;const i=T_(e,c);for(c+=4,a=2**32*t+i,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,RC.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=T_(e,c),c+=4,l=T_(e,c),c+=4;"\0"!==E_(e.subarray(c,c+1));)n+=E_(e.subarray(c,c+1)),c+=1;for(n+=E_(e.subarray(c,c+1)),c+=1;"\0"!==E_(e.subarray(c,c+1));)r+=E_(e.subarray(c,c+1)),c+=1;r+=E_(e.subarray(c,c+1)),c+=1}return{schemeIdUri:n,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:o,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(lk.test(r.schemeIdUri)){const e=wC(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const i=r.payload;n.samples.push({data:i,len:i.byteLength,dts:e,pts:e,type:AR,duration:s})}}))}return n}demuxSampleAes(e,t,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(function(e,t){if(!e||!t)return e;const n=t.keyId;n&&t.isCommonEncryption&&__(e,["moov","trak"]).forEach((e=>{const t=__(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=__(t,["enca"]);const s=r.length>0;s||(r=__(t,["encv"])),r.forEach((e=>{__(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=k_(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(RC.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${v_(e)} -> ${v_(n)}`),t.set(n,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:n}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=O_(e);t||(t=Kk(r.audio,MC)),n||(n=Kk(r.video,UC));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+n,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:RC.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,n,r,s,i){var a,o;let{initPTS:l,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};wC(c)||(c=this.lastEndTime=s||0);const u=t.samples;if(null==u||!u.length)return d;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return RC.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let n=0,r=0,s=0;const i=__(e,["moof","traf"]);for(let e=0;e<i.length;e++){const a=i[e],o=__(a,["tfhd"])[0],l=t[T_(o,4)];if(!l)continue;const c=l.default,d=T_(o,0)|(null==c?void 0:c.flags);let u=null==c?void 0:c.duration;8&d&&(u=T_(o,2&d?12:8));const h=l.timescale||9e4,f=__(a,["trun"]);for(let e=0;e<f.length;e++)n=P_(f[e]),!n&&u&&(n=u*T_(f[e],4)),l.type===UC?r+=n/h:l.type===MC&&(s+=n/h)}if(0===r&&0===s){let t=0;const n=__(e,["sidx"]);for(let e=0;e<n.length;e++){const r=R_(n[e]);null!=r&&r.references&&(t+=r.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return r||s}(u,f),g=function(e,t){return __(t,["moof","traf"]).reduce(((t,n)=>{const r=__(n,["tfdt"])[0],s=r[0],i=__(n,["tfhd"]).reduce(((t,n)=>{const i=T_(n,4),a=e[i];if(a){let e=T_(r,4);if(1===s){if(e===b_)return RC.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=b_+1,e+=T_(r,8)}const n=e/(a.timescale||9e4);if(isFinite(n)&&(null===t||n<t))return n}return t}),null);return null!==i&&isFinite(i)&&(null===t||i<t)?i:t}),null)}(f,u),m=null===g?s:g;(function(e,t,n,r){if(null===e)return!0;const s=Math.max(r,1),i=t-e.baseTime/e.timescale;return Math.abs(i-n)>s}(l,m,s,p)||h.timescale!==l.timescale&&i)&&(h.initPTS=m-s,l&&1===l.timescale&&RC.warn("Adjusting initPTS by "+(h.initPTS-l.baseTime)),this.initPTS=l={baseTime:h.initPTS,timescale:1});const y=e?m-l.baseTime/l.timescale:c,v=y+p;!function(e,t,n){__(t,["moof","traf"]).forEach((t=>{__(t,["tfhd"]).forEach((r=>{const s=T_(r,4),i=e[s];if(!i)return;const a=i.timescale||9e4;__(t,["tfdt"]).forEach((e=>{const t=e[0];let r=T_(e,4);if(0===t)r-=n*a,r=Math.max(r,0),C_(e,4,r);else{r*=Math.pow(2,32),r+=T_(e,8),r-=n*a,r=Math.max(r,0);const t=Math.floor(r/(b_+1)),s=Math.floor(r%(b_+1));C_(e,4,t),C_(e,8,s)}}))}))}))}(f,u,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(RC.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,w=!!f.video;let S="";b&&(S+="audio"),w&&(S+="video");const E={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:S,hasAudio:b,hasVideo:w,nb:1,dropped:0};return d.audio="audio"===E.type?E:void 0,d.video="audio"!==E.type?E:void 0,d.initSegment=h,d.id3=Bk(n,s,l,l),r.samples.length&&(d.text=jk(r,s,l)),d}}},{demux:Ek,remux:Fk},{demux:class extends XO{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(s_(e,0)||[]).length;for(let n=e.length;t<n;t++)if(sk(e,t))return RC.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&ek(e,t)&&nk(e,t)<=e.length-t}(e,t)}appendFrame(e,t,n){ik(e,this.observer,t,n,e.manifestCodec);const r=ok(e,t,n,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Fk},{demux:class extends XO{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(s_(e,0)||[]).length;for(let n=e.length;t<n;t++)if(vk(e,t))return RC.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return mk(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,n){if(null!==this.basePTS)return pk(e,t,n,this.basePTS,this.frameIndex)}},remux:Fk}];class Wk{constructor(e,t,n,r,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.vendor=r,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){const s=n.transmuxing;s.executeStart=xk();let i=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=r||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=o,b=function(e,t){let n=null;e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(n=t);return n}(i,t);if(b&&"AES-128"===b.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(i,b.key.buffer,b.iv.buffer).then((e=>{const t=this.push(e,null,n);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(i,b.key.buffer,b.iv.buffer);if(n.part>-1&&(t=e.flush()),!t)return s.executeEnd=xk(),Hk(n);i=new Uint8Array(t)}}const w=this.needsProbing(c,d);if(w){const e=this.configureTransmuxer(i);if(e)return RC.warn(`[transmuxer] ${e.message}`),this.observer.emit(SC.ERROR,SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=xk(),Hk(n)}(c||d||f||w)&&this.resetInitSegment(v,p,g,y,t),(c||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(i,b,h,u,n),E=this.currentTransmuxState;return E.contiguous=!0,E.discontinuity=!1,E.trackSwitch=!1,s.executeEnd=xk(),S}flush(e){const t=e.transmuxing;t.executeStart=xk();const{decrypter:n,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:a}=r;if(n){const t=n.flush();t&&i.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=xk(),[Hk(e)];const c=o.flush(a);return Vk(c)?c.then((t=>(this.flushRemux(i,t,e),i))):(this.flushRemux(i,c,e),i)}flushRemux(e,t,n){const{audioTrack:r,videoTrack:s,id3Track:i,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;RC.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const c=this.remuxer.remux(r,s,i,a,l,o,!0,this.id);e.push({remuxResult:c,chunkMeta:n}),n.transmuxing.executeEnd=xk()}resetInitialTimestamp(e){const{demuxer:t,remuxer:n}=this;t&&n&&(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,s){const{demuxer:i,remuxer:a}=this;i&&a&&(i.resetInitSegment(e,t,n,r),a.resetInitSegment(e,t,n,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,n,r,s){let i;return i=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,n,r,s):this.transmuxUnencrypted(e,n,r,s),i}transmuxUnencrypted(e,t,n,r){const{audioTrack:s,videoTrack:i,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,a,o,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,s){return this.demuxer.demuxSampleAes(e,t,n).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:n,typeSupported:r,vendor:s}=this;let i;for(let t=0,n=Gk.length;t<n;t++)if(Gk[t].demux.probe(e)){i=Gk[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,c=i.demux;o&&o instanceof l||(this.remuxer=new l(n,t,r,s)),a&&a instanceof c||(this.demuxer=new c(n,t,r),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new MO(this.config)),e}}const Hk=e=>({remuxResult:{},chunkMeta:e});function Vk(e){return"then"in e&&e.then instanceof Function}class Yk{constructor(e,t,n,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=s||null}}class Qk{constructor(e,t,n,r,s,i){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=i}}var zk={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,i||e,a),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,a=new Array(i);s<i;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,s,i,a){var o=n?n+e:e;if(!this._events[o])return!1;var l,c,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,i),!0;case 6:return d.fn.call(d.context,t,r,s,i,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,f=d.length;for(c=0;c<f;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,r);break;case 4:d[c].fn.call(d[c].context,t,r,s);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},o.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},o.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},o.prototype.removeListener=function(e,t,r,s){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return a(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||s&&!o.once||r&&o.context!==r||a(this,i);else{for(var l=0,c=[],d=o.length;l<d;l++)(o[l].fn!==t||s&&!o[l].once||r&&o[l].context!==r)&&c.push(o[l]);c.length?this._events[i]=1===c.length?c[0]:c:a(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o}(zk);var Jk=fC(zk.exports);const Xk=H_()||{isTypeSupported:()=>!1};class Zk{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;const i=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===SC.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Jk,this.observer.on(SC.FRAG_DECRYPTED,i),this.observer.on(SC.ERROR,i);const a={mp4:Xk.isTypeSupported("video/mp4"),mpeg:Xk.isTypeSupported("audio/mpeg"),mp3:Xk.isTypeSupported('audio/mp4; codecs="mp3"')},o=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(RC.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(RC.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const n=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,RC.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:n})},e.postMessage({cmd:"init",typeSupported:a,vendor:o,id:t,config:JSON.stringify(s)})}catch(e){RC.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new Wk(this.observer,a,s,o,t)}return}}this.transmuxer=new Wk(this.observer,a,s,o,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,n,r,s,i,a,o,l,c){var d,u;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,f=i?i.start:s.start,p=s.decryptdata,g=this.frag,m=!(g&&s.cc===g.cc),y=!(g&&l.level===g.level),v=g?l.sn-g.sn:-1,b=this.part?l.part-this.part.index:-1,w=0===v&&l.id>1&&l.id===(null==g?void 0:g.stats.chunkCount),S=!y&&(1===v||0===v&&(1===b||w&&b<=0)),E=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=E),!i||!b&&S||(i.stats.parsing.start=E);const I=!(g&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=g.initSegment)?void 0:u.url)),T=new Qk(m,S,o,y,f,I);if(!S||m||I){RC.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${I}`);const e=new Yk(n,r,t,a,c);this.configureTransmuxer(e)}if(this.frag=s,this.part=i,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:T},e instanceof ArrayBuffer?[e]:[]);else if(h){const t=h.push(e,p,l,T);Vk(t)?(h.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(h.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let n=t.flush(e);Vk(n)||t.async?(Vk(n)||(n=Promise.resolve(n)),n.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(n,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data,n=this.hls;switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":RC[t.data.logType]&&RC[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,n.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class eP{constructor(e,t,n,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=n,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:n,media:r,stalled:s}=this;if(null===r)return;const{currentTime:i,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;RC.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!AO.getBuffered(r).length)return;const c=AO.bufferInfo(r,i,0),d=c.len>0,u=c.nextStart||0;if(!d&&!u)return;if(a){const e=c.len>2,n=!u||t&&t.start<=i||u-i>2&&!this.fragmentTracker.getPartialFragment(i);if(e||n)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;const e=Math.max(u,c.start||0)-i,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,n=(null==t||null==(h=t.details)?void 0:h.live)?2*t.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(i);if(e>0&&(e<=n||r))return void this._trySkipBufferHole(r)}const f=self.performance.now();if(null===s)return void(this.stalled=f);const p=f-s;if(!a&&p>=250&&(this._reportStall(c),!this.media))return;const g=AO.bufferInfo(r,i,n.maxBufferHole);this._tryFixBufferStall(g,p)}_tryFixBufferStall(e,t){const{config:n,fragmentTracker:r,media:s}=this;if(null===s)return;const i=s.currentTime,a=r.getPartialFragment(i);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-i<n.maxBufferHole)&&t>1e3*n.highBufferWatchdogPeriod&&(RC.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:n,stallReported:r}=this;if(!r&&n){this.stallReported=!0;const r=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);RC.warn(r.message),t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:n,media:r}=this;if(null===r)return 0;const s=r.currentTime,i=AO.bufferInfo(r,s,0),a=s<i.start?i.start:i.nextStart;if(a){const o=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&r.readyState<3,c=a-s;if(c>0&&(o||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let n=!1;if(0===s){const e=t.getAppendedFrag(0,fR);e&&a<e.end&&(n=!0)}if(!n){const n=e||t.getAppendedFrag(s,fR);if(n){let e=!1,r=n.end;for(;r<a;){const n=t.getPartialFragment(r);if(!n){e=!0;break}r+=n.duration}if(e)return 0}}}const i=Math.max(a+.05,s+.1);if(RC.warn(`skipping hole, adjusting currentTime from ${s} to ${i}`),this.moved=!0,this.stalled=null,r.currentTime=i,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${i}`);n.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return i}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:n,nudgeRetry:r}=this;if(null===n)return;const s=n.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const i=s+(r+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${i}`);RC.warn(a.message),n.currentTime=i,t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);RC.error(n.message),t.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}class tP extends QO{constructor(e,t,n){super(e,t,n,"[stream-controller]",fR),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(SC.ERROR,this.onError,this),e.on(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this),e.on(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(SC.ERROR,this.onError,this),e.off(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(SC.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this),e.off(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(SC.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=n.startLevel;-1===e&&(n.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=n.nextAutoLevel),this.level=n.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=NO,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=FO}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case YO:{var e;const{levels:t,level:n}=this,r=null==t||null==(e=t[n])?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=NO;break}if(this.hls.nextLoadLevel!==this.level){this.state=NO;break}break}case $O:{var t;const e=self.performance.now(),n=this.retryDate;(!n||e>=n||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=NO)}}this.state===NO&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:n,media:r}=this,{config:s,nextLoadLevel:i}=e;if(null===t||!r&&(this.startFragRequested||!s.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==n||!n[i])return;const a=n[i],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(SC.BUFFER_EOS,e),void(this.state=WO)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=a.details;if(!c||this.state===YO||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=YO);const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==pO){var p;const e=(null!=(p=this.backtrackFragment)?p:f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?MC:UC,t=(e===UC?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,fR)}f=this.getNextFragmentLoopLoading(f,c,o,fR,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===uO||r===fO?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,fR)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let n;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;n=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else n=0;const i=this.getBufferedFrag(t.currentTime+n);if(i){const e=this.followingBufferedFrag(i);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(i.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,.5*n),.75*n));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case BO:case jO:case $O:case KO:case GO:this.state=NO}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const n=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),n.addEventListener("playing",this.onvplaying),n.addEventListener("seeked",this.onvseeked),this.gapController=new eP(this.config,n,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;wC(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const n=this.getMainFwdBufferInfo();null!==n&&0!==n.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${n?n.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(SC.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let n,r=!1,s=!1;t.levels.forEach((e=>{n=e.audioCodec,n&&(-1!==n.indexOf("mp4a.40.2")&&(r=!0),-1!==n.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=r&&s&&!function(){var e;const t=zO();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:n}=this;if(!n||this.state!==NO)return;const r=n[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=YO)}onLevelLoaded(e,t){var n;const{levels:r}=this,s=t.level,i=t.details,a=i.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""}, cc [${i.startCC}, ${i.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==jO&&this.state!==$O||l.level===t.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(n=o.details)&&n.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,o.details)}if(o.details=i,this.levelLastLoaded=s,this.hls.trigger(SC.LEVEL_UPDATED,{details:i,level:s}),this.state===YO){if(this.waitForCdnTuneIn(i))return;this.state=NO}this.startFragRequested?i.live&&this.synchronizeToLiveEdge(i):this.setStartPosition(i,c),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:n,part:r,payload:s}=e,{levels:i}=this;if(!i)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);const a=i[n.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),void this.fragmentTracker.removeFragment(n);const l=a.videoCodec,c=o.PTSKnown||!o.live,d=null==(t=n.initSegment)?void 0:t.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Zk(this.hls,fR,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,p=-1!==f,g=new CO(n.level,n.sn,n.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[n.cc];h.push(s,d,u,l,n,r,o.totalduration,c,g,m)}onAudioTrackSwitching(e,t){const n=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;n&&(e.trigger(SC.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(SC.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const n=t.id,r=!!this.hls.audioTracks[n].url;if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const n=t.tracks;let r,s,i=!1;for(const e in n){const t=n[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=n[e];t&&(this.videoBuffer=t.buffer)}}else i=!0}i&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:n,part:r}=t;if(n&&n.type!==fR)return;if(this.fragContextChanged(n))return this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===GO&&(this.state=NO));const s=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==n.sn&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}onError(e,t){var n;if(t.fatal)this.state=HO;else switch(t.details){case IC.FRAG_GAP:case IC.FRAG_PARSING_ERROR:case IC.FRAG_DECRYPT_ERROR:case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(fR,t);break;case IC.LEVEL_LOAD_ERROR:case IC.LEVEL_LOAD_TIMEOUT:case IC.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==YO||(null==(n=t.context)?void 0:n.type)!==dR||(this.state=NO);break;case IC.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case IC.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!AO.getBuffered(e).length){const e=this.state!==NO?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=NO,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==MC||this.audioOnly&&!this.altAudio){const e=(t===UC?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,fR)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let n=this.startPosition;if(n>=0&&t<n){if(e.seeking)return void this.log(`could not seek to ${n}, already seeking at ${t}`);const r=AO.getBuffered(e),s=(r.length?r.start(0):0)-n;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),this.log(`seek to target start position ${n} from current time ${t}`),e.currentTime=n}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((n=>{const{hls:r}=this;if(!n||this.fragContextChanged(e))return;t.fragmentError=0,this.state=NO,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(SC.FRAG_LOADED,n),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const n="main",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{video:d,text:u,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=KO,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(c,f.tracks,e,i),r.trigger(SC.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;wC(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(SC.INIT_PTS_FOUND,{frag:o,id:n,initPTS:e,timescale:t}))}if(d&&p&&"initSegment"!==o.sn){const e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===i.id&&!n&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!n)return void this.backtrack(o);n&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,r,o.start,a,!0)}o.setElementaryStreamInfo(d.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,i,t||n)}else{if(!t&&!n)return void this.backtrack(o);o.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=g;l&&(l.elementaryStreams[MC]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(MC,e,t,n,r),this.bufferFragmentData(g,o,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:n,frag:o,details:p,samples:h.samples};r.trigger(SC.FRAG_PARSING_METADATA,e)}if(p&&u){const e={id:n,frag:o,details:p,samples:u.samples};r.trigger(SC.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,n,r){if(this.state!==KO)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:a}=t;if(s){let t=e.audioCodec;const n=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===n.indexOf("firefox")&&(t="mp4a.40.5")),-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}i&&(i.levelCodec=e.videoCodec,i.id="main",this.log(`Init video buffer, container:${i.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(SC.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(SC.BUFFER_APPENDING,{type:e,data:s,frag:n,part:null,chunkMeta:r,parent:n.type})})),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,fR)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=NO}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const n=e.currentTime;if(AO.isBuffered(e,n)?t=this.getAppendedFrag(n):AO.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,n=t.level;e&&t.sn===e.sn&&e.level===n&&t.urlId===e.urlId||(this.fragPlaying=t,this.hls.trigger(SC.FRAG_CHANGED,{frag:t}),e&&e.level===n||this.hls.trigger(SC.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,n=this.currentFrag;if(n&&wC(t)&&wC(n.programDateTime)){const e=n.programDateTime+1e3*(t-n.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class nP{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){const n=Math.pow(this.alpha_,e);this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class rP{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new nP(e),this.fast_=new nP(t),this.defaultTTFB_=r,this.ttfb_=new nP(e)}update(e,t){const{slow_:n,fast_:r,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new nP(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new nP(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new nP(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const n=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class sP{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let n;return e.length?(n=1===e.length?e[0]:function(e,t){const n=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return n}(e,t),this.reset(),n):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function iP(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!aP(e[n].attrs,t[n].attrs))return!1;return!0}function aP(e,t){const n=e["STABLE-RENDITION-ID"];return n?n===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some((n=>e[n]!==t[n]))}class oP{constructor(e){this.buffered=void 0;const t=(t,n,r)=>{if((n>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end:n=>t("end",n,e.length),start:n=>t("start",n,e.length)}}}function lP(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[n])}return t}class cP{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const n=this.queues[t];n.push(e),1===n.length&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const n=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),n}executeNext(e){const{buffers:t,queues:n}=this,r=t[e],s=n[e];if(s.length){const t=s[0];try{t.execute()}catch(n){RC.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),t.onError(n),null!=r&&r.updating||(s.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const dP=H_(),uP=/([ha]vc.)(?:\.[^.,]+)+/;const hP={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},fP=function(e){let t=e;return hP.hasOwnProperty(e)&&(t=hP[e]),String.fromCharCode(t)},pP=15,gP=100,mP={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},yP={17:2,18:4,21:6,22:8,23:10,19:13,20:15},vP={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},bP={25:2,26:4,29:6,30:8,31:10,27:13,28:15},wP=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class SP{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const n="function"==typeof t?t():t;RC.log(`${this.time} [${e}] ${n}`)}}}const EP=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t};class IP{constructor(e,t,n,r,s){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=n||!1,this.background=r||"black",this.flash=s||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let n=0;n<t.length;n++){const r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class TP{constructor(e,t,n,r,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new IP(t,n,r,s,i)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class AP{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<gP;e++)this.chars.push(new TP);this.logger=e,this.pos=0,this.currPenState=new IP}equals(e){let t=!0;for(let n=0;n<gP;n++)if(!this.chars[n].equals(e.chars[n])){t=!1;break}return t}copy(e){for(let t=0;t<gP;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<gP;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>gP&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=gP)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=fP(e);this.pos>=gP?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<gP;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let n=0;n<gP;n++){const r=this.chars[n].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class CP{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<pP;t++)this.rows.push(new AP(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<pP;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<pP;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<pP;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<pP;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<pP;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const r=n.rows[e].cueStartTime,s=this.logger.time;if(r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;const n=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let n="",r=-1;for(let n=0;n<pP;n++){const s=this.rows[n].getTextString();s&&(r=n+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(n=e?"["+t.join(" | ")+"]":t.join("\n")),n}getTextAndFormat(){return this.rows}}class _P{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new CP(n),this.nonDisplayedMemory=new CP(n),this.lastOutputScreen=new CP(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const n=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class RP{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const r=new SP;this.channels=[null,new _P(e,t,r),new _P(e+1,n,r)],this.cmdHistory={a:null,b:null},this.logger=r}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let n,r,s,i=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(r=127&t[e],s=127&t[e+1],0!==r||0!==s){if(this.logger.log(3,"["+EP([t[e],t[e+1]])+"] -> ("+EP([r,s])+")"),n=this.parseCmd(r,s),n||(n=this.parseMidrow(r,s)),n||(n=this.parsePAC(r,s)),n||(n=this.parseBackgroundAttributes(r,s)),!n&&(i=this.parseChars(r,s),i)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(i)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||i||this.logger.log(2,"Couldn't parse cleaned data "+EP([r,s])+" orig: "+EP([t[e],t[e+1]]))}}parseCmd(e,t){const{cmdHistory:n}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(kP(e,t,n))return OP(null,null,n),this.logger.log(3,"Repeated command ("+EP([e,t])+") is dropped"),!0;const r=20===e||21===e||23===e?1:2,s=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),OP(e,t,n),this.currentChannel=r,!0}parseMidrow(e,t){let n=0;if((17===e||25===e)&&t>=32&&t<=47){if(n=17===e?1:2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[n];return!!r&&(r.ccMIDROW(t),this.logger.log(3,"MIDROW ("+EP([e,t])+")"),!0)}return!1}parsePAC(e,t){let n;const r=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(kP(e,t,r))return OP(null,null,r),!0;const s=e<=23?1:2;n=t>=64&&t<=95?1===s?mP[e]:vP[e]:1===s?yP[e]:bP[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(n,t)),OP(e,t,r),this.currentChannel=s,!0)}interpretPAC(e,t){let n;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=1==(1&n),n<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((n-16)/2),r}parseChars(e,t){let n,r=null,s=null;if(e>=25?(n=2,s=e-8):(n=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+fP(e)+"' in channel "+n),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);if(r){const n=EP(r);this.logger.log(3,"Char codes = "+n.join(",")),OP(e,t,this.cmdHistory)}return r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let n;const r={};16===e||24===e?(n=Math.floor((t-32)/2),r.background=wP[n],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),OP(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const n=this.channels[t];n&&n.cueSplitAtTime(e)}}}function OP(e,t,n){n.a=e,n.b=t}function kP(e,t,n){return n.a===e&&n.b===t}class PP{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var DP=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function n(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const n=t.toLowerCase();return!!~e.indexOf(n)&&n}function r(e){return n(t,e)}function s(e,...t){let n=1;for(;n<arguments.length;n++){const t=arguments[n];for(const n in t)e[n]=t[n]}return e}function i(t,i,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let c="",d=!1,u=t,h=i,f=a,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",S=50,E="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return g},set:function(t){const r=function(t){return n(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return v},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return w},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return E},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),o.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class LP{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function xP(e){function t(e,t,n,r){return 3600*(0|e)+60*(0|t)+(0|n)+parseFloat(r||0)}const n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}class MP{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}}function UP(e,t,n,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(n);if(2!==r.length)continue;t(r[0],r[1])}}const FP=new DP(0,0,""),NP="middle"===FP.align?"middle":"center";function BP(e,t,n){const r=e;function s(){const t=xP(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function i(){e=e.replace(/^\s+/,"")}if(i(),t.startTime=s(),i(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),i(),t.endTime=s(),i(),function(e,t){const r=new MP;UP(e,(function(e,t){let s;switch(e){case"region":for(let s=n.length-1;s>=0;s--)if(n[s].id===t){r.set(e,n[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",NP,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",NP,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",NP,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===FP.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",NP);let i=r.get("position","auto");"auto"===i&&50===FP.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function jP(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class $P{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new LP,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function n(){let e=t.buffer,n=0;for(e=jP(e);n<e.length&&"\r"!==e[n]&&"\n"!==e[n];)++n;const r=e.slice(0,n);return"\r"===e[n]&&++n,"\n"===e[n]&&++n,t.buffer=e.slice(n),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=n();const r=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=n(),t.state){case"HEADER":/:/.test(e)?UP(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new DP(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{BP(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const n=-1!==e.indexOf("--\x3e");if(!e||n&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const qP=/\r\n|\n\r|\n|\r/g,KP=function(e,t,n=0){return e.slice(n,n+t.length)===t},GP=function(e){let t=5381,n=e.length;for(;n;)t=33*t^e.charCodeAt(--n);return(t>>>0).toString()};function WP(e,t,n){return GP(e.toString())+GP(t.toString())+GP(n)}function HP(e,t,n,r,s,i,a){const o=new $P,l=g_(new Uint8Array(e)).trim().replace(qP,"\n").split("\n"),c=[],d=t?function(e,t=1){return Dk(e,9e4,1/t)}(t.baseTime,t.timescale):0;let u,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const i=n[r];let a=n.ccOffset;const o=(f-d)/9e4;if(null!=i&&i.new&&(void 0!==p?a=n.ccOffset=i.start:function(e,t,n){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(i=s)&&i.new;){var i;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=n}(n,r,o)),o){if(!t)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-n.presentationOffset}const l=e.endTime-e.startTime,h=Nk(9e4*(e.startTime+a-p),9e4*s)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=WP(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},o.onparsingerror=function(e){u=e},o.onflush=function(){u?a(u):i(c)},l.forEach((e=>{if(g){if(KP(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{KP(e,"LOCAL:")?h=e.slice(6):KP(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(wC(t)&&wC(n)&&wC(r)&&wC(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=6e4*r,t+=36e5*s,t}(h)/1e3}catch(e){u=e}return}""===e&&(g=!1)}o.parse(e+"\n")})),o.flush()}const VP="stpp.ttml.im1t",YP=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,QP=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zP={left:"start",center:"center",right:"end",start:"start",end:"end"};function JP(e,t,n,r){const s=__(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>g_(e))),a=function(e,t,n=1,r=!1){return Dk(e,t,1/n,r)}(t.baseTime,1,t.timescale);try{i.forEach((e=>n(function(e,t){const n=new DOMParser,r=n.parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=ZP(XP(r,"styling","style")),l=ZP(XP(r,"layout","region")),c=XP(r,"body","[begin]");return[].map.call(c,(e=>{const n=eD(e,a);if(!n||!e.hasAttribute("begin"))return null;const r=rD(e.getAttribute("begin"),i),s=rD(e.getAttribute("dur"),i);let c=rD(e.getAttribute("end"),i);if(null===r)throw nD(e);if(null===c){if(null===s)throw nD(e);c=r+s}const d=new DP(r-t,c-t,n);d.id=WP(d.startTime,d.endTime,d.text);const u=function(e,t,n){const r="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&n.hasOwnProperty(a)&&(s=n[a]);return i.reduce(((n,i)=>{const a=tD(t,r,i)||tD(e,r,i)||tD(s,r,i);return a&&(n[i]=a),n}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=u;if(h){const e=zP[h];e&&(d.lineAlign=e),d.align=h}return bC(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function XP(e,t,n){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function ZP(e){return e.reduce(((e,t)=>{const n=t.getAttribute("xml:id");return n&&(e[n]=t),e}),{})}function eD(e,t){return[].slice.call(e.childNodes).reduce(((e,n,r)=>{var s;return"br"===n.nodeName&&r?e+"\n":null!=(s=n.childNodes)&&s.length?eD(n,t):t?e+n.textContent.trim().replace(/\s+/g," "):e+n.textContent}),"")}function tD(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function nD(e){return new Error(`Could not parse ttml timestamp ${e}`)}function rD(e,t){if(!e)return null;let n=xP(e);return null===n&&(YP.test(e)?n=function(e,t){const n=YP.exec(e),r=(0|n[4])+(0|n[5])/t.subFrameRate;return 3600*(0|n[1])+60*(0|n[2])+(0|n[3])+r/t.frameRate}(e,t):QP.test(e)&&(n=function(e,t){const n=QP.exec(e),r=Number(n[1]);switch(n[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),n}function sD(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class iD{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(SC.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(SC.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){const n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const n=t.filter(((t,n)=>this.isLevelAllowed(t)&&n<=e));return this.clientRect=null,iD.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,t.width||t.height||(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,n){if(null==e||!e.length)return-1;let r=e.length-1;for(let a=0;a<e.length;a+=1){const o=e[a];if((o.width>=t||o.height>=n)&&(s=o,!(i=e[a+1])||s.width!==i.width||s.height!==i.height)){r=a;break}}var s,i;return r}}const aD="[eme]";class oD{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=oD.CDMCleanupPromise?[oD.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=RC.debug.bind(RC,aD),this.log=RC.log.bind(RC,aD),this.warn=RC.warn.bind(RC,aD),this.error=RC.error.bind(RC,aD),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(SC.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(SC.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===WC.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,n=t[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(n),s=t.map((e=>e.videoCodec)).filter(n);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,n)=>{const i=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?i(e):n(t instanceof lD?t:new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};i(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:n}=this.config;if("function"!=typeof n){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return null===e_&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){const r=function(e,t,n,r){let s;switch(e){case WC.FAIRPLAY:s=["cenc","sinf"];break;case WC.WIDEVINE:case WC.PLAYREADY:s=["cenc"];break;case WC.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:n.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,n,r)}(e,t,n,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let i=null==s?void 0:s.keySystemAccess;if(!i){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),i=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:i};return i.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),i.then((n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=n.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((n=>n?this.setMediaKeysServerCertificate(t,e,n):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return i.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${v_(e.keyId||[])}`);const r=n.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const n=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return v_(e.keyId)}updateKeySession(e,t){var n;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${v_((null==(n=e.decryptdata)?void 0:n.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,n)=>{const r=ZC(this.config),s=e.map(zC).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=XC(e);r?t(r):n(new Error(`Unable to find format for key-system "${e}"`))})).catch(n)}))}loadKey(e){const t=e.keyInfo.decryptdata,n=this.getKeyIdString(t),r=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[n];return s||(s=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(t).then((({keySystem:n,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(n,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:n,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof lD?this.hls.trigger(SC.ERROR,e.data):this.hls.trigger(SC.ERROR,{type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[t];if(!n){const t=zC(e.keyFormat),n=t?[t]:ZC(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=ZC(this.config)),0===e.length)throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:n}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===n)return;let r,s;if("sinf"===t&&this.config.drmSystems[WC.FAIRPLAY]){const e=E_(new Uint8Array(n));try{const t=qC(JSON.parse(e).sinf),n=k_(new Uint8Array(t));if(!n)return;r=n.subarray(8,24),s=WC.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},n=new DataView(e),r=n.getUint32(0);if(e.byteLength!==r&&r>44)return null;if(1886614376!==n.getUint32(4))return null;if(t.version=n.getUint32(8)>>>24,t.version>1)return null;t.systemId=v_(new Uint8Array(e,12,16));const s=n.getUint32(28);if(0===t.version){if(r-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let n=0;n<s;n++)t.kids.push(new Uint8Array(e,32+16*n,16))}return t}(n);if(null===e)return;0===e.version&&e.systemId===JC&&e.data&&(r=e.data.subarray(8,24)),s=function(e){if(e===JC)return WC.WIDEVINE}(e.systemId)}if(!s||!r)return;const i=v_(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[i];for(let e=0;e<o.length;e++){const s=o[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const d=v_(c.keyId);if(i===d||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=a[d],delete a[d],c.pssh=new Uint8Array(n),c.keyId=r,l=a[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,n,"encrypted-event-key-match")));break}}l||(l=a[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new B_("ISO-23001-7",i,null!=(a=XC(e))?a:"");return o.pssh=new Uint8Array(n),o.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,n,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(n).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===n.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,n,r){var s,i;const a=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(a)try{const r=a.call(this.hls,t,n,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,n=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===n)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${n?n.byteLength:null})`);const c=new Jk;e.mediaKeysSession.onmessage=t=>{const n=e.mediaKeysSession;if(!n)return void c.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),c.emit("error",e)})):"license-release"===r?e.keySystem===WC.FAIRPLAY&&(this.updateKeySession(e,GC("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const n=e.keyStatus;c.emit("keyStatus",n),"expired"===n&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};const d=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(n=>{n.startsWith("usable")?e():"output-restricted"===n?t(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===n?t(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${n}"`)):"expired"===n?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${n}"`)}))}));return e.mediaKeysSession.generateRequest(t,n).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>d)).catch((t=>{throw c.removeAllListeners(),this.removeSession(e),t})).then((()=>(c.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,n)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${v_("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${v_(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,n=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise(((s,i)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{s(e.data)},onError:(t,n,s,o)=>{i(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:yC({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,s)=>{i(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,n)=>{i(new Error("aborted"))}};n.load(a,l,c)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise(((r,s)=>{e.setServerCertificate(n).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==n?void 0:n.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}setupLicenseXHR(e,t,n,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!n.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,n,r)})).catch((i=>{if(!n.decryptdata)throw i;return e.open("POST",t,!0),s.call(this.hls,e,t,n,r)})).then((n=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:n||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const n=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const i=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${i}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,a,i,e)}catch(e){this.error(e)}r(t)}else{const o=n.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new lD({type:EC.KEY_SYSTEM_ERROR,details:IC.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:i,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${i}). Status: ${a.status} (${a.statusText})`));else{const n=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,i,e,t).then((({xhr:e,licenseChallenge:t})=>{e.send(t)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const n=t.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},B_.clearKeyUriToKeyIdMap();const n=t.length;oD.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)})))).then((()=>{n&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:n}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}oD.CDMCleanupPromise=void 0;class lD extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var cD="m",dD="a",uD="v",hD="av",fD="i",pD="tt";class gD{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:cD,su:!this.initialized})}catch(e){RC.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,n=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};r!==uD&&r!==dD&&r!=hD||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){RC.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:n}=t;null!=n&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||gD.uuid(),this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHED,this.onMediaDetached,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHED,this.onMediaDetached,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var n,r;this.audioBuffer=null==(n=t.tracks.audio)?void 0:n.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){bC(t,this.createData());const n=t.ot===fD||t.ot===uD||t.ot===hD;if(this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const n=gD.toHeaders(t);if(!Object.keys(n).length)return;e.headers||(e.headers={}),bC(e.headers,n)}else{const n=gD.toQuery(t);if(!n)return;e.url=gD.appendQueryToUri(e.url,n)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?pD:"initSegment"===e.sn?fD:"audio"===t?dD:"main"===t?this.hls.audioTracks.length?uD:hD:void 0}getTopBandwidth(e){let t,n=0;const r=this.hls;if(e===dD)t=r.audioTracks;else{const e=r.maxAutoLevel,n=e>-1?e+1:r.levels.length;t=r.levels.slice(0,n)}for(const e of t)e.bitrate>n&&(n=e.bitrate);return n>0?n:NaN}getBufferLength(e){const t=this.hls.media,n=e===dD?this.audioBuffer:this.videoBuffer;if(!n||!t)return NaN;return 1e3*AO.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],n=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,r=e=>Math.round(e),s=e=>100*r(e/100),i={br:r,d:r,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:r},a=Object.keys(e||{}).sort();for(const r of a){let s=e[r];if(!n(s))continue;if("v"===r&&1===s)continue;if("pr"==r&&1===s)continue;const a=i[r];a&&(s=a(s));const o=typeof s;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${s}`:"boolean"===o?r:"number"===o?`${r}=${s}`:`${r}=${JSON.stringify(s)}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),n={},r=["Object","Request","Session","Status"],s=[{},{},{},{}],i={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const n of t){s[null!=i[n]?i[n]:1][n]=e[n]}for(let e=0;e<s.length;e++){const t=gD.serialize(s[e]);t&&(n[`CMCD-${r[e]}`]=t)}return n}static toQuery(e){return`CMCD=${encodeURIComponent(gD.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const n=e.includes("?")?"&":"?";return`${e}${n}${t}`}}function mD(e,t,n,r){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=bC({},e);return i.details=void 0,i.attrs=new PC(i.attrs),i.url=i.attrs.URI=yD(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),i.groupId=i.attrs["GROUP-ID"]=t[s],i.attrs["PATHWAY-ID"]=r,i}));e.push(...i)}))}function yD(e,t,n,r){const{HOST:s,PARAMS:i,[n]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const vD=/^age:\s*[\d.]+\s*$/im;class bD{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new xC,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(!this.stats.aborted)return s(n,t.url)})).catch((e=>(n.open("GET",t.url,!0),s(n,t.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(n,t,e)})).catch((e=>{this.callbacks.onError({code:n.status,text:e.message},t,n,r)})):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open("GET",t.url,!0);const r=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:i}=n.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=s&&wC(s)?s:i,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:n}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!n.aborted&&r>=2&&(0===n.loading.first&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,i="text"!==t.responseType;if(r>=200&&r<300&&(i&&t.response||null!==t.responseText)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const s=i?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(n.loaded=n.total=a,n.bwEstimate=8e3*n.total/(n.loading.end-n.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(n,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,n,e,t)}else{const i=s.loadPolicy.errorRetry;YR(i,n.retry,!1,r)?this.retry(i):(RC.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,n))}}}loadtimeout(){var e;const t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(YR(t,this.stats.retry,!0))this.retry(t);else{RC.warn(`timeout while loading ${this.context.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:n}=this;this.retryDelay=HR(e,n.retry),n.retry++,RC.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&vD.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const wD=/(\d+)-(\d+)\/(\d+)/;class SD{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||ED,this.controller=new self.AbortController,this.stats=new xC}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;null!=e&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(bC({},e.headers))};e.rangeEnd&&n.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return n}(e,this.controller.signal),i=n.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&wC(l)?l:c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),n.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),n.onTimeout(r,e,this.response)}),c-(o-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new ID(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=wD.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(wC(e))return e}const n=e.get("Content-Length");if(n)return parseInt(n)}(s.headers)||r.total,i&&wC(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,i):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const c={url:a.url,data:s,code:a.status};i&&!wC(t.highWaterMark)&&i(r,e,s,a),n.onSuccess(c,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,i=t?t.message:null;n.onError({code:s,text:i},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,s){const i=new sP,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return i.dataLength&&s(t,n,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,c=l.length;return t.loaded+=c,c<r||i.dataLength?(i.push(l),i.dataLength>=r&&s(t,n,i.flush(),e)):s(t,n,l,e),o()})).catch((()=>Promise.reject()));return o()}}function ED(e,t){return new self.Request(e.url,t)}class ID extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}}const TD=/\s/,AD={newCue(e,t,n,r){const s=[];let i,a,o,l,c;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(i=r.rows[h],o=!0,l=0,c="",!i.isEmpty()){var u;for(let e=0;e<i.chars.length;e++)TD.test(i.chars[e].uchar)&&o?l++:(c+=i.chars[e].uchar,o=!1);i.cueStartTime=t,t===n&&(n+=1e-4),l>=16?l--:l++;const r=jP(c.trim()),f=WP(t,n,r);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new d(t,n,r),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>wR(e,t)))),s}},CD=yC(yC({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:bD,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new rP(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(SC.FRAG_LOADING,this.onFragLoading,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.FRAG_LOADING,this.onFragLoading,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var n;const r=t.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const n=this.hls.config,{total:r,bwEstimate:s}=t.stats;wC(r)&&wC(s)&&(this.lastLevelLoadSec=8*r/s),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:n}=this,{autoLevelEnabled:r,media:s}=n;if(!e||!s)return;const i=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=i-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||0===e.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const c=n.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const h=c.len/u;if(h>=2*o/u)return;const f=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=n,v=m[e.level],b=a.total||Math.max(a.loaded,Math.round(o*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*a.loaded/g));const S=p?1e3*a.loaded/w:0,E=S?(b-a.loaded)/S:8*b/g+d/1e3;if(E<=h)return;const I=S?8*S:g;let T,A=Number.POSITIVE_INFINITY;for(T=e.level-1;T>y;T--){const e=m[T].maxBitrate;if(A=this.getTimeToLoadFrag(d/1e3,I,o*e,!m[T].details),A<h)break}A>=E||A>10*o||(n.nextLoadLevel=T,p?this.bwEstimator.sample(l-Math.min(d,f),a.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),RC.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${h.toFixed(3)} s\n Estimated load time for current fragment: ${E.toFixed(3)} s\n Estimated load time for down switch fragment: ${A.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${wC(g)?(g/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${T}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),n.trigger(SC.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:n}){const r=n?n.stats:t.stats;if(t.type===fR&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const e=n?n.duration:t.duration,s=this.hls.levels[t.level],i=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:a},s.realBitrate=Math.round(8*i/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(SC.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:n,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:n.stats;if(s.aborted)return;if(this.ignoreFragment(n))return;const i=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(i,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),n.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==fR||"initSegment"===e.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(-1!==e&&!t.canEstimate())return e;let n=this.getNextABRAutoLevel();if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,n)&&t[e].loadError<=t[n].loadError)return e}return-1!==e&&(n=Math.min(e,n)),n}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:n}=this,{maxAutoLevel:r,config:s,minAutoLevel:i,media:a}=n,o=t?t.duration:e?e.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,d=n.mainForwardBufferInfo,u=(d?d.len:0)/l;let h=this.findBestLevel(c,i,r,u,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;RC.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!u){const e=this.bitrateTestDelay;if(e){f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-e,RC.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),p=g=1}}return h=this.findBestLevel(c,i,r,u+f,p,g),Math.max(h,0)}findBestLevel(e,t,n,r,s,i){var a;const{fragCurrent:o,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:d}=this.hls,u=d[c],h=!(null==u||null==(a=u.details)||!a.live),f=null==u?void 0:u.codecSet,p=l?l.duration:o?o.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let a=n;a>=t;a--){const t=d[a];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(a,m),y=Math.max(a,y));continue}-1!==y&&RC.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${d[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const n=t.details,o=(l?null==n?void 0:n.partTarget:null==n?void 0:n.averagetargetduration)||p;let v;v=a<=c?s*e:i*e;const b=d[a].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*o,void 0===n);if(RC.trace(`[abr] level:${a} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${o.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!wC(w)||h&&!this.bitrateTestDelay||w<r))return a}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;RC.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(SC.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{RC.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{RC.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&RC.error(`Media element src was set while attaching MediaSource (${t} > ${e.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.BUFFER_RESET,this.onBufferReset,this),e.on(SC.BUFFER_APPENDING,this.onBufferAppending,this),e.on(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.on(SC.BUFFER_EOS,this.onBufferEos,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(SC.FRAG_PARSED,this.onFragParsed,this),e.on(SC.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.BUFFER_RESET,this.onBufferReset,this),e.off(SC.BUFFER_APPENDING,this.onBufferAppending,this),e.off(SC.BUFFER_CODECS,this.onBufferCodecs,this),e.off(SC.BUFFER_EOS,this.onBufferEos,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(SC.FRAG_PARSED,this.onFragParsed,this),e.off(SC.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new cP(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,RC.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const n=this.media=t.media;if(n&&dP){const e=this.mediaSource=new dP;e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),n.src=self.URL.createObjectURL(e),this._objectUrl=n.src,n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:n}=this;if(t){if(RC.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){RC.warn(`[buffer-controller]: onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),e.src===n?(e.removeAttribute("src"),e.load()):RC.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(SC.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(t){RC.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}})),this._initSourceBuffer()}onBufferCodecs(e,t){const n=this.getSourceBufferTypes().length;Object.keys(t).forEach((e=>{if(n){const n=this.tracks[e];if(n&&"function"==typeof n.buffer.changeType){const{id:r,codec:s,levelCodec:i,container:a,metadata:o}=t[e],l=(n.levelCodec||n.codec).replace(uP,"$1"),c=(i||s).replace(uP,"$1");if(l!==c){const t=`${a};codecs=${i||s}`;this.appendChangeType(e,t),RC.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:n.buffer,codec:s,container:a,levelCodec:i,metadata:o,id:r}}}}else this.pendingTracks[e]=t[e]})),n||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:n}=this,r={execute:()=>{const r=this.sourceBuffer[e];r&&(RC.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{RC.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}};n.append(r,e)}onBufferAppending(e,t){const{hls:n,operationQueue:r,tracks:s}=this,{data:i,type:a,frag:o,part:l,chunkMeta:c}=t,d=c.buffering[a],u=self.performance.now();d.start=u;const h=o.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=u),f&&0===f.start&&(f.start=u);const p=s.audio;let g=!1;"audio"===a&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=o.start,y={execute:()=>{if(d.executeStart=self.performance.now(),g){const e=this.sourceBuffer[a];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(RC.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===h.first&&(h.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,n={};for(const e in t)n[e]=AO.getBuffered(t[e]);this.appendError=0,this.hls.trigger(SC.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:n})},onError:e=>{RC.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,e);const t={type:EC.MEDIA_ERROR,parent:o.type,details:IC.BUFFER_APPEND_ERROR,frag:o,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=IC.BUFFER_FULL_ERROR:(this.appendError++,t.details=IC.BUFFER_APPEND_ERROR,this.appendError>n.config.appendErrorMaxRetry&&(RC.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),n.trigger(SC.ERROR,t)}};r.append(y,a)}onBufferFlushing(e,t){const{operationQueue:n}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(SC.BUFFER_FLUSHED,{type:e})},onError:t=>{RC.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?n.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{n.append(r(e),e)}))}onFragParsed(e,t){const{frag:n,part:r}=t,s=[],i=r?r.elementaryStreams:n.elementaryStreams;i[FC]?s.push("audiovideo"):(i[MC]&&s.push("audio"),i[UC]&&s.push("video"));0===s.length&&RC.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers((()=>{const e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:n.stats;this.hls.trigger(SC.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})}),s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){const n=this.getSourceBufferTypes().reduce(((e,n)=>{const r=this.sourceBuffer[n];return!r||t.type&&t.type!==n||(r.ending=!0,r.ended||(r.ended=!0,RC.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0);n&&(RC.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(RC.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&RC.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:n,sourceBuffer:r}=this;if(!n||null===t)return;const s=this.getSourceBufferTypes();if(!s.length)return;const i=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(!wC(i)||i<0)return;const a=n.currentTime,o=t.levelTargetDuration,l=Math.max(i,o),c=Math.floor(a/o)*o-l;s.forEach((n=>{const s=r[n];if(s){const r=AO.getBuffered(s);if(r.length>0&&c>r.start(0)){if(e.trigger(SC.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(SC.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&r.end(r.length-1)-a<2*o)return void RC.info(`[buffer-controller]: Cannot flush ${n} back buffer while SourceBuffer is in ended state`);e.trigger(SC.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:n})}}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:n,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,i=n.duration,a=wC(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(RC.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>i||!wC(i))&&(RC.log(`[buffer-controller]: Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){const t=this.mediaSource,n=e.fragments;if(n.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,n[0].start),s=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:n}=this,r=Object.keys(n).length;if(r&&!e||2===r){this.createSourceBuffers(n),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(SC.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){const s=e[r];if(!s)throw Error(`source buffer exists for track ${r}, however track does not`);const i=s.levelCodec||s.codec,a=`${s.container};codecs=${i}`;RC.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const e=t[r]=n.addSourceBuffer(a),o=r;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.tracks[r]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){RC.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const n=new Error(`${e} SourceBuffer error`);RC.error(`[buffer-controller]: ${n}`,t),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.BUFFER_APPENDING_ERROR,error:n,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(t)}removeExecutor(e,t,n){const{media:r,mediaSource:s,operationQueue:i,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return RC.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=wC(r.duration)?r.duration:1/0,c=wC(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(n,l,c);u>d&&!o.ending?(o.ended=!1,RC.log(`[buffer-controller]: Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:n,sourceBuffer:r}=this,s=r[t];if(!s)return RC.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return RC.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:n}=this,r=t.map((e=>n.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||n.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,n){const r=this.sourceBuffer[e];if(!r)return;const s=n.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:iD,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=RC.log.bind(RC,"[info]:"),this.warn=RC.warn.bind(RC,"[warning]:"),this.error=RC.error.bind(RC,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(SC.ERROR,this.onError,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(SC.ERROR,this.onError,this),e.off(SC.ERROR,this.onErrorOut,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(null==e?void 0:e.type)===fR?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var n,r;if(t.fatal)return;const s=this.hls,i=t.context;switch(t.details){case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case IC.FRAG_PARSING_ERROR:if(null!=(n=t.frag)&&n.gap)return void(t.errorAction={action:ZR,flags:nO});case IC.FRAG_GAP:case IC.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=eO);case IC.LEVEL_EMPTY_ERROR:case IC.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===fR?t.level:s.loadLevel;t.details===IC.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case IC.LEVEL_LOAD_ERROR:case IC.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case IC.AUDIO_TRACK_LOAD_ERROR:case IC.AUDIO_TRACK_LOAD_TIMEOUT:case IC.SUBTITLE_LOAD_ERROR:case IC.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===uR&&i.groupId===e.audioGroupId||i.type===hR&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=eO,void(t.errorAction.flags=rO)}return;case IC.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],n=null==e?void 0:e.attrs["HDCP-LEVEL"];n&&(t.errorAction={action:eO,flags:sO,hdcpLevel:n})}return;case IC.BUFFER_ADD_CODEC_ERROR:case IC.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case IC.INTERNAL_EXCEPTION:case IC.BUFFER_APPENDING_ERROR:case IC.BUFFER_APPEND_ERROR:case IC.BUFFER_FULL_ERROR:case IC.LEVEL_SWITCH_ERROR:case IC.BUFFER_STALLED_ERROR:case IC.BUFFER_SEEK_OVER_HOLE:case IC.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:ZR,flags:nO})}if(t.type===EC.KEY_SYSTEM_ERROR){const e=this.getVariantLevelIndex(t.frag);return t.levelRetry=!1,void(t.errorAction=this.getLevelSwitchAction(t,e))}}getPlaylistRetryOrSwitchAction(e,t){var n;const r=WR(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(n=e.response)?void 0:n.code;if(YR(r,s,GR(e),i))return{action:tO,flags:nO,retryConfig:r,retryCount:s};const a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,a=WR(e.details.startsWith("key")?i:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){var l;e.details!==IC.FRAG_GAP&&r.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(YR(a,o,GR(e),t))return{action:tO,flags:nO,retryConfig:a,retryCount:o}}const c=this.getLevelSwitchAction(e,n);return a&&(c.retryConfig=a,c.retryCount=o),c}getLevelSwitchAction(e,t){const n=this.hls;null==t&&(t=n.loadLevel);const r=this.hls.levels[t];if(r&&(r.loadError++,n.autoLevelEnabled)){var s,i;let t=-1;const{levels:a,loadLevel:o,minAutoLevel:l,maxAutoLevel:c}=n,d=null==(s=e.frag)?void 0:s.type,{type:u,groupId:h}=null!=(i=e.context)?i:{};for(let n=a.length;n--;){const s=(n+o)%a.length;if(s!==o&&s>=l&&s<=c&&0===a[s].loadError){const n=a[s];if(e.details===IC.FRAG_GAP&&e.frag){const t=a[s].details;if(t){const n=zR(e.frag,t.fragments,e.frag.start);if(null!=n&&n.gap)continue}}else{if(u===uR&&h===n.audioGroupId||u===hR&&h===n.textGroupId)continue;if(d===pR&&r.audioGroupId===n.audioGroupId||d===gR&&r.textGroupId===n.textGroupId)continue}t=s;break}}if(t>-1&&n.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:eO,flags:nO,nextAutoLevel:t}}return{action:eO,flags:rO}}onErrorOut(e,t){var n;switch(null==(n=t.errorAction)?void 0:n.action){case ZR:break;case eO:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===IC.FRAG_GAP||(t.fatal=!0)}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,n=e.errorAction;if(!n)return;const{flags:r,hdcpLevel:s,nextAutoLevel:i}=n;switch(r){case nO:this.switchLevel(e,i);break;case rO:n.resolved||(n.resolved=this.redundantFailover(e));break;case sO:s&&(t.maxHdcpLevel=PR[PR.indexOf(s)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}n.resolved||this.switchLevel(e,i)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:n}=this,r=e.parent===fR?e.level:t.loadLevel,s=t.levels[r],i=s.url.length,a=e.frag?e.frag.urlId:s.urlId;s.urlId!==a||e.frag&&!s.details||this.penalizeRendition(s,e);for(let o=1;o<i;o++){const l=(a+o)%i,c=n[l];if(!c||iO(c,e,n[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${i}: "${s.url[l]}" after ${e.details}`),this.playlistError=0,t.levels.forEach((e=>{e.urlId=l})),t.nextLoadLevel=r,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:n}=this,r=n[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(t),r.details=e.details,n[e.urlId]=r}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const n=this.hls.config;if(n.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,n){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=n-this.lastDroppedFrames,i=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(SC.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:n}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*i){let e=o.currentLevel;RC.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(SC.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:e_,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:AD,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends QO{constructor(e,t,n){super(e,t,n,"[subtitle-stream-controller]",gR),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.ERROR,this.onError,this),e.on(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(SC.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(SC.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.ERROR,this.onError,this),e.off(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(SC.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(SC.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=NO,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:n,success:r}=t;if(this.fragPrevious=n,this.state=NO,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const a=n.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){i=s[e];break}const o=n.start+n.duration;i?i.end=o:(i={start:a,end:o},s.push(i)),this.fragmentTracker.fragBuffered(n)}onBufferFlushing(e,t){const{startOffset:n,endOffset:r}=t;if(0===n&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let n=0;n<t.length;)if(t[n].end<=e)t.shift();else{if(!(t[n].start<e))break;t[n].start=e,n++}})),this.fragmentTracker.removeFragmentsInRange(n,e,gR)}}onFragBuffered(e,t){var n;this.loadedmetadata||t.frag.type!==fR||null!=(n=this.media)&&n.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const n=t.frag;(null==n?void 0:n.type)===gR&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==FO&&(this.state=NO))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){iP(this.levels,t)?this.levels=t.map((e=>new UR(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new UR(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,gR),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const n=this.levels[this.currentTrackId];null!=n&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var n;const{details:r,id:s}=t,{currentTrackId:i,levels:a}=this;if(!a.length)return;const o=a[i];if(s>=a.length||s!==i||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(n=o.details)&&n.live){const e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;const t=e.fragments[0];o.details?(l=this.alignPlaylists(r,o.details),0===l&&t&&(l=t.start,$R(r,l))):r.hasProgramDateTime&&e.hasProgramDateTime?(PO(r,e),l=r.fragments[0].start):t&&(l=t.start,$R(r,l))}if(o.details=r,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(o.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===NO){zR(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:n}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r&&r.key&&r.iv&&"AES-128"===r.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((n=>{const r=performance.now();s.trigger(SC.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=NO}))}}doTick(){if(this.media){if(this.state===NO){const{currentTrackId:e,levels:t}=this,n=t[e];if(!t.length||!n||!n.details)return;const{config:r}=this,s=this.getLoadPosition(),i=AO.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=i,l=this.getFwdBufferInfo(this.media,fR),c=n.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const d=c.fragments,u=d.length,h=c.edge;let f=null;const p=this.fragPrevious;if(a<h){const e=r.maxFragLookUpTolerance,t=a>h-e?0:e;f=zR(p,d,Math.max(d[0].start,a),t),!f&&p&&p.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=d[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===uO&&(f=e)}this.fragmentTracker.getState(f)===uO&&this.loadFragment(f,n,a)}}else this.state=NO}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,n){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,n))}get mediaBufferTimeRanges(){return new oP(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends aO{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(SC.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);lP(this.media.textTracks).forEach((e=>{SR(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:n,details:r}=t,{trackId:s}=this,i=this.tracksInGroup[s];if(!i)return void this.warn(`Invalid subtitle track id ${n}`);const a=i.details;i.details=t.details,this.log(`subtitle track ${n} loaded [${r.startSN}-${r.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.textGroupIds)return;const n=t.textGroupIds[t.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==n){const e=this.tracks.filter((e=>!n||e.groupId===n));this.tracksInGroup=e;const t=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=n||null;const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n}" group-id`),this.hls.trigger(SC.SUBTITLE_TRACKS_UPDATED,s),-1!==t&&this.setSubtitleTrack(t,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||e===r.name))return r.id}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===hR&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const n=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(SC.SUBTITLE_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:n}=this;if(!t)return;const r=lP(t.textTracks),s=r.filter((e=>e.groupId===this.groupId));if(-1===e)[].slice.call(r).forEach((e=>{e.mode="disabled"}));else{const e=s[n];e&&(e.mode="disabled")}const i=s[e];i&&(i.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var n;const r=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(-1===e||null!=(n=r[e])&&n.details)||e<-1||e>=r.length)return;this.clearTimer();const s=r[e];if(this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:"")),this.trackId=e,s){const{id:e,groupId:n="",name:r,type:i,url:a}=s;this.hls.trigger(SC.SUBTITLE_TRACK_SWITCH,{id:e,groupId:n,name:r,type:i,url:a});const o=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(o)}else this.hls.trigger(SC.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=lP(this.media.textTracks);for(let n=0;n<t.length;n++)if("hidden"===t[n].mode)e=n;else if("showing"===t[n].mode){e=n;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}},timelineController:class{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const e=new PP(this,"textTrack1"),t=new PP(this,"textTrack2"),n=new PP(this,"textTrack3"),r=new PP(this,"textTrack4");this.cea608Parser1=new RP(1,e,t),this.cea608Parser2=new RP(3,n,r)}e.on(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(SC.FRAG_LOADING,this.onFragLoading,this),e.on(SC.FRAG_LOADED,this.onFragLoaded,this),e.on(SC.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(SC.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(SC.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(SC.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(SC.FRAG_LOADING,this.onFragLoading,this),e.off(SC.FRAG_LOADED,this.onFragLoaded,this),e.off(SC.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(SC.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(SC.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(SC.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,n,r,s){let i=!1;for(let e=s.length;e--;){const r=s[e],d=(a=r[0],o=r[1],l=t,c=n,Math.min(o,c)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),i=!0,d/(n-t)>.5))return}var a,o,l,c;if(i||s.push([t,n]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,n,r)}else{const s=this.Cues.newCue(null,t,n,r);this.hls.trigger(SC.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s}){const{unparsedVttFrags:i}=this;"main"===n&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),i.length&&(this.unparsedVttFrags=[],i.forEach((e=>{this.onFragLoaded(SC.FRAG_LOADED,e)})))}getExistingTrack(e){const{media:t}=this;if(t)for(let n=0;n<t.textTracks.length;n++){const r=t.textTracks[n];if(r[e])return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:n,media:r}=this,{label:s,languageCode:i}=t[e],a=this.getExistingTrack(e);if(a)n[e]=a,SR(n[e]),bR(n[e],r);else{const t=this.createTextTrack("captions",s,i);t&&(t[e]=!0,n[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const n={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(SC.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,n){const r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{SR(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)SR(t[e])}onSubtitleTracksUpdated(e,t){const n=t.subtitleTracks||[],r=n.some((e=>e.textCodec===VP));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(iP(this.tracks,n))return void(this.tracks=n);if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const e=this.media?this.media.textTracks:null;this.tracks.forEach(((t,n)=>{let r;if(e&&n<e.length){let n=null;for(let r=0;r<e.length;r++)if(sD(e[r],t)){n=e[r];break}n&&(r=n)}if(r)SR(r);else{const e=this._captionsOrSubtitlesFromCharacteristics(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&(r.groupId=t.groupId,this.textTracks.push(r))}))}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(SC.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),n=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&n)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:n,cea608Parser2:r,lastSn:s,lastPartIndex:i}=this;if(this.enabled&&n&&r&&t.frag.type===fR){var a,o;const e=t.frag.sn,l=null!=(a=null==t||null==(o=t.part)?void 0:o.index)?a:-1;e===s+1||e===s&&l===i+1||(n.reset(),r.reset()),this.lastSn=e,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:n,payload:r}=t;if(n.type===gR)if(r.byteLength){const e=n.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[n.level],s=this.vttCCs;s[n.cc]||(s[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===VP?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const n=this.hls;JP(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),n.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{RC.log(`Failed to parse IMSC1: ${t}`),n.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:n,payload:r}=e,{initPTS:s,unparsedVttFrags:i}=this,a=s.length-1;if(!s[n.cc]&&-1===a)return void i.push(e);const o=this.hls;HP(null!=(t=n.initSegment)&&t.data?D_(n.initSegment.data,new Uint8Array(r)):r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,(e=>{this._appendCues(e,n.level),o.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?i.push(e):this._fallbackToIMSC1(n,r),RC.log(`Failed to parse VTT cue: ${t}`),s&&a>n.cc||o.trigger(SC.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})}))}_fallbackToIMSC1(e,t){const n=this.tracks[e.level];n.textCodec||JP(t,this.initPTS[e.cc],(()=>{n.textCodec=VP,this._parseIMSC1(e,t)}),(()=>{n.textCodec="wvtt"}))}_appendCues(e,t){const n=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||"disabled"===n.mode)return;e.forEach((e=>wR(n,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;n.trigger(SC.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:n}=t;n.type===gR&&this.onFragLoaded(SC.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:n,cea608Parser2:r}=this;if(!this.enabled||!n||!r)return;const{frag:s,samples:i}=t;if(s.type!==fR||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){const s=this.extractCea608Data(t);n.addData(i[e].pts,s[0]),r.addData(i[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:s}){const{media:i}=this;if(i&&!(i.currentTime<n)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((r=>ER(e[r],t,n)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((n=>ER(e[n],t,r)))}}}extractCea608Data(e){const t=[[],[]],n=31&e[0];let r=2;for(let s=0;s<n;s++){const n=e[r++],s=127&e[r++],i=127&e[r++];if(0===s&&0===i)continue;if(0!=(4&n)){const e=3&n;0!==e&&1!==e||(t[e].push(s),t[e].push(i))}}return t}},audioStreamController:class extends QO{constructor(e,t,n){super(e,t,n,"[audio-stream-controller]",pR),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.on(SC.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(SC.ERROR,this.onError,this),e.on(SC.BUFFER_RESET,this.onBufferReset,this),e.on(SC.BUFFER_CREATED,this.onBufferCreated,this),e.on(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(SC.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(SC.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(SC.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.LEVEL_LOADED,this.onLevelLoaded,this),e.off(SC.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(SC.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(SC.ERROR,this.onError,this),e.off(SC.BUFFER_RESET,this.onBufferReset,this),e.off(SC.BUFFER_CREATED,this.onBufferCreated,this),e.off(SC.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(SC.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(SC.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s}){if("main"===n){const e=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${r}`),this.videoTrackCC=e,this.state===VO&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=FO);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=NO):(this.loadedmetadata=!1,this.state=qO),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case NO:this.doTickIdle();break;case qO:{var e;const{levels:t,trackId:n}=this,r=null==t||null==(e=t[n])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=VO}break}case $O:{var t;const e=performance.now(),n=this.retryDate;(!n||e>=n||null!=(t=this.media)&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=NO);break}case VO:{const e=this.waitingData;if(e){const{frag:t,part:n,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=jO;const e={frag:t,part:n,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),n=AO.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);JR(n.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${n.end} is needed`),this.clearWaitingFragment())}}else this.state=NO}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=NO)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:n,trackId:r}=this,s=e.config;if(null==t||!t[r])return;if(!n&&(this.startFragRequested||!s.startFragPrefetch))return;const i=t[r],a=i.details;if(!a||a.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(a))return void(this.state=qO);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,MC,pR));const l=this.getFwdBufferInfo(o,pR);if(null===l)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return e.trigger(SC.BUFFER_EOS,{type:"audio"}),void(this.state=WO);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,fR),h=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(h>=f&&!d)return;const p=a.fragments[0].start;let g=l.end;if(d&&n){const e=this.getLoadPosition();c&&d.attrs!==c.attrs&&(g=e),a.PTSKnown&&e<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}let m=this.getNextFragment(g,a),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,a,l,fR,f)),!m)return void(this.bufferFlushed=!0);const v=u&&m.start>u.end+a.targetduration;if(v||(null==u||!u.len)&&l.len){const e=this.getAppendedFrag(m.start,fR);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===u.len),v&&!y||y&&l.nextStart&&l.nextStart<e.end)return}this.loadFragment(m,i,g)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new UR(e)))}onAudioTrackSwitching(e,t){const n=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?this.setInterval(100):this.resetTransmuxer(),n?(this.switchingTrack=t,this.state=NO):(this.switchingTrack=null,this.bufferedTrack=t,this.state=FO),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(SC.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var n;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:r}=this,{details:s,id:i}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${i}`);this.log(`Track ${i} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[i];let o=0;if(s.live||null!=(n=a.details)&&n.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(PO(s,e),o=s.fragments[0].start):o=this.alignPlaylists(s,a.details)}a.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(a.details,o),this.state!==qO||this.waitForCdnTuneIn(s)||(this.state=NO),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:n,part:r,payload:s}=e,{config:i,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const c=l.details;if(!c)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(n.start);const d=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Zk(this.hls,pR,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[n.cc],f=null==(t=n.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=r?r.index:-1,i=-1!==t,a=new CO(n.level,n.sn,n.stats.chunkCount,s.byteLength,t,i);u.push(s,f,d,"",n,r,c.totalduration,e,a,h)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:n,part:r,cache:new sP,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=VO}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:n,part:r}=t;if(n.type===pR)if(this.fragContextChanged(n))this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==n.sn){this.fragPrevious=n;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(SC.AUDIO_TRACK_SWITCHED,yC({},e)))}this.fragBufferedComplete(n,r)}else if(!this.loadedmetadata&&n.type===fR){const e=this.videoBuffer||this.media;if(e){AO.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var n;if(t.fatal)this.state=HO;else switch(t.details){case IC.FRAG_GAP:case IC.FRAG_PARSING_ERROR:case IC.FRAG_DECRYPT_ERROR:case IC.FRAG_LOAD_ERROR:case IC.FRAG_LOAD_TIMEOUT:case IC.KEY_LOAD_ERROR:case IC.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(pR,t);break;case IC.AUDIO_TRACK_LOAD_ERROR:case IC.AUDIO_TRACK_LOAD_TIMEOUT:case IC.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==qO||(null==(n=t.context)?void 0:n.type)!==uR||(this.state=NO);break;case IC.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case IC.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===MC&&(this.bufferFlushed=!0,this.state===WO&&(this.state=NO))}_handleTransmuxComplete(e){var t;const n="audio",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{details:d}=c,{audio:u,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(o)&&d){if(this.state=KO,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;this._bufferInitSegment(p.tracks,e,i),r.trigger(SC.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:p.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=u;l&&(l.elementaryStreams[MC]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(MC,e,t,n,r),this.bufferFragmentData(u,o,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=bC({id:n,frag:o,details:d},f);r.trigger(SC.FRAG_PARSING_METADATA,e)}if(h){const e=bC({id:n,frag:o,details:d},h);r.trigger(SC.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,n){if(this.state!==KO)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.levelCodec=r.codec,r.id="audio",this.log(`Init audio buffer, container:${r.container}, codecs[parsed]=[${r.codec}]`),this.hls.trigger(SC.BUFFER_CODECS,e);const s=r.initSegment;if(null!=s&&s.byteLength){const e={type:"audio",frag:t,part:null,chunkMeta:n,parent:t.type,data:s};this.hls.trigger(SC.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||r===uO||r===fO)?"initSegment"===e.sn?this._loadInitSegment(e,t):null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=VO):(this.startFragRequested=!0,super.loadFragment(e,t,n)):this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:n,bufferedTrack:r}=this,s=null==r?void 0:r.attrs,i=e.attrs;n&&s&&(s.CHANNELS!==i.CHANNELS||s.NAME!==i.NAME||s.LANGUAGE!==i.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(SC.AUDIO_TRACK_SWITCHED,yC({},e))}},audioTrackController:class extends aO{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.LEVEL_LOADING,this.onLevelLoading,this),e.on(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.LEVEL_LOADING,this.onLevelLoading,this),e.off(SC.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(SC.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(SC.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:n,groupId:r,details:s}=t,i=this.tracksInGroup[n];if(!i||i.groupId!==r)return void this.warn(`Track with id:${n} and group:${r} not found in active group ${i.groupId}`);const a=i.details;i.details=t.details,this.log(`audio-track ${n} "${i.name}" lang:${i.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.audioGroupIds)return;const n=t.audioGroupIds[t.urlId];if(this.groupId!==n){this.groupId=n||null;const e=this.tracks.filter((e=>!n||e.groupId===n));this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),this.tracksInGroup=e;const t={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group:${n}`),this.hls.trigger(SC.AUDIO_TRACKS_UPDATED,t),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&t.context.type===uR&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const n=this.currentTrack;t[this.trackId];const r=t[e],{groupId:s,name:i}=r;if(this.log(`Switching to audio-track ${e} "${i}" lang:${r.lang} group:${s}`),this.trackId=e,this.currentTrack=r,this.selectDefaultTrack=!1,this.hls.trigger(SC.AUDIO_TRACK_SWITCHING,yC({},r)),r.details&&!r.details.live)return;const a=this.switchParams(r.url,null==n?void 0:n.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==t)this.setAudioTrack(t);else{const t=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(SC.ERROR,{type:EC.MEDIA_ERROR,details:IC.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if(!this.selectDefaultTrack||r.default){if(!e||void 0!==e.attrs["STABLE-RENDITION-ID"]&&e.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"])return r.id;if(e.name===r.name&&e.lang===r.lang)return r.id}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const n=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${n} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(SC.AUDIO_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:e||null})}}},emeController:oD,cmcdController:gD,contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=RC.log.bind(RC,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.on(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.on(SC.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(SC.MANIFEST_LOADING,this.onManifestLoading,this),e.off(SC.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(SC.MANIFEST_PARSED,this.onManifestParsed,this),e.off(SC.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:n}=t;null!==n&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:n}=t;if((null==n?void 0:n.action)===eO&&n.flags===rO){let e=this.pathwayPriority;const t=this.pathwayId;this.penalizedPathways[t]||(this.penalizedPathways[t]=performance.now()),!e&&this.levels&&(e=this.levels.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),n.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach((e=>{r-n[e]>3e5&&delete n[e]}));for(let r=0;r<e.length;r++){const s=e[r];if(n[s])continue;if(s===this.pathwayId)return;const i=this.hls.nextLoadLevel,a=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(SC.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=i);break}}}clonePathways(e){const t=this.levels;if(!t)return;const n={},r={};e.forEach((e=>{const{ID:s,"BASE-ID":i,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(i).map((e=>{const t=bC({},e);t.details=void 0,t.url=yD(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a);const i=new PC(e.attrs);i["PATHWAY-ID"]=s;const o=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;o&&(n[i.AUDIO]=o,i.AUDIO=o),l&&(r[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new UR(t);return cO(c,"audio",o),cO(c,"text",l),c}));t.push(...o),mD(this.audioTracks,n,a,s),mD(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,n=t.loader;let r;this.loader&&this.loader.destroy(),this.loader=new n(t);try{r=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==r.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:r.href},i=t.steeringManifestLoadPolicy.default,a=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,n,s)=>{this.log(`Loaded steering manifest: "${r}"`);const i=e.data;if(1!==i.VERSION)return void this.log(`Steering VERSION ${i.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=i.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=i;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||n.url),o&&this.clonePathways(o),l&&this.updatePathwayPriority(l)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function _D(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(_D):Object.keys(e).reduce(((t,n)=>(t[n]=_D(e[n]),t)),{}):e}function RD(e){const t=e.loader;if(t!==SD&&t!==bD)RC.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=SD,e.progressive=!0,e.enableSoftwareAES=!0,RC.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class OD{static get version(){return"1.4.10"}static isSupported(){return function(){const e=H_();if(!e)return!1;const t=zO(),n=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!n&&!!r}()}static get Events(){return SC}static get ErrorTypes(){return EC}static get ErrorDetails(){return IC}static get DefaultConfig(){return OD.defaultConfig?OD.defaultConfig:CD}static set DefaultConfig(e){OD.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Jk,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function(e,t){if(self.console&&!0===e||"object"==typeof e){_C(e,"debug","log","info","warn","error");try{CC.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){CC=AC}}else CC=AC}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=_D(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],a=[];r.forEach((r=>{const o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&i){a.push(o);const e=n[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&RC.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),yC(yC({},n),t)}(OD.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&RD(t);const{abrController:n,bufferController:r,capLevelController:s,errorController:i,fpsController:a}=t,o=new i(this),l=this.abrController=new n(this),c=this.bufferController=new r(this),d=this.capLevelController=new s(this),u=new a(this),h=new vR(this),f=new OR(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new lO(this,g),y=new gO(this),v=new IO(this.config),b=this.streamController=new tP(this,y,v);d.setStreamController(b),u.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const S=[l,c,d,u,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const E=t.audioStreamController;E&&w.push(new E(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const I=t.subtitleStreamController;I&&w.push(new I(this,y,v)),this.createController(t.timelineController,S),v.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(kR,S),this.coreComponents=S,w.push(o);const T=o.onErrorOut;"function"==typeof T&&this.on(SC.ERROR,T,o)}createController(e,t){if(e){const n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){RC.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(SC.ERROR,{type:EC.OTHER_ERROR,details:IC.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){RC.log("destroy"),this.trigger(SC.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){RC.log("attachMedia"),this._media=e,this.trigger(SC.MEDIA_ATTACHING,{media:e})}detachMedia(){RC.log("detachMedia"),this.trigger(SC.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,n=this.url,r=this.url=gC.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});RC.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(SC.MANIFEST_LOADING,{url:e})}startLoad(e=-1){RC.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){RC.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){RC.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){RC.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){RC.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){RC.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){RC.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){RC.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){RC.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(RC.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){PR.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this;let r;if(r=-1===t&&e&&e.length?e.length-1:t,n)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=n)return t}return r}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}OD.defaultConfig=void 0;class kD{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const s=e();if(s.length)try{const n=(new Date).toISOString(),i=await xb({timestamp:n,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const a={signature:i.signature,nonceStr:i.nonceStr,timestamp:n,streams:s},o=Ye();await o.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||r()}catch(e){return s.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let PD=null;class DD{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=PD||(PD=new kD,PD),this._usageCollector.registerStream(e.id),this._sessionId=String(Rf.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(cE((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var LD=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!OD.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await HA(t),{watcherUrl:r,status:s,recordings:i=[],resolution:a}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const o=document.createElement("video");o.id=t,o.controls=!0;const l=new OD;if(l.attachMedia(o),"recorded"!==s){let{url:e}=r.hls;e=e.replace("http:","https:"),l.loadSource(e)}else{const e=i.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");o.src=e.mp4.url}return new DD(o,a,t).registerEvents(),o}});const xD=e=>{const t=(e=>{var t;const n=Ye(),r=new Date,s=r.getTime()+31536e6,i=new Date(s).toISOString();let a=null===(t=tt(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return a||(a={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:i,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Ff({storyTargets:[a]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Ff(t),t},MD=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const i=new FileReader;i.readAsDataURL(s),i.onload=()=>r(xD(n?Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,videoFileId:{original:void 0},fileData:null==i?void 0:i.result})}):Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:null==i?void 0:i.result})})))}return r(xD(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},UD=async e=>{const t=Ye();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=hT(n.data);t.cache&&Ff(r),nt(["story-sync-state",e.targetId],"synced"),Ut("local.story.created",r);const s=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:s}},FD=async({targetId:e,targetType:t})=>{var n,r;if(!tt(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await zE(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await Iw(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}nt(["storyTarget","get",e],s)}},ND=e=>e?tt(["story","get",e]):{data:void 0,cachedAt:void 0},BD=async(e,t=!1)=>{var n,r,s;const i=Ye();let a;if(i.log("story/deleteStory",e),i.cache&&(a=ND(e),null==a?void 0:a.data)){const{data:i}=a;if(Ut("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},i),{isDeleted:!0})]}),"synced"!==i.syncState){t?it(["story","get",e]):nt(["story","get",e],Object.assign(Object.assign({},a.data),{isDeleted:!0}));const r=null===(n=et(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===i.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));nt(["story-expire",a.data.targetId],e.toISOString())}else it(["story-expire",a.data.targetId]);return!0}const o=null===(r=tt(["storyTarget","get",i.targetId]))||void 0===r?void 0:r.data,l=null===(s=et(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===i.targetId&&!0!==e.data.isDeleted));let c;l&&l.length>0&&(c=null==l?void 0:l.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),o&&nt(["storyTarget","get",i.targetId],Object.assign(Object.assign({},o),{lastStoryExpiresAt:c}))}return(await i.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},jD=e=>{const t=Ye(),n=[Mt(t,"onStoryUpdated","story.updated",(async t=>{const n=hT(t);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},$D=e=>{const t=Ye(),n=[Mt(t,"onStoryUpdated","local.story.updated",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},qD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Bf(t,["reactions"]),s=hT(r),i=dS("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Ff(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},KD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Ff({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},GD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Bf(t,["reactions"]),s=hT(r),i=dS("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Ff(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},WD=e=>{const t=Ye(),n=[Mt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Ff({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},HD=e=>{e.forEach((e=>{const t=tt(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||nt(["story-expire",e.targetId],n.toISOString())}))},VD=e=>{e.forEach((e=>{nt(["story-reference",e.storyId],e.referenceId)}))},YD=async({targetType:e,targetId:t,options:n})=>{const r=Ye();r.log("story/getActiveStoriesByTarget");const s=r.cache&&Date.now(),i=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),a=hT(i.data);return r.cache&&(Ff(a),HD(a.stories),VD(a.stories)),{data:a.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},QD=e=>{const t=Ye(),n=[Mt(t,"onStoryCreated","story.created",(async t=>{const n=hT(t,!0);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},zD=e=>{const t=Ye(),n=[Mt(t,"onStoryCreated","local.story.created",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},JD=e=>{const t=Ye(),n=[Mt(t,"onStoryDeleted","story.deleted",(async t=>{const n=hT(t);Ff(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},XD=e=>{const t=Ye(),n=[Mt(t,"onStoryDeleted","local.story.deleted",(async t=>{Ff(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ZD=e=>{const t=Ye();return Mt(t,"onStoryError","local.story.error",(async t=>{Ff(t),e(t.stories)}))},eL=e=>t=>e((e=>t(e[0]))),tL=async e=>{const t=Ye();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Ff(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class nL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),r=hT(e);t.cache&&(Ff(r,{cachedAt:n}),HD(r.stories),VD(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=tt(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],nt(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rL extends Ov{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class sL extends kv{constructor(e,t){const n=Tv(e),r=["story-target-ids","collection",n],s=new rL(e);super(s,n,r,t),this.query=e,this.queryStreamController=new nL(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>tt(["story","get",e]))).filter(Boolean).map((e=>gw.story(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:void 0,data:i,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(bt):r.sort(St)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QD,action:"onCreate"},{fn:jD,action:"onUpdate"},{fn:JD,action:"onDelete"},{fn:ZD,action:"onError"}])}}const iL=(e,t)=>{var n,r;const s=null===(n=tt(e))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];nt(e,Object.assign(Object.assign({},s),{data:[...new Set([...i,...t])]}))};class aL extends _v{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=s}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Ff(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?nt(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):iL(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&iL(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oL extends Av{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:s="unseen"}=e,i=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:r,token:t});if(null===(n=i.paging)||void 0===n?void 0:n.next)return i;if("smart"!==s)return i;if("seen"===this.smartFilterState)return i;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:r});return l=a,{categories:(o=i).categories.concat(l.categories),communities:o.communities.concat(l.communities),communityUsers:o.communityUsers.concat(l.communityUsers),files:o.files.concat(l.files),storyTargets:o.storyTargets.concat(l.storyTargets),users:o.users.concat(l.users),paging:l.paging};var o,l}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class lL extends kv{constructor(e,t){const n=Tv(e),r=["story-global-feed","collection",n],s=new oL(e);super(s,n,r,t),this.query=e,this.queryStreamController=new aL(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=Bf(Kv(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const i=s.data,a=et(["storyTarget"]);a&&(null==a?void 0:a.length)>0&&(null==a||a.forEach((({key:e})=>{s.data.includes(e[2])||i.push(e[2])})));let o=i.map((e=>tt(["storyTarget","get",e]))).filter(Boolean).map((e=>gw.storyTarget(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o).filter((({localSortingDate:e})=>!!e)).map((e=>Bf(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(wt);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(wt)||[],r=t.unseen.sort(wt)||[],s=t.seen.sort(wt)||[];return n.concat(r,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:QD,action:"onCreate"},{fn:jD,action:"onUpdate"},{fn:JD,action:"onDelete"},{fn:zD,action:"onCreate"},{fn:$D,action:"onUpdate"},{fn:XD,action:"onDelete"},{fn:ZD,action:"onError"}])}}var cL=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},s="fit",i=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Of(),dataType:"image",items:i,targetType:e,targetId:t,metadata:r};const o=new Date;nt(["story-sync-state",t],"syncing"),nt(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),MD({payload:a,formData:n},(e=>{Ut("local.story.created",e)}));try{const{data:r}=await Gw(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:s}=r[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:s})}),FD({targetId:t,targetType:e}),MD({payload:a,formData:n},(e=>{Ut("local.story.created",e)}));const i=await UD(a);return i.data?Object.assign(Object.assign({},i),{data:gw.story(i.data)}):i}catch(e){throw nt(["story-sync-state",t],"error"),MD({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n},(e=>{Ut("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Of(),dataType:"video",items:s,targetType:e,targetId:t,metadata:r};const a=new Date;nt(["story-sync-state",t],"syncing"),nt(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),FD({targetId:t,targetType:e}),MD({payload:i,formData:n,isVideo:!0},(e=>{Ut("local.story.created",e)}));try{const{data:e}=await Kw(n,m.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:t,videoFileId:{original:t}})}),MD({payload:i,formData:n,isVideo:!0},(e=>{Ut("local.story.created",e)}));const r=await UD(i);return r.data?Object.assign(Object.assign({},r),{data:gw.story(r.data)}):r}catch(e){throw nt(["story-sync-state",t],"error"),MD({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Ut("local.story.error",e)})),e}},hardDeleteStory:async e=>await BD(e,!0),softDeleteStory:async e=>await BD(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Ye(),s=[],i=["story-target","collection",e],a=Date.now();n(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),r||console.log(Y);const o=t=>{var n,r;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",i=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===i?t.sort(bt):t.sort(St):"asc"===i?t.sort(Et):t.sort(It)},l=e=>{var n;const r=e.data.map((e=>{const t=ND(e);if(null==t?void 0:t.data)return gw.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=o(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=o(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=o(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},c=(t,n,r=!1,s=!1,a=!1)=>{var o;const c=tt(i),d={loading:s,error:a,params:{page:void 0},data:(null==c?void 0:c.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(Je("story")):[...new Set([...d.data,...t.map(Je("story"))])];const u=null===(o=et(["story","get"]))||void 0===o?void 0:o.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Je("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),nt(i,d.data),l(d)},d=e=>t=>{c(t,e)};return(t=>{const n=Be(YD,e);$e(n,(({data:e,error:n,loading:r})=>{c(e,"fetch",t,r,n)}))})(!0),s.push(QD(d("onCreate")),jD(d("onUpdate")),JD(d("onDelete")),qD(d("onReactionAdded")),GD(d("onReactionRemoved")),ZD(d("onError")),zD(d("onCreate")),$D(d("onUpdate")),XD(d("onDelete")),KD(d("onReactionAdded")),WD(d("onReactionRemoved")),(e=>{const t=Ye();return Mt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=tt(i);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};l(n)})),(()=>it(i))),()=>{n(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Nv(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:gw.story(e.data)})):t(e)}),"storyId",fT,[eL(jD),eL(JD),eL(qD),eL(GD),eL(ZD),eL($D),eL(XD),eL(KD),eL(WD)]),getTargetById:(e,t)=>Nv(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:gw.storyTarget(e.data[0])})):t(e)}),"query",(e=>tL([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Ye(),s=[],i=["storyTargets","collection",e],a=Date.now();n(`getTargetsByTargetIds(tmpid: ${a}) > listen`),r||console.log(Y);const o=(e,n=!1,r=!1,s=!1)=>{const a=tt(i),o={loading:r,error:s,params:{page:void 0},data:[]};e&&(o.data=n?e.map(Je("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(Je("storyTarget"))])]),nt(i,o.data),(e=>{var n;const r=e.data.map((e=>{const t=tt(["storyTarget","get",e]);if(null==t?void 0:t.data)return gw.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(o)};return(t=>{const n=Be(tL,e);$e(n,(({data:e,error:n,loading:r})=>{o(e,t,r,n)}))})(!0),s.push((()=>it(i))),()=>{n(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const o=new sL(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:s,userId:i}=Ye();s||console.log(Y);const a=Date.now();r(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const o=new lL(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{it(c)})),()=>{r(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});const dL=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),uL=e=>Object.assign({},e);var hL=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(dL),r=t.advertisers.map(uL);return Ff({ads:n,advertisers:r,files:t.files}),nt(["ad","setting"],t.settings),{ads:n.map(gw.ad),settings:t.settings}}});const fL=async()=>{const e=Ye();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];nt(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};fL.locally=()=>{var e;const t=Ye();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=tt(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const pL=e=>{const t=Ye(),n=[Mt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class gL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class mL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.notificationTrayItems.map(Je("notificationTrayItem"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Je("notificationTrayItem"))])]}))}}}const yL=e=>{const t=e.users.map(fp);return Object.assign(Object.assign({},e),{users:t})};class vL extends kv{constructor(e,t){const n=Tv(e),r=["notificationTrayItem","collection",n];super(new gL(e),n,r,t),this.query=e,this.queryStreamController=new mL(this.query,this.cacheKey,this.notifyChange.bind(this),yL),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["notificationTrayItem","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.notificationTray);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var bL=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Rt();return Nv(t,e,"userId",fL,[pL],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Hf(e.lastTraySeenAt)>Hf(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getNotificationTrayItems(tmpid: ${i}) > listen`);const a=new vL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getNotificationTrayItems(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ye();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=tt(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const s=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();nt(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Ut("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Ye();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=tt(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,i={userId:n.userId,lastTraySeenAt:r.lastSeenAt},a=Object.assign(Object.assign({},s),i),o=n.cache&&Date.now();return n.cache&&nt(["notificationTraySeen","get",n.userId],a,{cachedAt:o}),Ut("local.notificationTraySeen.updated",i),{data:r,cachedAt:o}},onNotificationTraySeenUpdated:pL});class wL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:s})}),a=i.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==a?void 0:a.length)>0&&await QE(a),i}}class SL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.invitations.map(Je("invitation"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Je("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===lb.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===lb.OnLocalInvitationCreated){const e=Ye(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===lb.OnLocalInvitationCanceled&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class EL extends kv{constructor(e,t){const n=Tv(e),r=["invitation","collection",n];super(new wL(e),n,r,t),this.query=e,this.queryStreamController=new SL(this.query,this.cacheKey,this.notifyChange.bind(this),ib),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ub,action:lb.OnLocalInvitationCreated},{fn:hb,action:lb.OnLocalInvitationUpdated},{fn:fb,action:lb.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>tt(["invitation","get",e]))).filter(Pv).map((({data:e})=>ab(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?bt:St)();return t=t.sort(n),t}}var IL=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ye();n.log("invitation/cancelInvitation",e);const{data:r}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=tt(["invitation","get",e]))||void 0===t?void 0:t.data;return Nf("invitation",e),s&&Ut("local.invitation.canceled",[s]),r.success},onLocalInvitationCreated:ub,onLocalInvitationUpdated:hb,onLocalInvitationCanceled:fb,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMyCommunityInvitations: (tmpid: ${i}) > listen`);const a=new EL(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{it(l)})),()=>{r(`getInvitations (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=$t();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ye(),{targetId:s,targetType:i}=e,a=Date.now();r(`observeInvitations(tmpid: ${a}) > listen for ${i}: ${s}`);const o=[],l=n=>{const r=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(gw.invitation))})(r)};return"room"===i&&(o.push(EA(l)),o.push(TA(l)),o.push(AA(l)),o.push(CA(l))),()=>{r(`getInvitations(tmpid: ${a}) > dispose for ${i}: ${s}`),o.forEach((e=>e()))}}});const TL=e=>{const t=Ye();return Mt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var AL=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r,roomId:s})=>{const i=Ye();if(i.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:r,roomId:s}),!r&&!s)throw new Ke("You have to specify either streamId or roomId",800110,"error");const a=xm(),o={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:r,occurredAt:(new Date).toISOString()};return a.createLiveReaction(o),Ut("local.liveReaction.created",[Object.assign(Object.assign({},o),{userId:i.userId,referenceId:e})]),!0},onLiveReactionCreated:TL,getReactions:(e,t)=>{const{_id:n}=Rt();if(!n)throw new Ke("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Ye();r(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],i=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(TL(i)),s.push((e=>{const t=Ye();return Mt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(i)),()=>{s.forEach((e=>e()))}}});const CL=async e=>{const t=Ye();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),r=Qb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:r.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(ie(null==n?void 0:n.code)){const r=CL.locally(e);if(!r)throw n;const s=Object.assign(Object.assign({},null==r?void 0:r.data),{isDeleted:!0});st(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};CL.locally=e=>{const t=Ye();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=tt(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class _L extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class RL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.events.map(Je("event"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Je("event"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Zb.OnEventCreated&&(r.data=[...new Set([t.eventId,...r.data])]),e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class OL extends kv{constructor(e,t){const n=Tv(e),r=["event","collection",n];super(new _L(e),n,r,t),this.query=e,this.queryStreamController=new RL(this.query,this.cacheKey,this.notifyChange.bind(this),Qb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:nw,action:Zb.OnEventCreated},{fn:rw,action:Zb.OnEventUpdated},{fn:sw,action:Zb.OnEventDeleted},{fn:iw,action:Zb.OnEventCreated},{fn:aw,action:Zb.OnEventUpdated},{fn:ow,action:Zb.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["event","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.event);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class kL extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class PL extends _v{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),r=n.cache&&Date.now();n.cache&&Ff(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.events.map(Je("event"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Je("event"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=tt(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Zb.OnEventCreated){if(Ye().userId!==t.userId)return;r.data=[...new Set([t.eventId,...r.data])]}e===Zb.OnEventDeleted&&(r.data=r.data.filter((e=>e!==t.eventId))),nt(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class DL extends kv{constructor(e,t){const n=Tv(e),r=["event","collection",n];super(new kL(e),n,r,t),this.query=e,this.queryStreamController=new PL(this.query,this.cacheKey,this.notifyChange.bind(this),Qb),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:nw,action:Zb.OnEventCreated},{fn:rw,action:Zb.OnEventUpdated},{fn:sw,action:Zb.OnEventDeleted},{fn:iw,action:Zb.OnEventCreated},{fn:aw,action:Zb.OnEventUpdated},{fn:ow,action:Zb.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=(null!==(s=i.data.map((e=>tt(["event","get",e]))).filter(Pv).map((({data:e})=>e)))&&void 0!==s?s:[]).map(gw.event);(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var LL=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ye();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Ut("local.event.created",n);const r=Qb(n),s=t.cache&&Date.now();return t.cache&&Ff(r,{cachedAt:s}),{data:pw(r.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ye();n.log("event/updateEvent",e,t);const{data:r}=await n.http.put(`/api/v1/events/${e}`,t);Ut("local.event.updated",r);const s=Qb(r),i=n.cache&&Date.now();return n.cache&&Ff(s,{cachedAt:i}),{data:pw(s.events.find((t=>t.eventId===e))),cachedAt:i}},deleteEvent:async e=>{const t=Ye();t.log("event/deleteEvent",e);const n=await CL(e);await t.http.delete(`/api/v1/events/${e}`);const r=Object.assign(Object.assign({},n.data),{isDeleted:!0});st(["event","get",e],r),Ut("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[r]})},onEventCreated:nw,onEventUpdated:rw,onEventDeleted:sw,onLocalEventCreated:iw,onLocalEventUpdated:aw,onLocalEventDeleted:ow,onRSVPCreated:lw,onRSVPUpdated:cw,onLocalRSVPCreated:dw,onLocalRSVPUpdated:uw,getEvent:(e,t)=>Nv(e,t,"eventId",CL,[rw,sw,aw,ow],{callbackDataSelector:e=>e?pw(e):e}),getEvents:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getEvents: (tmpid: ${i}) > listen`);const a=new OL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getEvents (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`getMyEvents: (tmpid: ${i}) > listen`);const a=new DL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`getMyEvents (tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},getRSVPs:fw});const xL=async e=>{const t=Ye();let n;t.log("product/getProduct",e),Xf("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw ie(null==t?void 0:t.code)&&Nf("product",e),t}const r=t.cache&&Date.now();t.cache&&Ff(n,{cachedAt:r});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:r}};xL.locally=e=>{const t=Ye();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=tt(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ML extends Av{async getRequest(e,t){const{limit:n=W}=e,r=Bf(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},r),{options:s})});return i}}class UL extends _v{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Ff(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)nt(this.cacheKey,{data:e.products.map(Je("product"))});else{const t=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];nt(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Je("product"))])]}))}}}class FL extends kv{constructor(e,t){const n=Tv(e),r=["products","collection",n];super(new ML(e),n,r,t),this.query=e,this.queryStreamController=new UL(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=tt(this.cacheKey))||void 0===e?void 0:e.data)||nt(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=tt(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const a=null!==(s=i.data.map((e=>tt(["product","get",e]))).filter(Pv).map((({data:e})=>e)).map(gw.product))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var NL=Object.freeze({__proto__:null,getProduct:(e,t)=>Nv(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?gw.product(n):n}))}),"productId",xL,[]),searchProducts:(e,t,n)=>{const{log:r,cache:s}=Ye();s||console.log(Y);const i=Date.now();r(`searchProducts(tmpid: ${i}) > listen`);const a=new FL(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>it(l))),()=>{r(`searchProducts(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}}});return e.API_REGIONS=hn,e.AdRepository=hL,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=iT,e.ChannelRepository=VE,e.Client=sv,e.CommentRepository=TT,e.CommunityPostSettingMaps=f,e.CommunityPostSettings=h,e.CommunityRepository=nT,e.ContentFeedType=m,e.DefaultCommunityPostSetting=p,e.EventRepository=LL,e.FeedRepository=zT,e.FileRepository=Ww,e.FileType=a,e.GET_WATCHER_URLS=Sb,e.InvitationRepository=IL,e.LiveReactionRepository=AL,e.LiveStreamPlayer=LD,e.MessageContentType=v,e.MessageRepository=mE,e.PollRepository=hC,e.PostContentType=b,e.PostRepository=WA,e.PostStructureType=w,e.ProductRepository=NL,e.ReactionRepository=BS,e.RoomPresenceRepository=lC,e.RoomRepository=jA,e.StoryRepository=cL,e.StreamRepository=rC,e.SubChannelRepository=IE,e.UserRepository=$w,e.VERSION=G,e.VideoResolution=o,e.VideoSize=c,e.VideoTranscodingStatus=l,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:s}=Ye();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const i=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(i).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(i)),!0)},e.createQuery=Be,e.createReport=async(e,t,n)=>{const r=Ye();return r.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await yw(e,t))({referenceId:t,options:n}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await dp(n);Ff(e)}return Ut("message.flagged",n),!!n})({client:r,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await nS(n);Ff(e)}return Ut("post.flagged",n),!!n})({client:r,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await jS(n);Ff(e)}return Ut("comment.flagged",n),!!n})({client:r,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Pf(),s=Df(),i=Ps(pn("http",t)),{data:a}=await i.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const n=Ye();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Xg(n);Ff(e)}return Ut("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await dp(n);Ff(e)}return Ut("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await nS(n);Ff(e)}return Ut("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await jS(n);Ff(e)}return Ut("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=it,e.enableCache=(e={},t)=>{const n=Ye();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Ct,e.filterByChannelMembership=ct,e.filterByCommunityMembership=ut,e.filterByFeedType=dt,e.filterByPostDataTypes=ht,e.filterByPropEquality=at,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=lt,e.filterBySearchTerm=ft,e.filterByStringComparePartially=ot,e.filterByUntilAt=(e,t,n)=>{const r=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<r)):e.filter((e=>new Date(e.createdAt).valueOf()>r))},e.filterCommentsByBlockUsers=mt,e.filterPostsByBlockUsers=gt,e.getBlockUsersId=pt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Rt();return`${Gt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Kt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Xt,e.getMarkedMessageTopic=Vt,e.getMarkerUserFeedTopic=()=>{const e=Rt();return`${Gt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Wt,e.getMyFollowingsTopic=Ht,e.getNetworkId=Gt,e.getNetworkTopic=Yt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Vw,e.getRoomStreamerTopic=e=>{const t=$t();return`${Gt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=$t();return`${Gt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Qt,e.getSmartFeedMessageTopic=Jt,e.getSmartFeedSubChannelTopic=zt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Rt();return`${Gt(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Kt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=Oe,e.isAfterBeforeRaw=ke,e.isCachable=Fe,e.isFetcher=xe,e.isFresh=Ne,e.isLocal=e=>Fe(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Me,e.isOffline=Ue,e.isPaged=Pe,e.isReportedByMe=async(e,t)=>{const n=Ye();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=r?r:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Re,e.mergeInCache=rt,e.notificationTray=bL,e.onChannelMarkerFetched=Qy,e.onFeedMarkerFetched=e=>{const t=Ye();return Mt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ye();return Mt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Ff(t),e(t.feedMarkers[0])}))},e.onMessageMarked=ev,e.onMessageMarkerFetched=Zy,e.onSubChannelMarkerFetched=zy,e.onSubChannelMarkerUpdated=Jy,e.onUserMarkerFetched=Xy,e.onUserMarkerFetchedLegacy=e=>{const t=Ye();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=tt,e.pushToCache=nt,e.queryCache=et,e.queryOptions=je,e.queryRoles=Hw,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ye();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=$e,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=yt,e.sortByFirstCreated=bt,e.sortByFirstUpdated=Et,e.sortByLastActivity=Tt,e.sortByLastCreated=St,e.sortByLastUpdated=It,e.sortByLocalSortingDate=wt,e.sortByName=vt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Zt,e.toPage=Le,e.toPageRaw=e=>{if(!e)return;const t=JSON.parse(_e(e));return ke(t)?t:void 0},e.toToken=De,e.upsertInCache=st,e.validateUntilAt=At,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Ye();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|