@amityco/ts-sdk-react-native 6.24.1 → 6.24.2-18b8e6d.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.umd.js CHANGED
@@ -1,6 +1,5 @@
1
- var Amity=function(e,t){"use strict";const n=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),r=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),s=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),i=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"}),o=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),a=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),l="ONLY_ADMIN_CAN_POST",c=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),u=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),d=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const h=function(){try{return"v6.24.1-umd"}catch(e){return"__dev__"}}(),f=5,p="cache_then_server",g="For using Live Collection feature you need to enable Cache!",m="Observing unsynced object is not supported by Live Object.",y=1e3,v=864e5,b=6e5,w="dead",E=2e3,S=6e4,C=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),T=e=>JSON.parse(e),k=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>k(e[n],t[n])))),_=e=>[400400,400300].includes(e),I="function"==typeof atob,A="function"==typeof btoa,R="function"==typeof Buffer,L="function"==typeof TextDecoder?new TextDecoder:void 0,D="function"==typeof TextEncoder?new TextEncoder:void 0,O=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),x=(e=>{let t={};return e.forEach(((e,n)=>t[e]=n)),t})(O),P=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,M=String.fromCharCode.bind(String),F="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):(e,t=(e=>e))=>new Uint8Array(Array.prototype.slice.call(e,0).map(t)),U=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),N=A?e=>btoa(e):R?e=>Buffer.from(e,"binary").toString("base64"):e=>{let t,n,r,s,i="";const o=e.length%3;for(let o=0;o<e.length;){if((n=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255||(s=e.charCodeAt(o++))>255)throw new TypeError("invalid character found");t=n<<16|r<<8|s,i+=O[t>>18&63]+O[t>>12&63]+O[t>>6&63]+O[63&t]}return o?i.slice(0,o-3)+"===".substring(o):i},B=R?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let n=0,r=e.length;n<r;n+=4096)t.push(M.apply(null,e.subarray(n,n+4096)));return N(t.join(""))},j=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?M(192|t>>>6)+M(128|63&t):M(224|t>>>12&15)+M(128|t>>>6&63)+M(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return M(240|t>>>18&7)+M(128|t>>>12&63)+M(128|t>>>6&63)+M(128|63&t)},$=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,q=R?e=>Buffer.from(e,"utf8").toString("base64"):D?e=>B(D.encode(e)):e=>N(e.replace($,j)),K=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,G=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return M(55296+(t>>>10))+M(56320+(1023&t));case 3:return M((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return M((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},H=I?e=>atob(U(e)):R?e=>Buffer.from(e,"base64").toString("binary"):e=>{if(e=e.replace(/\s+/g,""),!P.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,n,r,s="";for(let i=0;i<e.length;)t=x[e.charAt(i++)]<<18|x[e.charAt(i++)]<<12|(n=x[e.charAt(i++)])<<6|(r=x[e.charAt(i++)]),s+=64===n?M(t>>16&255):64===r?M(t>>16&255,t>>8&255):M(t>>16&255,t>>8&255,255&t);return s},V=R?e=>F(Buffer.from(e,"base64")):e=>F(H(e),(e=>e.charCodeAt(0))),z=R?e=>Buffer.from(e,"base64").toString("utf8"):L?e=>L.decode(V(e)):e=>H(e).replace(K,G),W=e=>z(U(e.replace(/[-_]/g,(e=>"-"==e?"+":"/")))),Y=e=>["skip"].some((t=>t in e)),Q=e=>["after","before","first","last","limit"].some((t=>t in e)),X=e=>"limit"in e,J=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Z=(e,t)=>{var n;if(!e||!Object.keys(e).length)return;let r={};return"skiplimit"===t?r={skip:null!==(n=e.after)&&void 0!==n?n:0,limit:e.limit}:"afterbefore"===t&&Q(e)?((null==e?void 0:e.before)&&(r=Object.assign(Object.assign({},r),{before:e.before})),(null==e?void 0:e.after)&&(r=Object.assign(Object.assign({},r),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(r=Object.assign(Object.assign({},r),{limit:e.limit}))):"afterbeforeraw"===t&&(r=e),Object.keys(r).length?((e,t=!1)=>t?(e=>e.replace(/=/g,"").replace(/[+\/]/g,(e=>"+"==e?"-":"_")))(q(e)):q(e))(JSON.stringify(r)):void 0},ee=e=>{if(!e)return;const t=JSON.parse(W(e));if(Y(t))return{after:t.skip,limit:t.limit};if(Q(t)){if("before"in t)return{before:t.before,limit:t.last};if("after"in t)return{after:t.after,limit:t.first}}},te=e=>{if(!e)return;const t=JSON.parse(W(e));return X(t)?t:void 0},ne=e=>"locally"in e,re=e=>"optimistically"in e,se=e=>ne(e)||re(e),ie=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),oe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},ae=(e,...t)=>({func:e,args:t}),le=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<S?S:t},ce=({func:e,args:t},n,r=le("cache_then_server"))=>{let s;const{lifeSpan:i}=le("cache_then_server",r.lifeSpan);if(se(e)){try{s=re(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ue(void 0,{origin:"local",loading:!1,error:e}))}const r=ie(s)&&oe(s,i);if(null==n||n(ue(s,{origin:"local",loading:!(ne(e)&&r)})),r)return}else null==n||n(ue(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ue(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ue(void 0,{origin:"server",loading:!1,error:e}))}))};function ue(e,t){return J(e)||ie(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const de={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e})=>e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e},he=e=>de[e],fe={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",follows:"follow",followCounts:"followCount",feeds:"feed"};function pe(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class ge extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,ge)}}class me extends ge{constructor(e,t,n){super(e,t,n)}}class ye extends ge{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ve extends ge{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}let be=null;const we=()=>{if(!be)throw new ge("There is no active client",8e5,"fatal");return be},Ee=e=>{be=e},Se=e=>{const{log:t,cache:n}=we();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=T(t);return k(e,n)})).map((e=>n.data[e]))},Ce=e=>{const{log:t,cache:n}=we();if(!n)return;t("cache/api/pullFromCache",e);const r=C(e);return n.data[r]?n.data[r]:void 0},Te=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const i=C(e);return s.data[i]=Object.assign({key:e,data:t},n),!0},ke=(e,t,n)=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const i=Ce(e);if(!i)return!1;const o="function"==typeof t?t(i.data):Object.assign(Object.assign({},i.data),t);return a=i.data,!("updatedAt"in(l=o)&&"updatedAt"in l&&new Date(l.updatedAt)<new Date(a.updatedAt))&&(Te(e,o,n),!0);var a,l},_e=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Ce(e)?ke(e,t,n):Te(e,t,n)},Ie=(e,t=!1)=>{const{log:n,cache:r}=we();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>T(e))).filter((t=>k(e,t))).map((e=>Ie(e,!0))).every((e=>e));const s=C(e);return s in r.data&&(delete r.data[s],!0)},Ae=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Re=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Le=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,De=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const s=he("channelUsers")({channelId:e.channelPublicId,userId:n}),i=null===(r=Ce(["channelUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?i&&"none"!==i.membership:!i||"none"===i.membership})),Oe=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const s=null===(r=Ce(["feed","get",he("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return s&&s.feedType===t})),xe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const s=he("communityUsers")({communityId:e.communityId,userId:n}),i=null===(r=Ce(["communityUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?i&&"member"===i.communityMembership:!i||"none"!==i.communityMembership})),Pe=(e,t)=>{const n=[];return e.reduce(((e,r)=>{var s;if("text"===r.dataType&&!r.children.length)return e;if(n.includes(r.postId))return e;if((null==t?void 0:t.includes(r.dataType))&&e.push(r),!r.children.length)return e;const i=null===(s=Ce(["post","get",r.children[0]]))||void 0===s?void 0:s.data;return i?n.includes(i.postId)?e:(null==t?void 0:t.includes(null==i?void 0:i.dataType))?(n.push(i.postId),e.push(i),e):e:e}),[])},Me=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},Fe=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,Ue=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ne=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Be=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),je=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),qe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ke=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ge=null;const He=()=>{if(!Ge)throw new ge("Connect client first",8e5,"fatal");return Ge},Ve=e=>{Ge={_id:e._id,userId:e.userId,path:e.path}};let ze,We=[];const Ye=e=>{clearTimeout(ze),We.push(e),ze=setTimeout((()=>{We.forEach((e=>e())),We=[]}),0)},Qe=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired","v3.video-streaming.didRecord","v3.video-streaming.didStart","v3.video-streaming.didStop"],Xe=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Je=()=>{return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map((function(e){e(n)})),(r=e.get("*"))&&r.slice().map((function(e){e(t,n)}))}};var e},Ze=(e,t,n,r)=>{const{log:s,emitter:i}=e,o=Date.now();s(`${t}(tmpid: ${o}) > listen`);const a=(...e)=>{s(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){s(`${t}(tmpid: ${o}) > error`,e)}};return i.on(n,a),()=>{s(`${t}(tmpid: ${o}) > dispose`),i.off(n,a)}},et=(e,t)=>{const{emitter:n}=we();Ye((()=>{n.emit(e,t)}))};let tt,nt;async function rt(){var e;const{mqtt:t,emitter:n,token:r}=we(),s=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",i=He();tt===s&&nt===i._id||(tt=s,nt=i._id,await t.connect({accessToken:tt,userId:nt}),((e,t)=>{Xe.forEach((n=>{e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var st;e.SubscriptionLevels=void 0,(st=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",st.POST="post",st.COMMENT="comment",st.POST_AND_COMMENT="post_and_comment",st.USER="user";const it=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},ot=e=>e.path.split("/user/")[0],at=({path:t},n=e.SubscriptionLevels.USER)=>it(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),lt=({channelId:e,subChannelId:t})=>{const n=He();return`${ot(n)}/marker/channel/${e}/message/${t}`},ct=()=>{const e=He();return`${ot(e)}/marker/user/${e._id}`},ut=()=>ot(He()),dt=()=>{const e=He();return`${ot(e)}/smartfeed/${e._id}/channels`},ht=()=>{const e=He();return`${ot(e)}/smartfeed/${e._id}/messagefeeds`},ft=()=>{const e=He();return`${ot(e)}/smartfeed/${e._id}/messages`};function pt(e,t){const{mqtt:n}=we();return rt(),n.subscribe(e,t)}var gt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function mt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function yt(e){var t=e.default;if("function"==typeof t){var n=function(){return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var vt,bt,wt={exports:{}};function Et(){if(bt)return vt;bt=1;var e=1e3,t=60*e,n=60*t,r=24*n,s=7*r,i=365.25*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}return vt=function(a,l){l=l||{};var c=typeof a;if("string"===c&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var l=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*i;case"weeks":case"week":case"w":return l*s;case"days":case"day":case"d":return l*r;case"hours":case"hour":case"hrs":case"hr":case"h":return l*n;case"minutes":case"minute":case"mins":case"min":case"m":return l*t;case"seconds":case"second":case"secs":case"sec":case"s":return l*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(a);if("number"===c&&isFinite(a))return l.long?function(s){var i=Math.abs(s);if(i>=r)return o(s,i,r,"day");if(i>=n)return o(s,i,n,"hour");if(i>=t)return o(s,i,t,"minute");if(i>=e)return o(s,i,e,"second");return s+" ms"}(a):function(s){var i=Math.abs(s);if(i>=r)return Math.round(s/r)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},vt}var St=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Et(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=St(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(wt,wt.exports);var Ct,Tt=wt.exports;const kt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:_t={}}=kt,It="production"===(null===(Ct=_t.env)||void 0===Ct?void 0:Ct.NODE_ENV),At={EU:"eu",SG:"sg",US:"us"},Rt={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Lt(e,t){return Rt[e].replace("{region}",t)}function Dt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ot}=Object.prototype,{getPrototypeOf:xt}=Object,Pt=(Mt=Object.create(null),e=>{const t=Ot.call(e);return Mt[t]||(Mt[t]=t.slice(8,-1).toLowerCase())});var Mt;const Ft=e=>(e=e.toLowerCase(),t=>Pt(t)===e),Ut=e=>t=>typeof t===e,{isArray:Nt}=Array,Bt=Ut("undefined");const jt=Ft("ArrayBuffer");const $t=Ut("string"),qt=Ut("function"),Kt=Ut("number"),Gt=e=>null!==e&&"object"==typeof e,Ht=e=>{if("object"!==Pt(e))return!1;const t=xt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Vt=Ft("Date"),zt=Ft("File"),Wt=Ft("Blob"),Yt=Ft("FileList"),Qt=Ft("URLSearchParams");function Xt(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,s;if("object"!=typeof e&&(e=[e]),Nt(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(r=0;r<i;r++)o=s[r],t.call(null,e[o],o,e)}}function Jt(e,t){t=t.toLowerCase();const n=Object.keys(e);let r,s=n.length;for(;s-- >0;)if(r=n[s],t===r.toLowerCase())return r;return null}const Zt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,en=e=>!Bt(e)&&e!==Zt;const tn=(nn="undefined"!=typeof Uint8Array&&xt(Uint8Array),e=>nn&&e instanceof nn);var nn;const rn=Ft("HTMLFormElement"),sn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),on=Ft("RegExp"),an=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Xt(n,((n,s)=>{!1!==t(n,s,e)&&(r[s]=n)})),Object.defineProperties(e,r)};var ln={isArray:Nt,isArrayBuffer:jt,isBuffer:function(e){return null!==e&&!Bt(e)&&null!==e.constructor&&!Bt(e.constructor)&&qt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{const t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||Ot.call(e)===t||qt(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&jt(e.buffer),t},isString:$t,isNumber:Kt,isBoolean:e=>!0===e||!1===e,isObject:Gt,isPlainObject:Ht,isUndefined:Bt,isDate:Vt,isFile:zt,isBlob:Wt,isRegExp:on,isFunction:qt,isStream:e=>Gt(e)&&qt(e.pipe),isURLSearchParams:Qt,isTypedArray:tn,isFileList:Yt,forEach:Xt,merge:function e(){const{caseless:t}=en(this)&&this||{},n={},r=(r,s)=>{const i=t&&Jt(n,s)||s;Ht(n[i])&&Ht(r)?n[i]=e(n[i],r):Ht(r)?n[i]=e({},r):Nt(r)?n[i]=r.slice():n[i]=r};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Xt(arguments[e],r);return n},extend:(e,t,n,{allOwnKeys:r}={})=>(Xt(t,((t,r)=>{n&&qt(t)?e[r]=Dt(t,n):e[r]=t}),{allOwnKeys:r}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,r)=>{let s,i,o;const a={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],r&&!r(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&xt(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Pt,kindOfTest:Ft,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(Nt(e))return e;let t=e.length;if(!Kt(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Symbol.iterator]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:rn,hasOwnProperty:sn,hasOwnProp:sn,reduceDescriptors:an,freezeMethods:e=>{an(e,((t,n)=>{if(qt(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];qt(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach((e=>{n[e]=!0}))};return Nt(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:Jt,global:Zt,isContextDefined:en,toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(Gt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const s=Nt(e)?[]:{};return Xt(e,((e,t)=>{const i=n(e,r+1);!Bt(i)&&(s[t]=i)})),t[r]=void 0,s}}return e};return n(e,0)}};function cn(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}ln.inherits(cn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ln.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const un=cn.prototype,dn={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{dn[e]={value:e}})),Object.defineProperties(cn,dn),Object.defineProperty(un,"isAxiosError",{value:!0}),cn.from=(e,t,n,r,s,i)=>{const o=Object.create(un);return ln.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),cn.call(o,e.message,t,n,r,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};var hn="object"==typeof self?self.FormData:window.FormData;function fn(e){return ln.isPlainObject(e)||ln.isArray(e)}function pn(e){return ln.endsWith(e,"[]")?e.slice(0,-2):e}function gn(e,t,n){return e?e.concat(t).map((function(e,t){return e=pn(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const mn=ln.toFlatObject(ln,{},null,(function(e){return/^is[A-Z]/.test(e)}));function yn(e,t,n){if(!ln.isObject(e))throw new TypeError("target must be an object");t=t||new(hn||FormData);const r=(n=ln.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ln.isUndefined(t[e])}))).metaTokens,s=n.visitor||u,i=n.dots,o=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&((l=t)&&ln.isFunction(l.append)&&"FormData"===l[Symbol.toStringTag]&&l[Symbol.iterator]);var l;if(!ln.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ln.isDate(e))return e.toISOString();if(!a&&ln.isBlob(e))throw new cn("Blob is not supported. Use a Buffer instead.");return ln.isArrayBuffer(e)||ln.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,n,s){let a=e;if(e&&!s&&"object"==typeof e)if(ln.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(ln.isArray(e)&&function(e){return ln.isArray(e)&&!e.some(fn)}(e)||ln.isFileList(e)||ln.endsWith(n,"[]")&&(a=ln.toArray(e)))return n=pn(n),a.forEach((function(e,r){!ln.isUndefined(e)&&null!==e&&t.append(!0===o?gn([n],r,i):null===o?n:n+"[]",c(e))})),!1;return!!fn(e)||(t.append(gn(s,n,i),c(e)),!1)}const d=[],h=Object.assign(mn,{defaultVisitor:u,convertValue:c,isVisitable:fn});if(!ln.isObject(e))throw new TypeError("data must be an object");return function e(n,r){if(!ln.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+r.join("."));d.push(n),ln.forEach(n,(function(n,i){!0===(!(ln.isUndefined(n)||null===n)&&s.call(t,n,ln.isString(i)?i.trim():i,r,h))&&e(n,r?r.concat(i):[i])})),d.pop()}}(e),t}function vn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function bn(e,t){this._pairs=[],e&&yn(e,this,t)}const wn=bn.prototype;function En(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Sn(e,t,n){if(!t)return e;const r=n&&n.encode||En,s=n&&n.serialize;let i;if(i=s?s(t,n):ln.isURLSearchParams(t)?t.toString():new bn(t,n).toString(r),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}wn.append=function(e,t){this._pairs.push([e,t])},wn.toString=function(e){const t=e?function(t){return e.call(this,t,vn)}:vn;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Cn{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ln.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Tn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},kn="undefined"!=typeof URLSearchParams?URLSearchParams:bn,_n=FormData;const In=(()=>{let e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&("undefined"!=typeof window&&"undefined"!=typeof document)})(),An="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var Rn={isBrowser:!0,classes:{URLSearchParams:kn,FormData:_n,Blob:Blob},isStandardBrowserEnv:In,isStandardBrowserWebWorkerEnv:An,protocols:["http","https","file","blob","url","data"]};function Ln(e){function t(e,n,r,s){let i=e[s++];const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&ln.isArray(r)?r.length:i,a)return ln.hasOwnProp(r,i)?r[i]=[r[i],n]:r[i]=n,!o;r[i]&&ln.isObject(r[i])||(r[i]=[]);return t(e,n,r[i],s)&&ln.isArray(r[i])&&(r[i]=function(e){const t={},n=Object.keys(e);let r;const s=n.length;let i;for(r=0;r<s;r++)i=n[r],t[i]=e[i];return t}(r[i])),!o}if(ln.isFormData(e)&&ln.isFunction(e.entries)){const n={};return ln.forEachEntry(e,((e,r)=>{t(function(e){return ln.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),r,n,0)})),n}return null}const Dn={"Content-Type":void 0};const On={transitional:Tn,adapter:["xhr","http"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,s=ln.isObject(e);s&&ln.isHTMLForm(e)&&(e=new FormData(e));if(ln.isFormData(e))return r&&r?JSON.stringify(Ln(e)):e;if(ln.isArrayBuffer(e)||ln.isBuffer(e)||ln.isStream(e)||ln.isFile(e)||ln.isBlob(e))return e;if(ln.isArrayBufferView(e))return e.buffer;if(ln.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return yn(e,new Rn.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return Rn.isNode&&ln.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ln.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return yn(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||r?(t.setContentType("application/json",!1),function(e,t,n){if(ln.isString(e))try{return(t||JSON.parse)(e),ln.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||On.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(e&&ln.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw cn.from(e,cn.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Rn.classes.FormData,Blob:Rn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ln.forEach(["delete","get","head"],(function(e){On.headers[e]={}})),ln.forEach(["post","put","patch"],(function(e){On.headers[e]=ln.merge(Dn)}));const xn=ln.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Pn=Symbol("internals");function Mn(e){return e&&String(e).trim().toLowerCase()}function Fn(e){return!1===e||null==e?e:ln.isArray(e)?e.map(Fn):String(e)}function Un(e,t,n,r){return ln.isFunction(r)?r.call(this,t,n):ln.isString(t)?ln.isString(r)?-1!==t.indexOf(r):ln.isRegExp(r)?r.test(t):void 0:void 0}class Nn{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function s(e,t,n){const s=Mn(t);if(!s)throw new Error("header name must be a non-empty string");const i=ln.findKey(r,s);(!i||void 0===r[i]||!0===n||void 0===n&&!1!==r[i])&&(r[i||t]=Fn(e))}const i=(e,t)=>ln.forEach(e,((e,n)=>s(e,n,t)));return ln.isPlainObject(e)||e instanceof this.constructor?i(e,t):ln.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?i((e=>{const t={};let n,r,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),n=e.substring(0,s).trim().toLowerCase(),r=e.substring(s+1).trim(),!n||t[n]&&xn[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)})),t})(e),t):null!=e&&s(t,e,n),this}get(e,t){if(e=Mn(e)){const n=ln.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(ln.isFunction(t))return t.call(this,e,n);if(ln.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Mn(e)){const n=ln.findKey(this,e);return!(!n||t&&!Un(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function s(e){if(e=Mn(e)){const s=ln.findKey(n,e);!s||t&&!Un(0,n[s],s,t)||(delete n[s],r=!0)}}return ln.isArray(e)?e.forEach(s):s(e),r}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,n={};return ln.forEach(this,((r,s)=>{const i=ln.findKey(n,s);if(i)return t[i]=Fn(r),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(s):String(s).trim();o!==s&&delete t[s],t[o]=Fn(r),n[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ln.forEach(this,((n,r)=>{null!=n&&!1!==n&&(t[r]=e&&ln.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach((e=>n.set(e))),n}static accessor(e){const t=(this[Pn]=this[Pn]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=Mn(e);t[r]||(!function(e,t){const n=ln.toCamelCase(" "+t);["get","set","has"].forEach((r=>{Object.defineProperty(e,r+n,{value:function(e,n,s){return this[r].call(this,t,e,n,s)},configurable:!0})}))}(n,e),t[r]=!0)}return ln.isArray(e)?e.forEach(r):r(e),this}}function Bn(e,t){const n=this||On,r=t||n,s=Nn.from(r.headers);let i=r.data;return ln.forEach(e,(function(e){i=e.call(n,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function jn(e){return!(!e||!e.__CANCEL__)}function $n(e,t,n){cn.call(this,null==e?"canceled":e,cn.ERR_CANCELED,t,n),this.name="CanceledError"}Nn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),ln.freezeMethods(Nn.prototype),ln.freezeMethods(Nn),ln.inherits($n,cn,{__CANCEL__:!0});var qn=Rn.isStandardBrowserEnv?{write:function(e,t,n,r,s,i){const o=[];o.push(e+"="+encodeURIComponent(t)),ln.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),ln.isString(r)&&o.push("path="+r),ln.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function Kn(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var Gn=Rn.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let n;function r(n){let r=n;return e&&(t.setAttribute("href",r),r=t.href),t.setAttribute("href",r),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return n=r(window.location.href),function(e){const t=ln.isString(e)?r(e):e;return t.protocol===n.protocol&&t.host===n.host}}():function(){return!0};function Hn(e,t){let n=0;const r=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const l=Date.now(),c=r[o];s||(s=l),n[i]=a,r[i]=l;let u=o,d=0;for(;u!==i;)d+=n[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),l-s<t)return;const h=c&&l-c;return h?Math.round(1e3*d/h):void 0}}(50,250);return s=>{const i=s.loaded,o=s.lengthComputable?s.total:void 0,a=i-n,l=r(a);n=i;const c={loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:l||void 0,estimated:l&&o&&i<=o?(o-i)/l:void 0,event:s};c[t?"download":"upload"]=!0,e(c)}}var Vn="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,n){let r=e.data;const s=Nn.from(e.headers).normalize(),i=e.responseType;let o;function a(){e.cancelToken&&e.cancelToken.unsubscribe(o),e.signal&&e.signal.removeEventListener("abort",o)}ln.isFormData(r)&&(Rn.isStandardBrowserEnv||Rn.isStandardBrowserWebWorkerEnv)&&s.setContentType(!1);let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",n=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.set("Authorization","Basic "+btoa(t+":"+n))}const c=Kn(e.baseURL,e.url);function u(){if(!l)return;const r=Nn.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new cn("Request failed with status code "+n.status,[cn.ERR_BAD_REQUEST,cn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}((function(e){t(e),a()}),(function(e){n(e),a()}),{data:i&&"text"!==i&&"json"!==i?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:r,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),Sn(c,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=u:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(u)},l.onabort=function(){l&&(n(new cn("Request aborted",cn.ECONNABORTED,e,l)),l=null)},l.onerror=function(){n(new cn("Network Error",cn.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const r=e.transitional||Tn;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new cn(t,r.clarifyTimeoutError?cn.ETIMEDOUT:cn.ECONNABORTED,e,l)),l=null},Rn.isStandardBrowserEnv){const t=(e.withCredentials||Gn(c))&&e.xsrfCookieName&&qn.read(e.xsrfCookieName);t&&s.set(e.xsrfHeaderName,t)}void 0===r&&s.setContentType(null),"setRequestHeader"in l&&ln.forEach(s.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),ln.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),i&&"json"!==i&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",Hn(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",Hn(e.onUploadProgress)),(e.cancelToken||e.signal)&&(o=t=>{l&&(n(!t||t.type?new $n(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(o),e.signal&&(e.signal.aborted?o():e.signal.addEventListener("abort",o)));const d=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(c);d&&-1===Rn.protocols.indexOf(d)?n(new cn("Unsupported protocol "+d+":",cn.ERR_BAD_REQUEST,e)):l.send(r||null)}))};const zn={http:null,xhr:Vn};ln.forEach(zn,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));var Wn=e=>{e=ln.isArray(e)?e:[e];const{length:t}=e;let n,r;for(let s=0;s<t&&(n=e[s],!(r=ln.isString(n)?zn[n.toLowerCase()]:n));s++);if(!r){if(!1===r)throw new cn(`Adapter ${n} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(ln.hasOwnProp(zn,n)?`Adapter '${n}' is not available in the build`:`Unknown adapter '${n}'`)}if(!ln.isFunction(r))throw new TypeError("adapter is not a function");return r};function Yn(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new $n(null,e)}function Qn(e){Yn(e),e.headers=Nn.from(e.headers),e.data=Bn.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Wn(e.adapter||On.adapter)(e).then((function(t){return Yn(e),t.data=Bn.call(e,e.transformResponse,t),t.headers=Nn.from(t.headers),t}),(function(t){return jn(t)||(Yn(e),t&&t.response&&(t.response.data=Bn.call(e,e.transformResponse,t.response),t.response.headers=Nn.from(t.response.headers))),Promise.reject(t)}))}const Xn=e=>e instanceof Nn?e.toJSON():e;function Jn(e,t){t=t||{};const n={};function r(e,t,n){return ln.isPlainObject(e)&&ln.isPlainObject(t)?ln.merge.call({caseless:n},e,t):ln.isPlainObject(t)?ln.merge({},t):ln.isArray(t)?t.slice():t}function s(e,t,n){return ln.isUndefined(t)?ln.isUndefined(e)?void 0:r(void 0,e,n):r(e,t,n)}function i(e,t){if(!ln.isUndefined(t))return r(void 0,t)}function o(e,t){return ln.isUndefined(t)?ln.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,s,i){return i in t?r(n,s):i in e?r(void 0,n):void 0}const l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>s(Xn(e),Xn(t),!0)};return ln.forEach(Object.keys(e).concat(Object.keys(t)),(function(r){const i=l[r]||s,o=i(e[r],t[r],r);ln.isUndefined(o)&&i!==a||(n[r]=o)})),n}const Zn="1.2.3",er={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{er[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const tr={};er.transitional=function(e,t,n){function r(e,t){return"[Axios v1.2.3] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,s,i)=>{if(!1===e)throw new cn(r(s," has been removed"+(t?" in "+t:"")),cn.ERR_DEPRECATED);return t&&!tr[s]&&(tr[s]=!0,console.warn(r(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,s,i)}};var nr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new cn("options must be an object",cn.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const i=r[s],o=t[i];if(o){const t=e[i],n=void 0===t||o(t,i,e);if(!0!==n)throw new cn("option "+i+" must be "+n,cn.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new cn("Unknown option "+i,cn.ERR_BAD_OPTION)}},validators:er};const rr=nr.validators;class sr{constructor(e){this.defaults=e,this.interceptors={request:new Cn,response:new Cn}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Jn(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:s}=t;let i;void 0!==n&&nr.assertOptions(n,{silentJSONParsing:rr.transitional(rr.boolean),forcedJSONParsing:rr.transitional(rr.boolean),clarifyTimeoutError:rr.transitional(rr.boolean)},!1),void 0!==r&&nr.assertOptions(r,{encode:rr.function,serialize:rr.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),i=s&&ln.merge(s.common,s[t.method]),i&&ln.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Nn.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const l=[];let c;this.interceptors.response.forEach((function(e){l.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Qn.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,l),u=e.length,c=Promise.resolve(t);d<u;)c=c.then(e[d++],e[d++]);return c}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(e){t.call(this,e);break}}try{c=Qn.call(this,h)}catch(e){return Promise.reject(e)}for(d=0,u=l.length;d<u;)c=c.then(l[d++],l[d++]);return c}getUri(e){return Sn(Kn((e=Jn(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}ln.forEach(["delete","get","head","options"],(function(e){sr.prototype[e]=function(t,n){return this.request(Jn(n||{},{method:e,url:t,data:(n||{}).data}))}})),ln.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,s){return this.request(Jn(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}sr.prototype[e]=t(),sr.prototype[e+"Form"]=t(!0)}));class ir{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const n=this;this.promise.then((e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const r=new Promise((e=>{n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e((function(e,r,s){n.reason||(n.reason=new $n(e,r,s),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new ir((function(t){e=t})),cancel:e}}}const or={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(or).forEach((([e,t])=>{or[t]=e}));const ar=function e(t){const n=new sr(t),r=Dt(sr.prototype.request,n);return ln.extend(r,sr.prototype,n,{allOwnKeys:!0}),ln.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(Jn(t,n))},r}(On);ar.Axios=sr,ar.CanceledError=$n,ar.CancelToken=ir,ar.isCancel=jn,ar.VERSION=Zn,ar.toFormData=yn,ar.AxiosError=cn,ar.Cancel=ar.CanceledError,ar.all=function(e){return Promise.all(e)},ar.spread=function(e){return function(t){return e.apply(null,t)}},ar.isAxiosError=function(e){return ln.isObject(e)&&!0===e.isAxiosError},ar.mergeConfig=Jn,ar.AxiosHeaders=Nn,ar.formToJSON=e=>Ln(ln.isHTMLForm(e)?new FormData(e):e),ar.HttpStatusCode=or,ar.default=ar;var lr={exports:{}};lr.exports=ur;var cr=lr.exports.HttpsAgent=ur;function ur(){}var dr;!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(dr||(dr={}));const hr=new AbortController,fr=e=>{switch(e){case dr.UserGlobalBanned:throw new ge(e,400312,"fatal");case dr.UserDeleted:throw new ge(e,400100,"fatal");case dr.TokenExpired:throw et("tokenExpired","tokenExpired"),new ge(e,800403,"fatal");default:throw new ge("Request Aborted",8e5,"error")}},pr=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=ar.create({baseURL:e,httpAgent:new lr.exports(t),httpsAgent:new cr(t),signal:hr.signal});return n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(hr.abort(),fr(dr.UserGlobalBanned)),r&&(hr.abort(),fr(dr.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(hr.abort(dr.UserDeleted),fr(dr.TokenExpired))}return e})),n.interceptors.response.use((e=>e),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&et("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new ye(e.code);if("error"===e.status)throw new me(e.message,e.code,"error")})(null==r?void 0:r.data),hr.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var gr={exports:{}},mr=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,yr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],vr=function(e){var t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));for(var s=mr.exec(e||""),i={},o=14;o--;)i[yr[o]]=s[o]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i},br={exports:{}},wr={exports:{}},Er=1e3,Sr=6e4,Cr=60*Sr,Tr=24*Cr,kr=365.25*Tr,_r=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*kr;case"days":case"day":case"d":return n*Tr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Cr;case"minutes":case"minute":case"mins":case"min":case"m":return n*Sr;case"seconds":case"second":case"secs":case"sec":case"s":return n*Er;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?function(e){return Ir(e,Tr,"day")||Ir(e,Cr,"hour")||Ir(e,Sr,"minute")||Ir(e,Er,"second")||e+" ms"}(e):function(e){if(e>=Tr)return Math.round(e/Tr)+"d";if(e>=Cr)return Math.round(e/Cr)+"h";if(e>=Sr)return Math.round(e/Sr)+"m";if(e>=Er)return Math.round(e/Er)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ir(e,t,n){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}!function(e,t){function n(e){var n;function s(){if(s.enabled){var e=s,r=+new Date,i=r-(n||r);e.diff=i,e.prev=n,e.curr=r,n=r;for(var o=new Array(arguments.length),a=0;a<o.length;a++)o[a]=arguments[a];o[0]=t.coerce(o[0]),"string"!=typeof o[0]&&o.unshift("%O");var l=0;o[0]=o[0].replace(/%([a-zA-Z%])/g,(function(n,r){if("%%"===n)return n;l++;var s=t.formatters[r];if("function"==typeof s){var i=o[l];n=s.call(e,i),o.splice(l,1),l--}return n})),t.formatArgs.call(e,o);var c=s.log||t.log||console.log.bind(console);c.apply(e,o)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var n,r=0;for(n in e)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]}(e),s.destroy=r,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function r(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=n.debug=n.default=n).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var n;t.save(e),t.names=[],t.skips=[];var r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(n=0;n<t.instances.length;n++){var i=t.instances[n];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=_r,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(wr,wr.exports),function(e,t){function n(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=wr.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return;var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,r)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=n,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(br,br.exports);var Ar=vr,Rr=br.exports("socket.io-client:url"),Lr=function(e,t){var n=e;t=t||"undefined"!=typeof location&&location,null==e&&(e=t.protocol+"//"+t.host);"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?t.protocol+e:t.host+e),/^(https?|wss?):\/\//.test(e)||(Rr("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),Rr("parse %s",e),n=Ar(e));n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443"));n.path=n.path||"/";var r=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port,n.href=n.protocol+"://"+r+(t&&t.port===n.port?"":":"+n.port),n};var Dr={},Or={exports:{}},xr={exports:{}},Pr=1e3,Mr=6e4,Fr=60*Mr,Ur=24*Fr,Nr=365.25*Ur,Br=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*Nr;case"days":case"day":case"d":return n*Ur;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Fr;case"minutes":case"minute":case"mins":case"min":case"m":return n*Mr;case"seconds":case"second":case"secs":case"sec":case"s":return n*Pr;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?function(e){return jr(e,Ur,"day")||jr(e,Fr,"hour")||jr(e,Mr,"minute")||jr(e,Pr,"second")||e+" ms"}(e):function(e){if(e>=Ur)return Math.round(e/Ur)+"d";if(e>=Fr)return Math.round(e/Fr)+"h";if(e>=Mr)return Math.round(e/Mr)+"m";if(e>=Pr)return Math.round(e/Pr)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function jr(e,t,n){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}!function(e,t){function n(e){var n;function s(){if(s.enabled){var e=s,r=+new Date,i=r-(n||r);e.diff=i,e.prev=n,e.curr=r,n=r;for(var o=new Array(arguments.length),a=0;a<o.length;a++)o[a]=arguments[a];o[0]=t.coerce(o[0]),"string"!=typeof o[0]&&o.unshift("%O");var l=0;o[0]=o[0].replace(/%([a-zA-Z%])/g,(function(n,r){if("%%"===n)return n;l++;var s=t.formatters[r];if("function"==typeof s){var i=o[l];n=s.call(e,i),o.splice(l,1),l--}return n})),t.formatArgs.call(e,o);var c=s.log||t.log||console.log.bind(console);c.apply(e,o)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var n,r=0;for(n in e)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]}(e),s.destroy=r,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function r(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=n.debug=n.default=n).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var n;t.save(e),t.names=[],t.skips=[];var r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(n=0;n<t.instances.length;n++){var i=t.instances[n];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Br,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(xr,xr.exports),function(e,t){function n(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=xr.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return;var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,r)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=n,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(Or,Or.exports);var $r={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<r.length;s++)if((n=r[s])===t||n.fn===t){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var s=(n=n.slice(0)).length;r<s;++r)n[r].apply(this,t)}return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}($r);var qr={},Kr={}.toString,Gr=Array.isArray||function(e){return"[object Array]"==Kr.call(e)},Hr=function(e){return Vr&&Buffer.isBuffer(e)||zr&&(e instanceof ArrayBuffer||function(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer}(e))},Vr="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,zr="function"==typeof ArrayBuffer;var Wr=Gr,Yr=Hr,Qr=Object.prototype.toString,Xr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Qr.call(Blob),Jr="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Qr.call(File);function Zr(e,t){if(!e)return e;if(Yr(e)){var n={_placeholder:!0,num:t.length};return t.push(e),n}if(Wr(e)){for(var r=new Array(e.length),s=0;s<e.length;s++)r[s]=Zr(e[s],t);return r}if("object"==typeof e&&!(e instanceof Date)){r={};for(var i in e)r[i]=Zr(e[i],t);return r}return e}function es(e,t){if(!e)return e;if(e&&e._placeholder)return t[e.num];if(Wr(e))for(var n=0;n<e.length;n++)e[n]=es(e[n],t);else if("object"==typeof e)for(var r in e)e[r]=es(e[r],t);return e}qr.deconstructPacket=function(e){var t=[],n=e.data,r=e;return r.data=Zr(n,t),r.attachments=t.length,{packet:r,buffers:t}},qr.reconstructPacket=function(e,t){return e.data=es(e.data,t),e.attachments=void 0,e},qr.removeBlobs=function(e,t){var n=0,r=e;!function e(s,i,o){if(!s)return s;if(Xr&&s instanceof Blob||Jr&&s instanceof File){n++;var a=new FileReader;a.onload=function(){o?o[i]=this.result:r=this.result,--n||t(r)},a.readAsArrayBuffer(s)}else if(Wr(s))for(var l=0;l<s.length;l++)e(s[l],l,s);else if("object"==typeof s&&!Yr(s))for(var c in s)e(s[c],c,s)}(r),n||t(r)},function(e){var t=Or.exports("socket.io-parser"),n=$r.exports,r=qr,s=Gr,i=Hr;function o(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=o,e.Decoder=c;var a=e.ERROR+'"encode error"';function l(n){var r=""+n.type;if(e.BINARY_EVENT!==n.type&&e.BINARY_ACK!==n.type||(r+=n.attachments+"-"),n.nsp&&"/"!==n.nsp&&(r+=n.nsp+","),null!=n.id&&(r+=n.id),null!=n.data){var s=function(e){try{return JSON.stringify(e)}catch(e){return!1}}(n.data);if(!1===s)return a;r+=s}return t("encoded %j as %s",n,r),r}function c(){this.reconstructor=null}function u(e){this.reconPack=e,this.buffers=[]}function d(t){return{type:e.ERROR,data:"parser error: "+t}}o.prototype.encode=function(n,s){(t("encoding packet %j",n),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type)?function(e,t){function n(e){var n=r.deconstructPacket(e),s=l(n.packet),i=n.buffers;i.unshift(s),t(i)}r.removeBlobs(e,n)}(n,s):s([l(n)])},n(c.prototype),c.prototype.add=function(n){var r;if("string"==typeof n)r=function(n){var r=0,i={type:Number(n.charAt(0))};if(null==e.types[i.type])return d("unknown packet type "+i.type);if(e.BINARY_EVENT===i.type||e.BINARY_ACK===i.type){for(var o=r+1;"-"!==n.charAt(++r)&&r!=n.length;);var a=n.substring(o,r);if(a!=Number(a)||"-"!==n.charAt(r))throw new Error("Illegal attachments");i.attachments=Number(a)}if("/"===n.charAt(r+1)){for(o=r+1;++r;){if(","===(c=n.charAt(r)))break;if(r===n.length)break}i.nsp=n.substring(o,r)}else i.nsp="/";var l=n.charAt(r+1);if(""!==l&&Number(l)==l){for(o=r+1;++r;){var c;if(null==(c=n.charAt(r))||Number(c)!=c){--r;break}if(r===n.length)break}i.id=Number(n.substring(o,r+1))}if(n.charAt(++r)){var u=function(e){try{return JSON.parse(e)}catch(e){return!1}}(n.substr(r));if(!(!1!==u&&(i.type===e.ERROR||s(u))))return d("invalid payload");i.data=u}return t("decoded %s as %j",n,i),i}(n),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new u(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!i(n)&&!n.base64)throw new Error("Unknown type: "+n);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(r=this.reconstructor.takeBinaryData(n))&&(this.reconstructor=null,this.emit("decoded",r))}},c.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},u.prototype.takeBinaryData=function(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t=r.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null},u.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}}(Dr);var ts={exports:{}},ns={},rs={exports:{}};try{rs.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){rs.exports=!1}var ss,is,os,as,ls=rs.exports,cs=function(e){var t=e.xdomain,n=e.xscheme,r=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||ls))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!n&&r)return new XDomainRequest}catch(e){}if(!t)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},us={exports:{}},ds={},hs=Object.keys||function(e){var t=[],n=Object.prototype.hasOwnProperty;for(var r in e)n.call(e,r)&&t.push(r);return t};function fs(){if(as)return os;as=1;var e=function(){if(is)return ss;is=1;var e={}.toString;return ss=Array.isArray||function(t){return"[object Array]"==e.call(t)}}(),t=Object.prototype.toString,n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===t.call(Blob),r="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===t.call(File);return os=function t(s){if(!s||"object"!=typeof s)return!1;if(e(s)){for(var i=0,o=s.length;i<o;i++)if(t(s[i]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(s)||"function"==typeof ArrayBuffer&&s instanceof ArrayBuffer||n&&s instanceof Blob||r&&s instanceof File)return!0;if(s.toJSON&&"function"==typeof s.toJSON&&1===arguments.length)return t(s.toJSON(),!0);for(var a in s)if(Object.prototype.hasOwnProperty.call(s,a)&&t(s[a]))return!0;return!1},os}var ps=function(e,t,n){var r=e.byteLength;if(t=t||0,n=n||r,e.slice)return e.slice(t,n);if(t<0&&(t+=r),n<0&&(n+=r),n>r&&(n=r),t>=r||t>=n||0===r)return new ArrayBuffer(0);for(var s=new Uint8Array(e),i=new Uint8Array(n-t),o=t,a=0;o<n;o++,a++)i[a]=s[o];return i.buffer},gs=function(e,t,n){var r=!1;return n=n||ms,s.count=e,0===e?t():s;function s(e,i){if(s.count<=0)throw new Error("after called too many times");--s.count,e?(r=!0,t(e),t=n):0!==s.count||r||t(null,i)}};function ms(){}
2
- /*! https://mths.be/utf8js v2.1.2 by @mathias */var ys,vs,bs,ws=String.fromCharCode;function Es(e){for(var t,n,r=[],s=0,i=e.length;s<i;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<i?56320==(64512&(n=e.charCodeAt(s++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),s--):r.push(t);return r}function Ss(e,t){if(e>=55296&&e<=57343){if(t)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function Cs(e,t){return ws(e>>t&63|128)}function Ts(e,t){if(0==(4294967168&e))return ws(e);var n="";return 0==(4294965248&e)?n=ws(e>>6&31|192):0==(4294901760&e)?(Ss(e,t)||(e=65533),n=ws(e>>12&15|224),n+=Cs(e,6)):0==(4292870144&e)&&(n=ws(e>>18&7|240),n+=Cs(e,12),n+=Cs(e,6)),n+=ws(63&e|128)}function ks(){if(bs>=vs)throw Error("Invalid byte index");var e=255&ys[bs];if(bs++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function _s(e){var t,n;if(bs>vs)throw Error("Invalid byte index");if(bs==vs)return!1;if(t=255&ys[bs],bs++,0==(128&t))return t;if(192==(224&t)){if((n=(31&t)<<6|ks())>=128)return n;throw Error("Invalid continuation byte")}if(224==(240&t)){if((n=(15&t)<<12|ks()<<6|ks())>=2048)return Ss(n,e)?n:65533;throw Error("Invalid continuation byte")}if(240==(248&t)&&(n=(7&t)<<18|ks()<<12|ks()<<6|ks())>=65536&&n<=1114111)return n;throw Error("Invalid UTF-8 detected")}var Is,As,Rs,Ls={version:"2.1.2",encode:function(e,t){for(var n=!1!==(t=t||{}).strict,r=Es(e),s=r.length,i=-1,o="";++i<s;)o+=Ts(r[i],n);return o},decode:function(e,t){var n=!1!==(t=t||{}).strict;ys=Es(e),vs=ys.length,bs=0;for(var r,s=[];!1!==(r=_s(n));)s.push(r);return function(e){for(var t,n=e.length,r=-1,s="";++r<n;)(t=e[r])>65535&&(s+=ws((t-=65536)>>>10&1023|55296),t=56320|1023&t),s+=ws(t);return s}(s)}},Ds={};function Os(){if(Rs)return As;Rs=1;var e=void 0!==e?e:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,t=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),n=t&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),r=e&&e.prototype.append&&e.prototype.getBlob;function s(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var n=new Uint8Array(e.byteLength);n.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=n.buffer}return t}return e}))}function i(t,n){n=n||{};var r=new e;return s(t).forEach((function(e){r.append(e)})),n.type?r.getBlob(n.type):r.getBlob()}function o(e,t){return new Blob(s(e),t||{})}return"undefined"!=typeof Blob&&(i.prototype=Blob.prototype,o.prototype=Blob.prototype),As=t?n?Blob:o:r?i:void 0}!function(e){var t,n=hs,r=fs(),s=ps,i=gs,o=Ls;"undefined"!=typeof ArrayBuffer&&(Is||(Is=1,function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=new Uint8Array(256),n=0;n<e.length;n++)t[e.charCodeAt(n)]=n;Ds.encode=function(t){var n,r=new Uint8Array(t),s=r.length,i="";for(n=0;n<s;n+=3)i+=e[r[n]>>2],i+=e[(3&r[n])<<4|r[n+1]>>4],i+=e[(15&r[n+1])<<2|r[n+2]>>6],i+=e[63&r[n+2]];return s%3==2?i=i.substring(0,i.length-1)+"=":s%3==1&&(i=i.substring(0,i.length-2)+"=="),i},Ds.decode=function(e){var n,r,s,i,o,a=.75*e.length,l=e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var u=new ArrayBuffer(a),d=new Uint8Array(u);for(n=0;n<l;n+=4)r=t[e.charCodeAt(n)],s=t[e.charCodeAt(n+1)],i=t[e.charCodeAt(n+2)],o=t[e.charCodeAt(n+3)],d[c++]=r<<2|s>>4,d[c++]=(15&s)<<4|i>>2,d[c++]=(3&i)<<6|63&o;return u}}()),t=Ds);var a="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),l="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),c=a||l;e.protocol=3;var u=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},d=n(u),h={type:"error",data:"parser error"},f=Os();function p(e,t,n){for(var r=new Array(e.length),s=i(e.length,n),o=function(e,n,s){t(n,(function(t,n){r[e]=n,s(t,r)}))},a=0;a<e.length;a++)o(a,e[a],s)}e.encodePacket=function(t,n,r,s){"function"==typeof n&&(s=n,n=!1),"function"==typeof r&&(s=r,r=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var s=t.data,i=new Uint8Array(s),o=new Uint8Array(1+s.byteLength);o[0]=u[t.type];for(var a=0;a<i.length;a++)o[a+1]=i[a];return r(o.buffer)}(t,n,s);if(void 0!==f&&i instanceof f)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);if(c)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var s=new FileReader;return s.onload=function(){e.encodePacket({type:t.type,data:s.result},n,!0,r)},s.readAsArrayBuffer(t.data)}(t,n,r);var s=new Uint8Array(1);s[0]=u[t.type];var i=new f([s.buffer,t.data]);return r(i)}(t,n,s);if(i&&i.base64)return function(t,n){var r="b"+e.packets[t.type]+t.data.data;return n(r)}(t,s);var a=u[t.type];return void 0!==t.data&&(a+=r?o.encode(String(t.data),{strict:!1}):String(t.data)),s(""+a)},e.encodeBase64Packet=function(t,n){var r,s="b"+e.packets[t.type];if(void 0!==f&&t.data instanceof f){var i=new FileReader;return i.onload=function(){var e=i.result.split(",")[1];n(s+e)},i.readAsDataURL(t.data)}try{r=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var o=new Uint8Array(t.data),a=new Array(o.length),l=0;l<o.length;l++)a[l]=o[l];r=String.fromCharCode.apply(null,a)}return s+=btoa(r),n(s)},e.decodePacket=function(t,n,r){if(void 0===t)return h;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),n);if(r&&!1===(t=function(e){try{e=o.decode(e,{strict:!1})}catch(e){return!1}return e}(t)))return h;var i=t.charAt(0);return Number(i)==i&&d[i]?t.length>1?{type:d[i],data:t.substring(1)}:{type:d[i]}:h}i=new Uint8Array(t)[0];var a=s(t,1);return f&&"blob"===n&&(a=new f([a])),{type:d[i],data:a}},e.decodeBase64Packet=function(e,n){var r=d[e.charAt(0)];if(!t)return{type:r,data:{base64:!0,data:e.substr(1)}};var s=t.decode(e.substr(1));return"blob"===n&&f&&(s=new f([s])),{type:r,data:s}},e.encodePayload=function(t,n,s){"function"==typeof n&&(s=n,n=null);var i=r(t);if(n&&i)return f&&!c?e.encodePayloadAsBlob(t,s):e.encodePayloadAsArrayBuffer(t,s);if(!t.length)return s("0:");p(t,(function(t,r){e.encodePacket(t,!!i&&n,!1,(function(e){r(null,function(e){return e.length+":"+e}(e))}))}),(function(e,t){return s(t.join(""))}))},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);var s;if("function"==typeof n&&(r=n,n=null),""===t)return r(h,0,1);for(var i,o,a="",l=0,c=t.length;l<c;l++){var u=t.charAt(l);if(":"===u){if(""===a||a!=(i=Number(a)))return r(h,0,1);if(a!=(o=t.substr(l+1,i)).length)return r(h,0,1);if(o.length){if(s=e.decodePacket(o,n,!1),h.type===s.type&&h.data===s.data)return r(h,0,1);if(!1===r(s,l+i,c))return}l+=i,a=""}else a+=u}return""!==a?r(h,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,n){if(!t.length)return n(new ArrayBuffer(0));p(t,(function(t,n){e.encodePacket(t,!0,!0,(function(e){return n(null,e)}))}),(function(e,t){var r=t.reduce((function(e,t){var n;return e+(n="string"==typeof t?t.length:t.byteLength).toString().length+n+2}),0),s=new Uint8Array(r),i=0;return t.forEach((function(e){var t="string"==typeof e,n=e;if(t){for(var r=new Uint8Array(e.length),o=0;o<e.length;o++)r[o]=e.charCodeAt(o);n=r.buffer}s[i++]=t?0:1;var a=n.byteLength.toString();for(o=0;o<a.length;o++)s[i++]=parseInt(a[o]);s[i++]=255;for(r=new Uint8Array(n),o=0;o<r.length;o++)s[i++]=r[o]})),n(s.buffer)}))},e.encodePayloadAsBlob=function(t,n){p(t,(function(t,n){e.encodePacket(t,!0,!0,(function(e){var t=new Uint8Array(1);if(t[0]=1,"string"==typeof e){for(var r=new Uint8Array(e.length),s=0;s<e.length;s++)r[s]=e.charCodeAt(s);e=r.buffer,t[0]=0}var i=(e instanceof ArrayBuffer?e.byteLength:e.size).toString(),o=new Uint8Array(i.length+1);for(s=0;s<i.length;s++)o[s]=parseInt(i[s]);if(o[i.length]=255,f){var a=new f([t.buffer,o.buffer,e]);n(null,a)}}))}),(function(e,t){return n(new f(t))}))},e.decodePayloadAsBinary=function(t,n,r){"function"==typeof n&&(r=n,n=null);for(var i=t,o=[];i.byteLength>0;){for(var a=new Uint8Array(i),l=0===a[0],c="",u=1;255!==a[u];u++){if(c.length>310)return r(h,0,1);c+=a[u]}i=s(i,2+c.length),c=parseInt(c);var d=s(i,0,c);if(l)try{d=String.fromCharCode.apply(null,new Uint8Array(d))}catch(e){var f=new Uint8Array(d);d="";for(u=0;u<f.length;u++)d+=String.fromCharCode(f[u])}o.push(d),i=s(i,c)}var p=o.length;o.forEach((function(t,s){r(e.decodePacket(t,n,!0),s,p)}))}}(ds);var xs,Ps,Ms={exports:{}};function Fs(){if(Ps)return xs;Ps=1;var e=ds;function t(e){this.path=e.path,this.hostname=e.hostname,this.port=e.port,this.secure=e.secure,this.query=e.query,this.timestampParam=e.timestampParam,this.timestampRequests=e.timestampRequests,this.readyState="",this.agent=e.agent||!1,this.socket=e.socket,this.enablesXDR=e.enablesXDR,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.forceNode=e.forceNode,this.isReactNative=e.isReactNative,this.extraHeaders=e.extraHeaders,this.localAddress=e.localAddress}return xs=t,(0,Ms.exports)(t.prototype),t.prototype.onError=function(e,t){var n=new Error(e);return n.type="TransportError",n.description=t,this.emit("error",n),this},t.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},t.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},t.prototype.send=function(e){if("open"!==this.readyState)throw new Error("Transport not open");this.write(e)},t.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},t.prototype.onData=function(t){var n=e.decodePacket(t,this.socket.binaryType);this.onPacket(n)},t.prototype.onPacket=function(e){this.emit("packet",e)},t.prototype.onClose=function(){this.readyState="closed",this.emit("close")},xs}!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<r.length;s++)if((n=r[s])===t||n.fn===t){r.splice(s,1);break}return this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),n=this._callbacks["$"+e];if(n)for(var r=0,s=(n=n.slice(0)).length;r<s;++r)n[r].apply(this,t);return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(Ms);var Us,Ns={};function Bs(){return Us||(Us=1,Ns.encode=function(e){var t="";for(var n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t},Ns.decode=function(e){for(var t={},n=e.split("&"),r=0,s=n.length;r<s;r++){var i=n[r].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}),Ns}var js,$s=function(e,t){var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e},qs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Ks={},Gs=0,Hs=0;function Vs(e){var t="";do{t=qs[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function zs(){var e=Vs(+new Date);return e!==js?(Gs=0,js=e):e+"."+Vs(Gs++)}for(;Hs<64;Hs++)Ks[qs[Hs]]=Hs;zs.encode=Vs,zs.decode=function(e){var t=0;for(Hs=0;Hs<e.length;Hs++)t=64*t+Ks[e.charAt(Hs)];return t};var Ws=zs,Ys={exports:{}},Qs={exports:{}},Xs=1e3,Js=60*Xs,Zs=60*Js,ei=24*Zs,ti=365.25*ei,ni=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*ti;case"days":case"day":case"d":return n*ei;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Zs;case"minutes":case"minute":case"mins":case"min":case"m":return n*Js;case"seconds":case"second":case"secs":case"sec":case"s":return n*Xs;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?function(e){return ri(e,ei,"day")||ri(e,Zs,"hour")||ri(e,Js,"minute")||ri(e,Xs,"second")||e+" ms"}(e):function(e){if(e>=ei)return Math.round(e/ei)+"d";if(e>=Zs)return Math.round(e/Zs)+"h";if(e>=Js)return Math.round(e/Js)+"m";if(e>=Xs)return Math.round(e/Xs)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function ri(e,t,n){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}!function(e,t){function n(e){var n;function s(){if(s.enabled){var e=s,r=+new Date,i=r-(n||r);e.diff=i,e.prev=n,e.curr=r,n=r;for(var o=new Array(arguments.length),a=0;a<o.length;a++)o[a]=arguments[a];o[0]=t.coerce(o[0]),"string"!=typeof o[0]&&o.unshift("%O");var l=0;o[0]=o[0].replace(/%([a-zA-Z%])/g,(function(n,r){if("%%"===n)return n;l++;var s=t.formatters[r];if("function"==typeof s){var i=o[l];n=s.call(e,i),o.splice(l,1),l--}return n})),t.formatArgs.call(e,o);var c=s.log||t.log||console.log.bind(console);c.apply(e,o)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var n,r=0;for(n in e)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]}(e),s.destroy=r,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function r(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=n.debug=n.default=n).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var n;t.save(e),t.names=[],t.skips=[];var r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(n=0;n<t.instances.length;n++){var i=t.instances[n];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=ni,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(Qs,Qs.exports),function(e,t){function n(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=Qs.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return;var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,r)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=n,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(Ys,Ys.exports);var si=Fs(),ii=Bs(),oi=ds,ai=$s,li=Ws,ci=Ys.exports("engine.io-client:polling"),ui=hi,di=null!=new cs({xdomain:!1}).responseType;function hi(e){var t=e&&e.forceBase64;di&&!t||(this.supportsBinary=!1),si.call(this,e)}ai(hi,si),hi.prototype.name="polling",hi.prototype.doOpen=function(){this.poll()},hi.prototype.pause=function(e){var t=this;function n(){ci("paused"),t.readyState="paused",e()}if(this.readyState="pausing",this.polling||!this.writable){var r=0;this.polling&&(ci("we are currently polling - waiting to pause"),r++,this.once("pollComplete",(function(){ci("pre-pause polling complete"),--r||n()}))),this.writable||(ci("we are currently writing - waiting to pause"),r++,this.once("drain",(function(){ci("pre-pause writing complete"),--r||n()})))}else n()},hi.prototype.poll=function(){ci("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},hi.prototype.onData=function(e){var t=this;ci("polling got data %s",e);oi.decodePayload(e,this.socket.binaryType,(function(e,n,r){if("opening"===t.readyState&&t.onOpen(),"close"===e.type)return t.onClose(),!1;t.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():ci('ignoring poll - transport state "%s"',this.readyState))},hi.prototype.doClose=function(){var e=this;function t(){ci("writing close packet"),e.write([{type:"close"}])}"open"===this.readyState?(ci("transport open - closing"),t()):(ci("transport not open - deferring close"),this.once("open",t))},hi.prototype.write=function(e){var t=this;this.writable=!1;var n=function(){t.writable=!0,t.emit("drain")};oi.encodePayload(e,this.supportsBinary,(function(e){t.doWrite(e,n)}))},hi.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",n="";return!1!==this.timestampRequests&&(e[this.timestampParam]=li()),this.supportsBinary||e.sid||(e.b64=1),e=ii.encode(e),this.port&&("https"===t&&443!==Number(this.port)||"http"===t&&80!==Number(this.port))&&(n=":"+this.port),e.length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+e};var fi=cs,pi=ui,gi=Ms.exports,mi=$s,yi=Ys.exports("engine.io-client:polling-xhr");function vi(){}function bi(e){if(pi.call(this,e),this.requestTimeout=e.requestTimeout,this.extraHeaders=e.extraHeaders,"undefined"!=typeof location){var t="https:"===location.protocol,n=location.port;n||(n=t?443:80),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port,this.xs=e.secure!==t}}function wi(e){this.method=e.method||"GET",this.uri=e.uri,this.xd=!!e.xd,this.xs=!!e.xs,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.agent=e.agent,this.isBinary=e.isBinary,this.supportsBinary=e.supportsBinary,this.enablesXDR=e.enablesXDR,this.requestTimeout=e.requestTimeout,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.extraHeaders=e.extraHeaders,this.create()}if(us.exports=bi,us.exports.Request=wi,mi(bi,pi),bi.prototype.supportsBinary=!0,bi.prototype.request=function(e){return(e=e||{}).uri=this.uri(),e.xd=this.xd,e.xs=this.xs,e.agent=this.agent||!1,e.supportsBinary=this.supportsBinary,e.enablesXDR=this.enablesXDR,e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized,e.requestTimeout=this.requestTimeout,e.extraHeaders=this.extraHeaders,new wi(e)},bi.prototype.doWrite=function(e,t){var n="string"!=typeof e&&void 0!==e,r=this.request({method:"POST",data:e,isBinary:n}),s=this;r.on("success",t),r.on("error",(function(e){s.onError("xhr post error",e)})),this.sendXhr=r},bi.prototype.doPoll=function(){yi("xhr poll");var e=this.request(),t=this;e.on("data",(function(e){t.onData(e)})),e.on("error",(function(e){t.onError("xhr poll error",e)})),this.pollXhr=e},gi(wi.prototype),wi.prototype.create=function(){var e={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized;var t=this.xhr=new fi(e),n=this;try{yi("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var r in t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(r)&&t.setRequestHeader(r,this.extraHeaders[r])}catch(e){}if("POST"===this.method)try{this.isBinary?t.setRequestHeader("Content-type","application/octet-stream"):t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=!0),this.requestTimeout&&(t.timeout=this.requestTimeout),this.hasXDR()?(t.onload=function(){n.onLoad()},t.onerror=function(){n.onError(t.responseText)}):t.onreadystatechange=function(){if(2===t.readyState)try{var e=t.getResponseHeader("Content-Type");n.supportsBinary&&"application/octet-stream"===e&&(t.responseType="arraybuffer")}catch(e){}4===t.readyState&&(200===t.status||1223===t.status?n.onLoad():setTimeout((function(){n.onError(t.status)}),0))},yi("xhr data %s",this.data),t.send(this.data)}catch(e){return void setTimeout((function(){n.onError(e)}),0)}"undefined"!=typeof document&&(this.index=wi.requestsCount++,wi.requests[this.index]=this)},wi.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},wi.prototype.onData=function(e){this.emit("data",e),this.onSuccess()},wi.prototype.onError=function(e){this.emit("error",e),this.cleanup(!0)},wi.prototype.cleanup=function(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=vi:this.xhr.onreadystatechange=vi,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete wi.requests[this.index],this.xhr=null}},wi.prototype.onLoad=function(){var e;try{var t;try{t=this.xhr.getResponseHeader("Content-Type")}catch(e){}e="application/octet-stream"===t&&this.xhr.response||this.xhr.responseText}catch(e){this.onError(e)}null!=e&&this.onData(e)},wi.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},wi.prototype.abort=function(){this.cleanup()},wi.requestsCount=0,wi.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Si);else if("function"==typeof addEventListener){var Ei="onpagehide"in self?"pagehide":"unload";addEventListener(Ei,Si,!1)}function Si(){for(var e in wi.requests)wi.requests.hasOwnProperty(e)&&wi.requests[e].abort()}var Ci,Ti=ui,ki=Li,_i=/\n/g,Ii=/\\n/g;function Ai(){}function Ri(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==gt?gt:{}}function Li(e){if(Ti.call(this,e),this.query=this.query||{},!Ci){var t=Ri();Ci=t.___eio=t.___eio||[]}this.index=Ci.length;var n=this;Ci.push((function(e){n.onData(e)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){n.script&&(n.script.onerror=Ai)}),!1)}$s(Li,Ti),Li.prototype.supportsBinary=!1,Li.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),Ti.prototype.doClose.call(this)},Li.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(t){e.onError("jsonp poll error",t)};var n=document.getElementsByTagName("script")[0];n?n.parentNode.insertBefore(t,n):(document.head||document.body).appendChild(t),this.script=t,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var e=document.createElement("iframe");document.body.appendChild(e),document.body.removeChild(e)}),100)},Li.prototype.doWrite=function(e,t){var n=this;if(!this.form){var r,s=document.createElement("form"),i=document.createElement("textarea"),o=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=o,s.method="POST",s.setAttribute("accept-charset","utf-8"),i.name="d",s.appendChild(i),document.body.appendChild(s),this.form=s,this.area=i}function a(){l(),t()}function l(){if(n.iframe)try{n.form.removeChild(n.iframe)}catch(e){n.onError("jsonp polling iframe removal error",e)}try{var e='<iframe src="javascript:0" name="'+n.iframeId+'">';r=document.createElement(e)}catch(e){(r=document.createElement("iframe")).name=n.iframeId,r.src="javascript:0"}r.id=n.iframeId,n.form.appendChild(r),n.iframe=r}this.form.action=this.uri(),l(),e=e.replace(Ii,"\\\n"),this.area.value=e.replace(_i,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===n.iframe.readyState&&a()}:this.iframe.onload=a};var Di,Oi,xi=yt(Object.freeze({__proto__:null,default:{}})),Pi=Fs(),Mi=ds,Fi=Bs(),Ui=$s,Ni=Ws,Bi=Ys.exports("engine.io-client:websocket");if("undefined"!=typeof WebSocket)Di=WebSocket;else if("undefined"!=typeof self)Di=self.WebSocket||self.MozWebSocket;else try{Oi=xi}catch(e){}var ji=Di||Oi,$i=qi;function qi(e){e&&e.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=Di&&!e.forceNode,this.protocols=e.protocols,this.usingBrowserWebSocket||(ji=Oi),Pi.call(this,e)}Ui(qi,Pi),qi.prototype.name="websocket",qi.prototype.supportsBinary=!0,qi.prototype.doOpen=function(){if(this.check()){var e=this.uri(),t=this.protocols,n={agent:this.agent,perMessageDeflate:this.perMessageDeflate};n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?t?new ji(e,t):new ji(e):new ji(e,t,n)}catch(e){return this.emit("error",e)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},qi.prototype.addEventListeners=function(){var e=this;this.ws.onopen=function(){e.onOpen()},this.ws.onclose=function(){e.onClose()},this.ws.onmessage=function(t){e.onData(t.data)},this.ws.onerror=function(t){e.onError("websocket error",t)}},qi.prototype.write=function(e){var t=this;this.writable=!1;for(var n=e.length,r=0,s=n;r<s;r++)!function(e){Mi.encodePacket(e,t.supportsBinary,(function(r){if(!t.usingBrowserWebSocket){var s={};if(e.options&&(s.compress=e.options.compress),t.perMessageDeflate)("string"==typeof r?Buffer.byteLength(r):r.length)<t.perMessageDeflate.threshold&&(s.compress=!1)}try{t.usingBrowserWebSocket?t.ws.send(r):t.ws.send(r,s)}catch(e){Bi("websocket closed before onclose event")}--n||i()}))}(e[r]);function i(){t.emit("flush"),setTimeout((function(){t.writable=!0,t.emit("drain")}),0)}},qi.prototype.onClose=function(){Pi.prototype.onClose.call(this)},qi.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},qi.prototype.uri=function(){var e=this.query||{},t=this.secure?"wss":"ws",n="";return this.port&&("wss"===t&&443!==Number(this.port)||"ws"===t&&80!==Number(this.port))&&(n=":"+this.port),this.timestampRequests&&(e[this.timestampParam]=Ni()),this.supportsBinary||(e.b64=1),(e=Fi.encode(e)).length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+e},qi.prototype.check=function(){return!(!ji||"__initialize"in ji&&this.name===qi.prototype.name)};var Ki=cs,Gi=us.exports,Hi=ki,Vi=$i;ns.polling=function(e){var t=!1,n=!1,r=!1!==e.jsonp;if("undefined"!=typeof location){var s="https:"===location.protocol,i=location.port;i||(i=s?443:80),t=e.hostname!==location.hostname||i!==e.port,n=e.secure!==s}if(e.xdomain=t,e.xscheme=n,"open"in new Ki(e)&&!e.forceJSONP)return new Gi(e);if(!r)throw new Error("JSONP disabled");return new Hi(e)},ns.websocket=Vi;var zi,Wi=[].indexOf,Yi=function(e,t){if(Wi)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1},Qi=ns,Xi=Ms.exports,Ji=Ys.exports("engine.io-client:socket"),Zi=Yi,eo=ds,to=vr,no=Bs(),ro=so;function so(e,t){if(!(this instanceof so))return new so(e,t);t=t||{},e&&"object"==typeof e&&(t=e,e=null),e?(e=to(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=to(t.host).host),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.agent=t.agent||!1,this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=t.query||{},"string"==typeof this.query&&(this.query=no.decode(this.query)),this.upgrade=!1!==t.upgrade,this.path=(t.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!t.forceJSONP,this.jsonp=!1!==t.jsonp,this.forceBase64=!!t.forceBase64,this.enablesXDR=!!t.enablesXDR,this.timestampParam=t.timestampParam||"t",this.timestampRequests=t.timestampRequests,this.transports=t.transports||["polling","websocket"],this.transportOptions=t.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=t.policyPort||843,this.rememberUpgrade=t.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=t.onlyBinaryUpgrades,this.perMessageDeflate=!1!==t.perMessageDeflate&&(t.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=t.pfx||null,this.key=t.key||null,this.passphrase=t.passphrase||null,this.cert=t.cert||null,this.ca=t.ca||null,this.ciphers=t.ciphers||null,this.rejectUnauthorized=void 0===t.rejectUnauthorized||t.rejectUnauthorized,this.forceNode=!!t.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(t.extraHeaders&&Object.keys(t.extraHeaders).length>0&&(this.extraHeaders=t.extraHeaders),t.localAddress&&(this.localAddress=t.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}so.priorWebsocketSuccess=!1,Xi(so.prototype),so.protocol=eo.protocol,so.Socket=so,so.Transport=Fs(),so.transports=ns,so.parser=ds,so.prototype.createTransport=function(e){Ji('creating transport "%s"',e);var t=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}(this.query);t.EIO=eo.protocol,t.transport=e;var n=this.transportOptions[e]||{};return this.id&&(t.sid=this.id),new Qi[e]({query:t,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0,isReactNative:this.isReactNative})},so.prototype.open=function(){var e;if(this.rememberUpgrade&&so.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length){var t=this;return void setTimeout((function(){t.emit("error","No transports available")}),0)}e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)},so.prototype.setTransport=function(e){Ji("setting transport %s",e.name);var t=this;this.transport&&(Ji("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",(function(){t.onDrain()})).on("packet",(function(e){t.onPacket(e)})).on("error",(function(e){t.onError(e)})).on("close",(function(){t.onClose("transport close")}))},so.prototype.probe=function(e){Ji('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),n=!1,r=this;function s(){if(r.onlyBinaryUpgrades){var s=!this.supportsBinary&&r.transport.supportsBinary;n=n||s}n||(Ji('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(s){if(!n)if("pong"===s.type&&"probe"===s.data){if(Ji('probe transport "%s" pong',e),r.upgrading=!0,r.emit("upgrading",t),!t)return;so.priorWebsocketSuccess="websocket"===t.name,Ji('pausing current transport "%s"',r.transport.name),r.transport.pause((function(){n||"closed"!==r.readyState&&(Ji("changing transport and sending upgrade packet"),u(),r.setTransport(t),t.send([{type:"upgrade"}]),r.emit("upgrade",t),t=null,r.upgrading=!1,r.flush())}))}else{Ji('probe transport "%s" failed',e);var i=new Error("probe error");i.transport=t.name,r.emit("upgradeError",i)}})))}function i(){n||(n=!0,u(),t.close(),t=null)}function o(n){var s=new Error("probe error: "+n);s.transport=t.name,i(),Ji('probe transport "%s" failed because of error: %s',e,n),r.emit("upgradeError",s)}function a(){o("transport closed")}function l(){o("socket closed")}function c(e){t&&e.name!==t.name&&(Ji('"%s" works - aborting "%s"',e.name,t.name),i())}function u(){t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),r.removeListener("close",l),r.removeListener("upgrading",c)}so.priorWebsocketSuccess=!1,t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",c),t.open()},so.prototype.onOpen=function(){if(Ji("socket open"),this.readyState="open",so.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){Ji("starting upgrade probes");for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},so.prototype.onPacket=function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(Ji('socket receive: type "%s", data "%s"',e.type,e.data),this.emit("packet",e),this.emit("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emit("data",e.data),this.emit("message",e.data)}else Ji('packet received with socket readyState "%s"',this.readyState)},so.prototype.onHandshake=function(e){this.emit("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},so.prototype.onHeartbeat=function(e){clearTimeout(this.pingTimeoutTimer);var t=this;t.pingTimeoutTimer=setTimeout((function(){"closed"!==t.readyState&&t.onClose("ping timeout")}),e||t.pingInterval+t.pingTimeout)},so.prototype.setPing=function(){var e=this;clearTimeout(e.pingIntervalTimer),e.pingIntervalTimer=setTimeout((function(){Ji("writing ping packet - expecting pong within %sms",e.pingTimeout),e.ping(),e.onHeartbeat(e.pingTimeout)}),e.pingInterval)},so.prototype.ping=function(){var e=this;this.sendPacket("ping",(function(){e.emit("ping")}))},so.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},so.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(Ji("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},so.prototype.write=so.prototype.send=function(e,t,n){return this.sendPacket("message",e,t,n),this},so.prototype.sendPacket=function(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var s={type:e,data:t,options:n};this.emit("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}},so.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var e=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?r():t()})):this.upgrading?r():t()}function t(){e.onClose("forced close"),Ji("socket closing - telling transport to close"),e.transport.close()}function n(){e.removeListener("upgrade",n),e.removeListener("upgradeError",n),t()}function r(){e.once("upgrade",n),e.once("upgradeError",n)}return this},so.prototype.onError=function(e){Ji("socket error %j",e),so.priorWebsocketSuccess=!1,this.emit("error",e),this.onClose("transport error",e)},so.prototype.onClose=function(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){Ji('socket close with reason: "%s"',e);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",e,t),this.writeBuffer=[],this.prevBufferLen=0}},so.prototype.filterUpgrades=function(e){for(var t=[],n=0,r=e.length;n<r;n++)~Zi(this.transports,e[n])&&t.push(e[n]);return t},(zi=ts).exports=ro,zi.exports.parser=ds;var io,oo,ao={exports:{}},lo={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<r.length;s++)if((n=r[s])===t||n.fn===t){r.splice(s,1);break}return this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),n=this._callbacks["$"+e];if(n)for(var r=0,s=(n=n.slice(0)).length;r<s;++r)n[r].apply(this,t);return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(lo);var co=function(e,t,n){return e.on(t,n),{destroy:function(){e.removeListener(t,n)}}};var uo,ho=[].slice,fo=function(e,t){if("string"==typeof t&&(t=e[t]),"function"!=typeof t)throw new Error("bind() requires a function");var n=ho.call(arguments,2);return function(){return t.apply(e,n.concat(ho.call(arguments)))}};function po(){return uo||(uo=1,function(e,t){var n=Dr,r=lo.exports,s=(oo||(oo=1,io=function(e,t){for(var n=[],r=(t=t||0)||0;r<e.length;r++)n[r-t]=e[r];return n}),io),i=co,o=fo,a=br.exports("socket.io-client:socket"),l=Bs(),c=fs();e.exports=h;var u={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},d=r.prototype.emit;function h(e,t,n){this.io=e,this.nsp=t,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},n&&n.query&&(this.query=n.query),this.io.autoConnect&&this.open()}r(h.prototype),h.prototype.subEvents=function(){if(!this.subs){var e=this.io;this.subs=[i(e,"open",o(this,"onopen")),i(e,"packet",o(this,"onpacket")),i(e,"close",o(this,"onclose"))]}},h.prototype.open=h.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},h.prototype.send=function(){var e=s(arguments);return e.unshift("message"),this.emit.apply(this,e),this},h.prototype.emit=function(e){if(u.hasOwnProperty(e))return d.apply(this,arguments),this;var t=s(arguments),r={type:(void 0!==this.flags.binary?this.flags.binary:c(t))?n.BINARY_EVENT:n.EVENT,data:t,options:{}};return r.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(a("emitting packet with ack id %d",this.ids),this.acks[this.ids]=t.pop(),r.id=this.ids++),this.connected?this.packet(r):this.sendBuffer.push(r),this.flags={},this},h.prototype.packet=function(e){e.nsp=this.nsp,this.io.packet(e)},h.prototype.onopen=function(){if(a("transport is open - connecting"),"/"!==this.nsp)if(this.query){var e="object"==typeof this.query?l.encode(this.query):this.query;a("sending connect packet with query %s",e),this.packet({type:n.CONNECT,query:e})}else this.packet({type:n.CONNECT})},h.prototype.onclose=function(e){a("close (%s)",e),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",e)},h.prototype.onpacket=function(e){var t=e.nsp===this.nsp,r=e.type===n.ERROR&&"/"===e.nsp;if(t||r)switch(e.type){case n.CONNECT:this.onconnect();break;case n.EVENT:case n.BINARY_EVENT:this.onevent(e);break;case n.ACK:case n.BINARY_ACK:this.onack(e);break;case n.DISCONNECT:this.ondisconnect();break;case n.ERROR:this.emit("error",e.data)}},h.prototype.onevent=function(e){var t=e.data||[];a("emitting event %j",t),null!=e.id&&(a("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?d.apply(this,t):this.receiveBuffer.push(t)},h.prototype.ack=function(e){var t=this,r=!1;return function(){if(!r){r=!0;var i=s(arguments);a("sending ack %j",i),t.packet({type:c(i)?n.BINARY_ACK:n.ACK,id:e,data:i})}}},h.prototype.onack=function(e){var t=this.acks[e.id];"function"==typeof t?(a("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):a("bad ack %s",e.id)},h.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},h.prototype.emitBuffered=function(){var e;for(e=0;e<this.receiveBuffer.length;e++)d.apply(this,this.receiveBuffer[e]);for(this.receiveBuffer=[],e=0;e<this.sendBuffer.length;e++)this.packet(this.sendBuffer[e]);this.sendBuffer=[]},h.prototype.ondisconnect=function(){a("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},h.prototype.destroy=function(){if(this.subs){for(var e=0;e<this.subs.length;e++)this.subs[e].destroy();this.subs=null}this.io.destroy(this)},h.prototype.close=h.prototype.disconnect=function(){return this.connected&&(a("performing disconnect (%s)",this.nsp),this.packet({type:n.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},h.prototype.compress=function(e){return this.flags.compress=e,this},h.prototype.binary=function(e){return this.flags.binary=e,this}}(ao)),ao.exports}var go=mo;function mo(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}mo.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},mo.prototype.reset=function(){this.attempts=0},mo.prototype.setMin=function(e){this.ms=e},mo.prototype.setMax=function(e){this.max=e},mo.prototype.setJitter=function(e){this.jitter=e};var yo=ts.exports,vo=po(),bo=lo.exports,wo=Dr,Eo=co,So=fo,Co=br.exports("socket.io-client:manager"),To=Yi,ko=go,_o=Object.prototype.hasOwnProperty,Io=Ao;function Ao(e,t){if(!(this instanceof Ao))return new Ao(e,t);e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.nsps={},this.subs=[],this.opts=t,this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor||.5),this.backoff=new ko({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this.readyState="closed",this.uri=e,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var n=t.parser||wo;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.autoConnect=!1!==t.autoConnect,this.autoConnect&&this.open()}Ao.prototype.emitAll=function(){for(var e in this.emit.apply(this,arguments),this.nsps)_o.call(this.nsps,e)&&this.nsps[e].emit.apply(this.nsps[e],arguments)},Ao.prototype.updateSocketIds=function(){for(var e in this.nsps)_o.call(this.nsps,e)&&(this.nsps[e].id=this.generateId(e))},Ao.prototype.generateId=function(e){return("/"===e?"":e+"#")+this.engine.id},bo(Ao.prototype),Ao.prototype.reconnection=function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection},Ao.prototype.reconnectionAttempts=function(e){return arguments.length?(this._reconnectionAttempts=e,this):this._reconnectionAttempts},Ao.prototype.reconnectionDelay=function(e){return arguments.length?(this._reconnectionDelay=e,this.backoff&&this.backoff.setMin(e),this):this._reconnectionDelay},Ao.prototype.randomizationFactor=function(e){return arguments.length?(this._randomizationFactor=e,this.backoff&&this.backoff.setJitter(e),this):this._randomizationFactor},Ao.prototype.reconnectionDelayMax=function(e){return arguments.length?(this._reconnectionDelayMax=e,this.backoff&&this.backoff.setMax(e),this):this._reconnectionDelayMax},Ao.prototype.timeout=function(e){return arguments.length?(this._timeout=e,this):this._timeout},Ao.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},Ao.prototype.open=Ao.prototype.connect=function(e,t){if(Co("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;Co("opening %s",this.uri),this.engine=yo(this.uri,this.opts);var n=this.engine,r=this;this.readyState="opening",this.skipReconnect=!1;var s=Eo(n,"open",(function(){r.onopen(),e&&e()})),i=Eo(n,"error",(function(t){if(Co("connect_error"),r.cleanup(),r.readyState="closed",r.emitAll("connect_error",t),e){var n=new Error("Connection error");n.data=t,e(n)}else r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var o=this._timeout;Co("connect attempt will timeout after %d",o);var a=setTimeout((function(){Co("connect attempt timed out after %d",o),s.destroy(),n.close(),n.emit("error","timeout"),r.emitAll("connect_timeout",o)}),o);this.subs.push({destroy:function(){clearTimeout(a)}})}return this.subs.push(s),this.subs.push(i),this},Ao.prototype.onopen=function(){Co("open"),this.cleanup(),this.readyState="open",this.emit("open");var e=this.engine;this.subs.push(Eo(e,"data",So(this,"ondata"))),this.subs.push(Eo(e,"ping",So(this,"onping"))),this.subs.push(Eo(e,"pong",So(this,"onpong"))),this.subs.push(Eo(e,"error",So(this,"onerror"))),this.subs.push(Eo(e,"close",So(this,"onclose"))),this.subs.push(Eo(this.decoder,"decoded",So(this,"ondecoded")))},Ao.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},Ao.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},Ao.prototype.ondata=function(e){this.decoder.add(e)},Ao.prototype.ondecoded=function(e){this.emit("packet",e)},Ao.prototype.onerror=function(e){Co("error",e),this.emitAll("error",e)},Ao.prototype.socket=function(e,t){var n=this.nsps[e];if(!n){n=new vo(this,e,t),this.nsps[e]=n;var r=this;n.on("connecting",s),n.on("connect",(function(){n.id=r.generateId(e)})),this.autoConnect&&s()}function s(){~To(r.connecting,n)||r.connecting.push(n)}return n},Ao.prototype.destroy=function(e){var t=To(this.connecting,e);~t&&this.connecting.splice(t,1),this.connecting.length||this.close()},Ao.prototype.packet=function(e){Co("writing packet %j",e);var t=this;e.query&&0===e.type&&(e.nsp+="?"+e.query),t.encoding?t.packetBuffer.push(e):(t.encoding=!0,this.encoder.encode(e,(function(n){for(var r=0;r<n.length;r++)t.engine.write(n[r],e.options);t.encoding=!1,t.processPacketQueue()})))},Ao.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var e=this.packetBuffer.shift();this.packet(e)}},Ao.prototype.cleanup=function(){Co("cleanup");for(var e=this.subs.length,t=0;t<e;t++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},Ao.prototype.close=Ao.prototype.disconnect=function(){Co("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},Ao.prototype.onclose=function(e){Co("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",e),this._reconnection&&!this.skipReconnect&&this.reconnect()},Ao.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Co("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var t=this.backoff.duration();Co("will wait %dms before reconnect attempt",t),this.reconnecting=!0;var n=setTimeout((function(){e.skipReconnect||(Co("attempting reconnect"),e.emitAll("reconnect_attempt",e.backoff.attempts),e.emitAll("reconnecting",e.backoff.attempts),e.skipReconnect||e.open((function(t){t?(Co("reconnect attempt error"),e.reconnecting=!1,e.reconnect(),e.emitAll("reconnect_error",t.data)):(Co("reconnect success"),e.onreconnect())})))}),t);this.subs.push({destroy:function(){clearTimeout(n)}})}},Ao.prototype.onreconnect=function(){var e=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",e)},function(e,t){var n=Lr,r=Dr,s=Io,i=br.exports("socket.io-client");e.exports=t=a;var o=t.managers={};function a(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,a=n(e),l=a.source,c=a.id,u=a.path,d=o[c]&&u in o[c].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||d?(i("ignoring socket cache for %s",l),r=s(l,t)):(o[c]||(i("new io instance for %s",l),o[c]=s(l,t)),r=o[c]),a.query&&!t.query&&(t.query=a.query),r.socket(a.path,t)}t.protocol=r.protocol,t.connect=a,t.Manager=Io,t.Socket=po()}(gr,gr.exports);var Ro=gr.exports;function Lo(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 Do={exports:{}};!function(e,t){e.exports=function(){function e(t,n,r){function s(o,a){if(!n[o]){if(!t[o]){if(!a&&Lo)return Lo(o);if(i)return i(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[o]={exports:{}};t[o][0].call(c.exports,(function(e){return s(t[o][1][e]||e)}),c,c.exports,e,t,n,r)}return n[o].exports}for(var i=Lo,o=0;o<r.length;o++)s(r[o]);return s}return e}()({1:[function(e,t,n){(function(n,r){(function(){const s=e("events").EventEmitter,i=e("./store"),o=e("./topic-alias-recv"),a=e("./topic-alias-send"),l=e("mqtt-packet"),c=e("./default-message-id-provider"),u=e("readable-stream").Writable,d=e("inherits"),h=e("reinterval"),f=e("rfdc/default"),p=e("./validations"),g=e("xtend"),m=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],E={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function S(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function C(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(m("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function T(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){m("sendPacket :: packet: %O",t),m("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),m("sendPacket :: writing to stream");const r=l.writeToStream(t,e.stream,e.options);m("sendPacket :: writeToStream result %s",r),!r&&n&&n!==R?(m("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(m("sendPacket :: invoking cb"),n())}function _(e){e&&(m("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function I(e){e&&(m("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function A(e,t,n,r){m("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let s,i=t;if("publish"===i.cmd&&(i=f(t),s=T(e,i),s))return n&&n(s);e.outgoingStore.put(i,(function(s){if(s)return n&&n(s);r(),k(e,t,n)}))}function R(e){m("nop ::",e)}function L(e,t){let n;const r=this;if(!(this instanceof L))return new L(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];m("MqttClient :: options.protocol",t.protocol),m("MqttClient :: options.protocolVersion",t.protocolVersion),m("MqttClient :: options.username",t.username),m("MqttClient :: options.keepalive",t.keepalive),m("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),m("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),m("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:S(),m("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new c:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new i,this.incomingStore=t.incomingStore||new i,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?m("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();m("deliver :: entry %o",n);let s=null;if(!n)return void r._resubscribe();s=n.packet,m("deliver :: call _sendPacket for %o",s);let i=!0;s.messageId&&0!==s.messageId&&(r.messageIdProvider.register(s.messageId)||(i=!1)),i?r._sendPacket(s,(function(e){n.cb&&n.cb(e),t()})):(m("messageId: %d has already used. The message is skipped and removed.",s.messageId),t())}m("connect :: sending queued packets"),t()})),this.on("close",(function(){m("close :: connected set to `false`"),this.connected=!1,m("close :: clearing connackTimer"),clearTimeout(this.connackTimer),m("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),m("close :: calling _setupReconnect"),this._setupReconnect()})),s.call(this),m("MqttClient :: setting up stream"),this._setupStream()}d(L,s),L.prototype._setupStream=function(){const e=this,t=new u,n=l.parser(this.options);let r=null;const s=[];function i(){if(s.length)y(o);else{const e=r;r=null,e()}}function o(){m("work :: getting next packet in queue");const t=s.shift();if(t)m("work :: packet pulled from queue"),e._handlePacket(t,i);else{m("work :: no packets in queue");const e=r;r=null,m("work :: done flag is %s",!!e),e&&e()}}function a(t){m("streamErrorHandler :: error",t.message),w.includes(t.code)?(m("streamErrorHandler :: emitting error"),e.emit("error",t)):R(t)}m("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),m("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){m("parser :: on packet push to packets array."),s.push(e)})),t._write=function(e,t,s){r=s,m("writable stream :: parsing buffer"),n.parse(e),o()},m("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",a),this.stream.on("close",(function(){m("(%s)stream :: on close",e.options.clientId),I(e.outgoing),m("stream: emit close to MqttClient"),e.emit("close")})),m("_setupStream: sending packet `connect`");const c=Object.create(this.options);if(c.cmd="connect",this.topicAliasRecv&&(c.properties||(c.properties={}),this.topicAliasRecv&&(c.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,c),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,g({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){m("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},L.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(m("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},L.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==R?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},L.prototype.publish=function(e,t,n,r){m("publish :: message `%s` to topic `%s`",t,e);const s=this.options;if("function"==typeof n&&(r=n,n=null),n=g({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const i=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=i._nextId(),null===o))return m("No messageId left"),!1;const a={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===s.protocolVersion&&(a.properties=n.properties),m("publish :: qos",n.qos),n.qos){case 1:case 2:i.outgoing[a.messageId]={volatile:!1,cb:r||R},m("MqttClient:publish: packet cmd: %s",a.cmd),i._sendPacket(a,void 0,n.cbStorePut);break;default:m("MqttClient:publish: packet cmd: %s",a.cmd),i._sendPacket(a,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},L.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const s=r.resubscribe;let i=t.pop()||R,o=t.pop();const a=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof i&&(o=i,i=R);const l=p.validateTopics(r);if(null!==l)return v(i,new Error("Invalid topic "+l)),this;if(this._checkDisconnecting(i))return m("subscribe: discconecting true"),this;const c={qos:0};if(5===a&&(c.nl=!1,c.rap=!1,c.rh=0),o=g(c,o),Array.isArray(r)?r.forEach((function(t){if(m("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||s){const e={topic:t,qos:o.qos};5===a&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),m("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(m("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||s){const e={topic:t,qos:r[t].qos};5===a&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=o.properties),m("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return i(null,[]),this;const u=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(r.properties=o.properties),e.options.resubscribe){m("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===a&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}i(e,n)}},m("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!u())&&this._storeProcessingQueue.push({invoke:u,callback:i}),this},L.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||R,s=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(s=r,r=R);const i=p.validateTopics(n);if(null!==i)return v(r,new Error("Invalid topic "+i)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const i={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?i.unsubscriptions=[n]:Array.isArray(n)&&(i.unsubscriptions=n),e.options.resubscribe&&i.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof s&&s.properties&&(i.properties=s.properties),e.outgoing[i.messageId]={volatile:!0,cb:r},m("unsubscribe: call _sendPacket"),e._sendPacket(i),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},L.prototype.end=function(e,t,n){const r=this;function s(){m("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(m("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;m("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function i(){m("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{m("end :: finish :: calling process.nextTick on closeStores"),y(s.bind(r))}),t)}return m("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||R,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=R))),"object"!=typeof t&&(n=t,t=null),m("end :: cb? %s",!!n),n=n||R,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(m("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,i,10))):(m("end :: (%s) :: immediately calling finish",r.options.clientId),i()),this)},L.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},L.prototype.reconnect=function(e){m("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new i,t.outgoingStore=t.options.outgoingStore||new i,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},L.prototype._reconnect=function(){m("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),m("client already connected. disconnecting first.")):(m("_reconnect: calling _setupStream"),this._setupStream())},L.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(m("_setupReconnect :: emit `offline` state"),this.emit("offline"),m("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),m("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){m("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):m("_setupReconnect :: doing nothing...")},L.prototype._clearReconnect=function(){m("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},L.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(m("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),m("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&_(this.outgoing),m("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=g({cmd:"disconnect"},n);m("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(m("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(m("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(m("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},L.prototype._sendPacket=function(e,t,n){m("_sendPacket :: (%s) :: start",this.options.clientId),n=n||R,t=t||R;const r=C(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(m("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void A(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:A(this,e,t,n);break;default:k(this,e,t)}m("_sendPacket :: (%s) :: end",this.options.clientId)}},L.prototype._storePacket=function(e,t,n){m("_storePacket :: packet: %o",e),m("_storePacket :: cb? %s",!!t),n=n||R;let r=e;if("publish"===r.cmd){r=f(e);const n=T(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},L.prototype._setupPingTimer=function(){m("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},L.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},L.prototype._checkPing=function(){m("_checkPing :: checking ping..."),this.pingResp?(m("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(m("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},L.prototype._handlePingresp=function(){this.pingResp=!0},L.prototype._handleConnack=function(e){m("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new a(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+E[n]);e.code=n,this.emit("error",e)}},L.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+E[n]);e.code=n,r.emit("error",t)}}))},L.prototype.handleAuth=function(e,t){t()},L.prototype._handlePublish=function(e,t){m("_handlePublish: packet %o",e),t=void 0!==t?t:R;let n=e.topic.toString();const r=e.payload,s=e.qos,i=e.messageId,o=this,a=this.options,l=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return m("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,m("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));m("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(m("_handlePublish: qos %d",s),s){case 2:a.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===l.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:i,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:i},t)})))}));break;case 1:a.customHandleAcks(n,r,e,(function(s,a){return s instanceof Error||(a=s,s=null),s?o.emit("error",s):-1===l.indexOf(a)?o.emit("error",new Error("Wrong reason code for puback")):(a||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:i,reasonCode:a},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:m("_handlePublish: unknown QoS. Doing nothing.")}},L.prototype.handleMessage=function(e,t){t()},L.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const s=this.outgoing[t]?this.outgoing[t].cb:null,i=this;let o;if(s){switch(m("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+E[n]),o.code=n,s(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,s),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+E[n]),o.code=n,s(o,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete i._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),s(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),s(null);break;default:i.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else m("_handleAck :: Server sent an ack in error. Ignoring.")},L.prototype._handlePubrel=function(e,t){m("handling pubrel packet"),t=void 0!==t?t:R;const n=e.messageId,r=this,s={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(s,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,R),r._sendPacket(s,t)})))}))},L.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},L.prototype._nextId=function(){return this.messageIdProvider.allocate()},L.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},L.prototype._resubscribe=function(){m("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){m("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},L.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function s(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function i(){r.destroy(),r=null,t._flushStoreProcessingQueue(),s()}function o(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):m("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",i),r.on("error",(function(e){s(),t._flushStoreProcessingQueue(),t.removeListener("close",i),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(s(),t.removeListener("close",i),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},L.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},L.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},L.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=L}).call(this)}).call(this,e("_process"),void 0!==gt?gt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,i=e("duplexify");let o,a,l,c=!1;function u(){const e=new s;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.closeSocket({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function f(){c||(c=!0,o.onSocketOpen((function(){l.setReadable(a),l.setWritable(a),l.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");a.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),a.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){l.end(),l.destroy()})),o.onSocketError((function(e){l.destroy(e)})))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=h(t,e);return o=t.my,o.connectSocket({url:r,protocols:n}),a=u(),l=i.obj(),f(),l}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),s=e("debug")("mqttjs:tcp");function i(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,i=t.hostname;return s("port %d and host %s",n,i),r.createConnection(n,i)}t.exports=i},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),s=e("net"),i=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===s.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,i("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function o(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),s=e("ws"),i=e("debug")("mqttjs:ws"),o=e("duplexify"),a=e("readable-stream").Transform,l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],c=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function u(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function d(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),c||"wss"!==e.protocol||l.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=d(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function f(e,t,n){i("createWebSocket"),i("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return i("creating new Websocket for url: "+t+" and protocol: "+r),new s(t,[r],n.wsOptions)}function p(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=u(t,e),s=new WebSocket(r,[n]);return s.binaryType="arraybuffer",s}function g(e,t){i("streamBuilder");const n=d(t),r=u(n,e),o=f(e,r,n),a=s.createWebSocketStream(o,n.wsOptions);return a.url=r,o.on("close",(()=>{a.destroy()})),a}function m(e,t){let n;i("browserStreamBuilder");const s=h(t).browserBufferSize||524288,l=t.browserBufferTimeout||1e3,c=!t.objectMode,u=p(e,t),d=g(t,E,S);t.objectMode||(d._writev=w),d.on("close",(()=>{u.close()}));const f=void 0!==u.addEventListener;function g(e,t,n){const r=new a({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function m(){n.setReadable(d),n.setWritable(d),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),d.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function E(e,t,n){u.bufferedAmount>s&&setTimeout(E,l,e,t,n),c&&"string"==typeof e&&(e=r.from(e,"utf8"));try{u.send(e)}catch(e){return n(e)}n()}function S(e){u.close(),e()}return u.readyState===u.OPEN?n=d:(n=n=o(void 0,void 0,t),t.objectMode||(n._writev=w),f?u.addEventListener("open",m):u.onopen=m),n.socket=u,f?(u.addEventListener("close",y),u.addEventListener("error",v),u.addEventListener("message",b)):(u.onclose=y,u.onerror=v,u.onmessage=b),n}t.exports=c?m:g}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,i=e("duplexify");let o,a,l;function c(){const e=new s;return e._write=function(e,t,n){o.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){o.close({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function d(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){o.onOpen((function(){l.setReadable(a),l.setWritable(a),l.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),a.push(t)})),o.onClose((function(){l.end(),l.destroy()})),o.onError((function(e){l.destroy(new Error(e.errMsg))}))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=d(t,e);o=wx.connectSocket({url:r,protocols:[n]}),a=c(),l=i.obj(),l._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const s=l.destroy;return l.destroy=function(){l.destroy=s;const e=this;setTimeout((function(){o.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(l),h(),l}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),s=e("readable-stream").Readable,i={objectMode:!0},o={clean:!0};function a(e){if(!(this instanceof a))return new a(e);this.options=e||{},this.options=r(o,e),this._inflights=new Map}a.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},a.prototype.createStream=function(){const e=new s(i),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},a.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},a.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},a.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=a},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),s=e("number-allocator").NumberAllocator;function i(e){if(!(this instanceof i))return new i(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new s(1,e),this.max=e,this.length=0)}i.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},i.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},i.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},i.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},i.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=i},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function s(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:s}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),s=e("../store"),i=e("url"),o=e("xtend"),a=e("debug")("mqttjs"),l={};function c(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function u(e,t){if(a("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=i.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=o(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(c(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!l[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof l[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),a("calling streambuilder for",t.protocol),l[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const s=new r(n,t);return s.on("error",(function(){})),s}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(l.mqtt=e("./tcp"),l.tcp=e("./tcp"),l.ssl=e("./tls"),l.tls=e("./tls"),l.mqtts=e("./tls")):(l.wx=e("./wx"),l.wxs=e("./wx"),l.ali=e("./ali"),l.alis=e("./ali")),l.ws=e("./ws"),l.wss=e("./ws"),t.exports=u,t.exports.connect=u,t.exports.MqttClient=r,t.exports.Store=s}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=u,n.toByteArray=h,n.fromByteArray=g;for(var r=[],s=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,l=o.length;a<l;++a)r[a]=o[a],s[o.charCodeAt(a)]=a;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function u(e){var t=c(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function d(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=c(e),o=r[0],a=r[1],l=new i(d(e,o,a)),u=0,h=a>0?o-4:o;for(n=0;n<h;n+=4)t=s[e.charCodeAt(n)]<<18|s[e.charCodeAt(n+1)]<<12|s[e.charCodeAt(n+2)]<<6|s[e.charCodeAt(n+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===a&&(t=s[e.charCodeAt(n)]<<2|s[e.charCodeAt(n+1)]>>4,l[u++]=255&t),1===a&&(t=s[e.charCodeAt(n)]<<10|s[e.charCodeAt(n+1)]<<4|s[e.charCodeAt(n+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l}function f(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function p(e,t,n){for(var r,s=[],i=t;i<n;i+=3)r=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),s.push(f(r));return s.join("")}function g(e){for(var t,n=e.length,s=n%3,i=[],o=16383,a=0,l=n-s;a<l;a+=o)i.push(p(e,a,a+o>l?l:a+o));return 1===s?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")}s["-".charCodeAt(0)]=62,s["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),s=Symbol.for("BufferList");function i(e){if(!(this instanceof i))return new i(e);i._init.call(this,e)}i._init=function(e){Object.defineProperty(this,s,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},i.prototype._new=function(e){return new i(e)},i.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},i.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},i.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,n,s){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof s||s>this.length)&&(s=this.length),n>=this.length)return e||r.alloc(0);if(s<=0)return e||r.alloc(0);const i=!!e,o=this._offset(n),a=s-n;let l=a,c=i&&t||0,u=o[1];if(0===n&&s===this.length){if(!i)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,c),c+=this._bufs[t].length;return e}if(l<=this._bufs[o[0]].length-u)return i?this._bufs[o[0]].copy(e,t,u,u+l):this._bufs[o[0]].slice(u,u+l);i||(e=r.allocUnsafe(a));for(let t=o[0];t<this._bufs.length;t++){const n=this._bufs[t].length-u;if(!(l>n)){this._bufs[t].copy(e,c,u,u+l),c+=n;break}this._bufs[t].copy(e,c,u),c+=n,l-=n,u&&(u=0)}return e.length>c?e.slice(0,c):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),s=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?s.pop():s[s.length-1]=s[s.length-1].slice(0,r[1]),0!==n[1]&&(s[0]=s[0].slice(n[1])),this._new(s)},i.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},i.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},i.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},i.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const s=this._offset(t);let i=s[0],o=s[1];for(;i<this._bufs.length;i++){const t=this._bufs[i];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([i,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([i,o]);if(this._match(t,e))return t;o++}o=0}return-1},i.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?i.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:i.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),i.prototype._isBufferList=function(e){return e instanceof i||i.isBufferList(e)},i.isBufferList=function(e){return null!=e&&e[s]},t.exports=i},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,s=e("inherits"),i=e("./BufferList");function o(e){if(!(this instanceof o))return new o(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}i._init.call(this,e),r.call(this)}s(o,r),Object.assign(o.prototype,i.prototype),o.prototype._new=function(e){return new o(e)},o.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},o.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},o.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},o.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},o.prototype._isBufferList=function(e){return e instanceof o||e instanceof i||o.isBufferList(e)},o.isBufferList=i.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=i},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=a,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var s=2147483647;function i(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function o(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=a.prototype,t}function a(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return l(e,t,n)}function l(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return f(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return p(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return a.from(r,t,n);var s=g(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function d(e){return c(e),o(e<0?0:0|m(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!a.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=o(n),s=r.write(e,t);return s!==n&&(r=r.slice(0,s)),r}function f(e){for(var t=e.length<0?0:0|m(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function p(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=a.prototype,r}function g(e){if(a.isBuffer(e)){var t=0|m(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||X(e.length)?o(0):f(e):"Buffer"===e.type&&Array.isArray(e.data)?f(e.data):void 0}function m(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(s)return r?-1:H(e).length;t=(""+t).toLowerCase(),s=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return M(this,t,n);case"utf8":case"utf-8":return L(this,t,n);case"ascii":return x(this,t,n);case"latin1":case"binary":return P(this,t,n);case"base64":return R(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function E(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),X(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:S(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):S(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function S(e,t,n,r,s){var i,o=1,a=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,l/=2,n/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){var u=-1;for(i=n;i<a;i++)if(c(e,i)===c(t,-1===u?0:i-u)){if(-1===u&&(u=i),i-u+1===l)return u*o}else-1!==u&&(i-=i-u),u=-1}else for(n+l>a&&(n=a-l),i=n;i>=0;i--){for(var d=!0,h=0;h<l;h++)if(c(e,i+h)!==c(t,h)){d=!1;break}if(d)return i}return-1}function C(e,t,n,r){n=Number(n)||0;var s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;var i=t.length;r>i/2&&(r=i/2);for(var o=0;o<r;++o){var a=parseInt(t.substr(2*o,2),16);if(X(a))return o;e[n+o]=a}return o}function T(e,t,n,r){return Y(H(t,e.length-n),e,n,r)}function k(e,t,n,r){return Y(V(t),e,n,r)}function _(e,t,n,r){return k(e,t,n,r)}function I(e,t,n,r){return Y(W(t),e,n,r)}function A(e,t,n,r){return Y(z(t,e.length-n),e,n,r)}function R(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function L(e,t,n){n=Math.min(e.length,n);for(var r=[],s=t;s<n;){var i,o,a,l,c=e[s],u=null,d=c>239?4:c>223?3:c>191?2:1;if(s+d<=n)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(i=e[s+1]))&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[s+1],o=e[s+2],128==(192&i)&&128==(192&o)&&(l=(15&c)<<12|(63&i)<<6|63&o)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[s+1],o=e[s+2],a=e[s+3],128==(192&i)&&128==(192&o)&&128==(192&a)&&(l=(15&c)<<18|(63&i)<<12|(63&o)<<6|63&a)>65535&&l<1114112&&(u=l)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),s+=d}return O(r)}n.kMaxLength=s,a.TYPED_ARRAY_SUPPORT=i(),a.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),a.poolSize=8192,a.from=function(e,t,n){return l(e,t,n)},a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,a.alloc=function(e,t,n){return u(e,t,n)},a.allocUnsafe=function(e){return d(e)},a.allocUnsafeSlow=function(e){return d(e)},a.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==a.prototype},a.compare=function(e,t){if(Q(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),Q(t,Uint8Array)&&(t=a.from(t,t.offset,t.byteLength)),!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,i=Math.min(n,r);s<i;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},a.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=a.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var i=e[n];if(Q(i,Uint8Array)&&(i=a.from(i)),!a.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,s),s+=i.length}return r},a.byteLength=v,a.prototype._isBuffer=!0,a.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},a.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},a.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},a.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?L(this,0,e):b.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},a.prototype.compare=function(e,t,n,r,s){if(Q(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(s>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),l=Math.min(i,o),c=this.slice(r,s),u=e.slice(t,n),d=0;d<l;++d)if(c[d]!==u[d]){i=c[d],o=u[d];break}return i<o?-1:o<i?1:0},a.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},a.prototype.indexOf=function(e,t,n){return E(this,e,t,n,!0)},a.prototype.lastIndexOf=function(e,t,n){return E(this,e,t,n,!1)},a.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return C(this,e,t,n);case"utf8":case"utf-8":return T(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return _(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var D=4096;function O(e){var t=e.length;if(t<=D)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=D));return n}function x(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function P(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){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var s="",i=t;i<n;++i)s+=G(e[i]);return s}function F(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}function U(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,s,i){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,s,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function j(e,t,n,s,i){return t=+t,n>>>=0,i||B(e,t,n,4),r.write(e,t,n,s,23,4),n+4}function $(e,t,n,s,i){return t=+t,n>>>=0,i||B(e,t,n,8),r.write(e,t,n,s,52,8),n+8}a.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=a.prototype,r},a.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||U(e,t,this.length);for(var r=this[e],s=1,i=0;++i<t&&(s*=256);)r+=this[e+i]*s;return r},a.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||U(e,t,this.length);for(var r=this[e+--t],s=1;t>0&&(s*=256);)r+=this[e+--t]*s;return r},a.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||U(e,t,this.length);for(var r=this[e],s=1,i=0;++i<t&&(s*=256);)r+=this[e+i]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||U(e,t,this.length);for(var r=t,s=1,i=this[e+--r];r>0&&(s*=256);)i+=this[e+--r]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),r.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),r.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),r.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),r.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var s=1,i=0;for(this[t]=255&e;++i<n&&(s*=256);)this[t+i]=e/s&255;return t+n},a.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var s=n-1,i=1;for(this[t+s]=255&e;--s>=0&&(i*=256);)this[t+s]=e/i&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);N(this,e,t,n,s-1,-s)}var i=0,o=1,a=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);N(this,e,t,n,s-1,-s)}var i=n-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeFloatLE=function(e,t,n){return j(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return j(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return $(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return $(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(!a.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var s=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var i=s-1;i>=0;--i)e[i+t]=this[i+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return s},a.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!a.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var s=e.charCodeAt(0);("utf8"===r&&s<128||"latin1"===r)&&(e=s)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{var o=a.isBuffer(e)?e:a.from(e,r),l=o.length;if(0===l)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=o[i%l]}return this};var q=/[^+/0-9A-Za-z-_]/g;function K(e){if((e=(e=e.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function G(e){return e<16?"0"+e.toString(16):e.toString(16)}function H(e,t){var n;t=t||1/0;for(var r=e.length,s=null,i=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function z(e,t){for(var n,r,s,i=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,s=n%256,i.push(s),i.push(r);return i}function W(e){return t.toByteArray(K(e))}function Y(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 Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function s(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),e.splice(s,0,n)}function o(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function a(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function l(){try{return localStorage}catch(e){}}n.formatArgs=i,n.save=o,n.load=a,n.useColors=s,n.storage=l(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:c}=t.exports;c.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(t||s);n.diff=i,n.prev=t,n.curr=s,t=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,s)=>{if("%%"===t)return"%";o++;const i=r.formatters[s];if("function"==typeof i){const r=e[o];t=i.call(n,r),e.splice(o,1),o--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return a.namespace=e,a.useColors=r.useColors(),a.color=r.selectColor(e),a.extend=s,a.destroy=r.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==r.namespaces&&(n=r.namespaces,i=r.enabled(e)),i),set:e=>{o=e}}),"function"==typeof r.init&&r.init(a),a}function s(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function i(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(t=0;t<s;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function o(){const e=[...r.names.map(l),...r.skips.map(l).map((e=>"-"+e))].join(",");return r.enable(""),e}function a(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function l(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function c(e){return e instanceof Error?e.stack||e.message:e}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=c,r.disable=o,r.enable=i,r.enabled=a,r.humanize=e("ms"),r.destroy=u,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var s=e("readable-stream"),i=e("end-of-stream"),o=e("inherits"),a=e("stream-shift"),l=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),c=function(e,t){e._corked?e.once("uncork",t):t()},u=function(e,t){e._autoDestroy&&e.destroy(t)},d=function(e,t){return function(n){n?u(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},f=function(){},p=function(e){return new s.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},g=function(e,t,n){if(!(this instanceof g))return new g(e,t,n);s.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};o(g,s.Duplex),g.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new g(e,t,n)},g.prototype.cork=function(){1==++this._corked&&this.emit("cork")},g.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},g.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=i(e,{writable:!0,readable:!1},d(this,this._forwardEnd)),s=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",s),r()};this._unwrite&&n.nextTick(s),this._writable=e,this._writable.on("drain",s),this._unwrite=o,this.uncork()}else this.end()},g.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=i(e,{writable:!1,readable:!0},d(this)),r=function(){t._forward()},s=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",s),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:p(e),this._readable2.on("readable",r),this._readable2.on("end",s),this._unread=o,this._forward()}},g.prototype._read=function(){this._drained=!0,this._forward()},g.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=a(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},g.prototype.destroy=function(e,t){if(t||(t=f),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},g.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},g.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?c(this,this._write.bind(this,e,t,n)):e===l?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},g.prototype._finish=function(e){var t=this;this.emit("preend"),c(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),c(t,e)}))}))},g.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(l),s.Writable.prototype.end.call(this,n))},t.exports=g}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),s=function(){},i=function(e){return e.setHeader&&"function"==typeof e.abort},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},a=function(e,t,l){if("function"==typeof t)return a(e,null,t);t||(t={}),l=r(l||s);var c=e._writableState,u=e._readableState,d=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,f=!1,p=function(){e.writable||g()},g=function(){h=!1,d||l.call(e)},m=function(){d=!1,h||l.call(e)},y=function(t){l.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){l.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!f)return(!d||u&&u.ended&&!u.destroyed)&&(!h||c&&c.ended&&!c.destroyed)?void 0:l.call(e,new Error("premature close"))},E=function(){e.req.on("finish",g)};return i(e)?(e.on("complete",g),e.on("abort",b),e.req?E():e.on("request",E)):h&&!c&&(e.on("end",p),e.on("close",p)),o(e)&&e.on("exit",y),e.on("end",m),e.on("finish",g),!1!==t.error&&e.on("error",v),e.on("close",b),function(){f=!0,e.removeListener("complete",g),e.removeListener("abort",b),e.removeListener("request",E),e.req&&e.req.removeListener("finish",g),e.removeListener("end",p),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("exit",y),e.removeListener("end",m),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=a}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||T,s=Object.keys||k,i=Function.prototype.bind||_;function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0;var a,l=10;try{var c={};Object.defineProperty&&Object.defineProperty(c,"x",{value:0}),a=0===c.x}catch(e){a=!1}function u(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function d(e,t,n){if(t)e.call(n);else for(var r=e.length,s=S(e,r),i=0;i<r;++i)s[i].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var s=e.length,i=S(e,s),o=0;o<s;++o)i[o].call(n,r)}function f(e,t,n,r,s){if(t)e.call(n,r,s);else for(var i=e.length,o=S(e,i),a=0;a<i;++a)o[a].call(n,r,s)}function p(e,t,n,r,s,i){if(t)e.call(n,r,s,i);else for(var o=e.length,a=S(e,o),l=0;l<o;++l)a[l].call(n,r,s,i)}function g(e,t,n,r){if(t)e.apply(n,r);else for(var s=e.length,i=S(e,s),o=0;o<s;++o)i[o].apply(n,r)}function m(e,t,n,s){var i,o,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]):(o=e._events=r(null),e._eventsCount=0),a){if("function"==typeof a?a=o[t]=s?[n,a]:[a,n]:s?a.unshift(n):a.push(n),!a.warned&&(i=u(e))&&i>0&&a.length>i){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else a=o[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=i.call(y,r);return s.listener=n,r.wrapFn=s,s}function b(e,t,n){var r=e._events;if(!r)return[];var s=r[t];return s?"function"==typeof s?n?[s.listener||s]:[s]:n?C(s):S(s,s.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function E(e,t){for(var n=t,r=n+1,s=e.length;r<s;n+=1,r+=1)e[n]=e[r];e.pop()}function S(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function C(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function T(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function _(e){var t=this;return function(){return t.apply(e,arguments)}}a?Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');l=e}}):o.defaultMaxListeners=l,o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(e){var t,n,r,s,i,o,a="error"===e;if(o=this._events)a=a&&null==o.error;else if(!a)return!1;if(a){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var l=new Error('Unhandled "error" event. ('+t+")");throw l.context=t,l}if(!(n=o[e]))return!1;var c="function"==typeof n;switch(r=arguments.length){case 1:d(n,c,this);break;case 2:h(n,c,this,arguments[1]);break;case 3:f(n,c,this,arguments[1],arguments[2]);break;case 4:p(n,c,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(r-1),i=1;i<r;i++)s[i-1]=arguments[i];g(n,c,this,s)}return!0},o.prototype.addListener=function(e,t){return m(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return m(this,e,t,!0)},o.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,s,i,o,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():E(n,i),1===n.length&&(s[e]=n[0]),s.removeListener&&this.emit("removeListener",e,a||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,i;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var o,a=s(n);for(i=0;i<a.length;++i)"removeListener"!==(o=a[i])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},o.prototype.listenerCount=w,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
1
+ var Amity=function(e,t,n,r,o,a,s,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(n),f=h(r),g=h(o),m=h(a),y=h(s),v=h(i),b=h(c),w=h(d),C=h(u);const I=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),_=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),S=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"}),E=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),A=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),T="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),O=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),P=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const R=function(){try{return"v6.24.1-umd"}catch(e){return"__dev__"}}(),U=5,x="cache_then_server",j="For using Live Collection feature you need to enable Cache!",D="Observing unsynced object is not supported by Live Object.",N=1e3,B=864e5,F=6e5,q="dead",L=2e3,$=6e4,K=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),z=e=>JSON.parse(e),V=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>V(e[n],t[n])))),Q=e=>[400400,400300].includes(e),H=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),G=e=>"limit"in e,J=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Y=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let o={};return"skiplimit"===n?o={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&W(e)?((null==e?void 0:e.before)&&(o=Object.assign(Object.assign({},o),{before:e.before})),(null==e?void 0:e.after)&&(o=Object.assign(Object.assign({},o),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(o=Object.assign(Object.assign({},o),{limit:e.limit}))):"afterbeforeraw"===n&&(o=e),Object.keys(o).length?t.encode(JSON.stringify(o)):void 0},X=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(H(n))return{after:n.skip,limit:n.limit};if(W(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Z=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return G(n)?n:void 0},ee=e=>"locally"in e,te=e=>"optimistically"in e,ne=e=>ee(e)||te(e),re=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),oe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},ae=(e,...t)=>({func:e,args:t}),se=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<$?$:t},ie=({func:e,args:t},n,r=se("cache_then_server"))=>{let o;const{lifeSpan:a}=se("cache_then_server",r.lifeSpan);if(ne(e)){try{o=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ce(void 0,{origin:"local",loading:!1,error:e}))}const r=re(o)&&oe(o,a);if(null==n||n(ce(o,{origin:"local",loading:!(ee(e)&&r)})),r)return}else null==n||n(ce(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ce(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ce(void 0,{origin:"server",loading:!1,error:e}))}))};function ce(e,t){return J(e)||re(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const le={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e})=>e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e},de=e=>le[e],ue={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",follows:"follow",followCounts:"followCount",feeds:"feed"};function he(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class pe extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,pe)}}class fe extends pe{constructor(e,t,n){super(e,t,n)}}class ge extends pe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class me extends pe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ye extends pe{constructor(e){super(e,800110,"error")}}let ve=null;const be=()=>{if(!ve)throw new pe("There is no active client",8e5,"fatal");return ve},we=e=>{ve=e},Ce=e=>{const{log:t,cache:n}=be();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=z(t);return V(e,n)})).map((e=>n.data[e]))},Ie=e=>{const{log:t,cache:n}=be();if(!n)return;t("cache/api/pullFromCache",e);const r=K(e);return n.data[r]?n.data[r]:void 0},_e=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:o}=be();if(!o)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&o.persistIf&&(n.offline=o.persistIf(e,t));const a=K(e);return o.data[a]=Object.assign({key:e,data:t},n),!0},Se=(e,t,n)=>{const{log:r,cache:o}=be();if(!o)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const a=Ie(e);if(!a)return!1;const s="function"==typeof t?t(a.data):Object.assign(Object.assign({},a.data),t);return i=a.data,!("updatedAt"in(c=s)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(_e(e,s,n),!0);var i,c},ke=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:o}=be();if(!o)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Ie(e)?Se(e,t,n):_e(e,t,n)},Ee=(e,t=!1)=>{const{log:n,cache:r}=be();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>z(e))).filter((t=>V(e,t))).map((e=>Ee(e,!0))).every((e=>e));const o=K(e);return o in r.data&&(delete r.data[o],!0)},Ae=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Te=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Me=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Oe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const o=de("channelUsers")({channelId:e.channelPublicId,userId:n}),a=null===(r=Ie(["channelUsers","get",o]))||void 0===r?void 0:r.data;return"member"===t?a&&"none"!==a.membership:!a||"none"===a.membership})),Pe=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const o=null===(r=Ie(["feed","get",de("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return o&&o.feedType===t})),Re=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const o=de("communityUsers")({communityId:e.communityId,userId:n}),a=null===(r=Ie(["communityUsers","get",o]))||void 0===r?void 0:r.data;return"member"===t?a&&"member"===a.communityMembership:!a||"none"!==a.communityMembership})),Ue=(e,t)=>{const n=[];return e.reduce(((e,r)=>{var o;if("text"===r.dataType&&!r.children.length)return e;if(n.includes(r.postId))return e;if((null==t?void 0:t.includes(r.dataType))&&e.push(r),!r.children.length)return e;const a=null===(o=Ie(["post","get",r.children[0]]))||void 0===o?void 0:o.data;return a?n.includes(a.postId)?e:(null==t?void 0:t.includes(null==a?void 0:a.dataType))?(n.push(a.postId),e.push(a),e):e:e}),[])},xe=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},je=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,De=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ne=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Be=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Fe=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),qe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Le=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ke=null;const ze=()=>{if(!Ke)throw new pe("Connect client first",8e5,"fatal");return Ke},Ve=e=>{Ke={_id:e._id,userId:e.userId,path:e.path}};let Qe,He=[];const We=e=>{clearTimeout(Qe),He.push(e),Qe=setTimeout((()=>{He.forEach((e=>e())),He=[]}),0)},Ge=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired","v3.video-streaming.didRecord","v3.video-streaming.didStart","v3.video-streaming.didStop"],Je=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Ye=(e,t,n,r)=>{const{log:o,emitter:a}=e,s=Date.now();o(`${t}(tmpid: ${s}) > listen`);const i=(...e)=>{o(`${t}(tmpid: ${s}) > trigger`,e);try{r(...e)}catch(e){o(`${t}(tmpid: ${s}) > error`,e)}};return a.on(n,i),()=>{o(`${t}(tmpid: ${s}) > dispose`),a.off(n,i)}},Xe=(e,t)=>{const{emitter:n}=be();We((()=>{n.emit(e,t)}))};let Ze,et;async function tt(){var e;const{mqtt:t,emitter:n,token:r}=be(),o=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",a=ze();Ze===o&&et===a._id||(Ze=o,et=a._id,await t.connect({accessToken:Ze,userId:et}),((e,t)=>{Je.forEach((n=>{e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var nt;e.SubscriptionLevels=void 0,(nt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",nt.POST="post",nt.COMMENT="comment",nt.POST_AND_COMMENT="post_and_comment",nt.USER="user";const rt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},ot=e=>e.path.split("/user/")[0],at=({path:t},n=e.SubscriptionLevels.USER)=>rt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),st=({channelId:e,subChannelId:t})=>{const n=ze();return`${ot(n)}/marker/channel/${e}/message/${t}`},it=()=>{const e=ze();return`${ot(e)}/marker/user/${e._id}`},ct=()=>ot(ze()),lt=()=>{const e=ze();return`${ot(e)}/smartfeed/${e._id}/channels`},dt=()=>{const e=ze();return`${ot(e)}/smartfeed/${e._id}/messagefeeds`},ut=()=>{const e=ze();return`${ot(e)}/smartfeed/${e._id}/messages`};function ht(e,t){const{mqtt:n}=be();return tt(),n.subscribe(e,t)}var pt;const ft="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:gt={}}=ft,mt="production"===(null===(pt=gt.env)||void 0===pt?void 0:pt.NODE_ENV),yt={EU:"eu",SG:"sg",US:"us"},vt={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function bt(e,t){return vt[e].replace("{region}",t)}var wt;!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(wt||(wt={}));const Ct=new AbortController,It=e=>{switch(e){case wt.UserGlobalBanned:throw new pe(e,400312,"fatal");case wt.UserDeleted:throw new pe(e,400100,"fatal");case wt.TokenExpired:throw Xe("tokenExpired","tokenExpired"),new pe(e,800403,"fatal");default:throw new pe("Request Aborted",8e5,"error")}},_t=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new m.default(t),httpsAgent:new a.HttpsAgent(t),signal:Ct.signal});return n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(Ct.abort(),It(wt.UserGlobalBanned)),r&&(Ct.abort(),It(wt.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(Ct.abort(wt.UserDeleted),It(wt.TokenExpired))}return e})),n.interceptors.response.use((e=>e),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&Xe("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new ge(e.code);if("error"===e.status)throw new fe(e.message,e.code,"error")})(null==r?void 0:r.data),Ct.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var St="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function kt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Et(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 At={exports:{}};At.exports=function(){function e(t,n,r){function o(s,i){if(!n[s]){if(!t[s]){if(!i&&Et)return Et(s);if(a)return a(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};t[s][0].call(l.exports,(function(e){return o(t[s][1][e]||e)}),l,l.exports,e,t,n,r)}return n[s].exports}for(var a=Et,s=0;s<r.length;s++)o(r[s]);return o}return e}()({1:[function(e,t,n){(function(n,r){(function(){const o=e("events").EventEmitter,a=e("./store"),s=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),g=e("xtend"),m=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function _(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(m("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function S(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){m("sendPacket :: packet: %O",t),m("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),m("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);m("sendPacket :: writeToStream result %s",r),!r&&n&&n!==M?(m("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(m("sendPacket :: invoking cb"),n())}function E(e){e&&(m("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function A(e){e&&(m("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function T(e,t,n,r){m("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let o,a=t;if("publish"===a.cmd&&(a=p(t),o=S(e,a),o))return n&&n(o);e.outgoingStore.put(a,(function(o){if(o)return n&&n(o);r(),k(e,t,n)}))}function M(e){m("nop ::",e)}function O(e,t){let n;const r=this;if(!(this instanceof O))return new O(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];m("MqttClient :: options.protocol",t.protocol),m("MqttClient :: options.protocolVersion",t.protocolVersion),m("MqttClient :: options.username",t.username),m("MqttClient :: options.keepalive",t.keepalive),m("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),m("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),m("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),m("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new a,this.incomingStore=t.incomingStore||new a,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?m("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new s(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();m("deliver :: entry %o",n);let o=null;if(!n)return void r._resubscribe();o=n.packet,m("deliver :: call _sendPacket for %o",o);let a=!0;o.messageId&&0!==o.messageId&&(r.messageIdProvider.register(o.messageId)||(a=!1)),a?r._sendPacket(o,(function(e){n.cb&&n.cb(e),t()})):(m("messageId: %d has already used. The message is skipped and removed.",o.messageId),t())}m("connect :: sending queued packets"),t()})),this.on("close",(function(){m("close :: connected set to `false`"),this.connected=!1,m("close :: clearing connackTimer"),clearTimeout(this.connackTimer),m("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),m("close :: calling _setupReconnect"),this._setupReconnect()})),o.call(this),m("MqttClient :: setting up stream"),this._setupStream()}u(O,o),O.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const o=[];function a(){if(o.length)y(s);else{const e=r;r=null,e()}}function s(){m("work :: getting next packet in queue");const t=o.shift();if(t)m("work :: packet pulled from queue"),e._handlePacket(t,a);else{m("work :: no packets in queue");const e=r;r=null,m("work :: done flag is %s",!!e),e&&e()}}function i(t){m("streamErrorHandler :: error",t.message),w.includes(t.code)?(m("streamErrorHandler :: emitting error"),e.emit("error",t)):M(t)}m("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),m("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){m("parser :: on packet push to packets array."),o.push(e)})),t._write=function(e,t,o){r=o,m("writable stream :: parsing buffer"),n.parse(e),s()},m("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){m("(%s)stream :: on close",e.options.clientId),A(e.outgoing),m("stream: emit close to MqttClient"),e.emit("close")})),m("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,g({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){m("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},O.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(m("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},O.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==M?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},O.prototype.publish=function(e,t,n,r){m("publish :: message `%s` to topic `%s`",t,e);const o=this.options;if("function"==typeof n&&(r=n,n=null),n=g({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const a=this,s=function(){let s=0;if((1===n.qos||2===n.qos)&&(s=a._nextId(),null===s))return m("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:s,dup:n.dup};switch(5===o.protocolVersion&&(i.properties=n.properties),m("publish :: qos",n.qos),n.qos){case 1:case 2:a.outgoing[i.messageId]={volatile:!1,cb:r||M},m("MqttClient:publish: packet cmd: %s",i.cmd),a._sendPacket(i,void 0,n.cbStorePut);break;default:m("MqttClient:publish: packet cmd: %s",i.cmd),a._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,cbStorePut:n.cbStorePut,callback:r}),this},O.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const o=r.resubscribe;let a=t.pop()||M,s=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof a&&(s=a,a=M);const c=f.validateTopics(r);if(null!==c)return v(a,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(a))return m("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),s=g(l,s),Array.isArray(r)?r.forEach((function(t){if(m("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<s.qos||o){const e={topic:t,qos:s.qos};5===i&&(e.nl=s.nl,e.rap=s.rap,e.rh=s.rh,e.properties=s.properties),m("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(m("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||o){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=s.properties),m("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return a(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(s.properties&&(r.properties=s.properties),e.options.resubscribe){m("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}a(e,n)}},m("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:a}),this},O.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||M,o=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(o=r,r=M);const a=f.validateTopics(n);if(null!==a)return v(r,new Error("Invalid topic "+a)),this;if(e._checkDisconnecting(r))return this;const s=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const a={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?a.unsubscriptions=[n]:Array.isArray(n)&&(a.unsubscriptions=n),e.options.resubscribe&&a.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof o&&o.properties&&(a.properties=o.properties),e.outgoing[a.messageId]={volatile:!0,cb:r},m("unsubscribe: call _sendPacket"),e._sendPacket(a),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,callback:r}),this},O.prototype.end=function(e,t,n){const r=this;function o(){m("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(m("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;m("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function a(){m("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{m("end :: finish :: calling process.nextTick on closeStores"),y(o.bind(r))}),t)}return m("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||M,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=M))),"object"!=typeof t&&(n=t,t=null),m("end :: cb? %s",!!n),n=n||M,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(m("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,a,10))):(m("end :: (%s) :: immediately calling finish",r.options.clientId),a()),this)},O.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},O.prototype.reconnect=function(e){m("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new a,t.outgoingStore=t.options.outgoingStore||new a,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},O.prototype._reconnect=function(){m("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),m("client already connected. disconnecting first.")):(m("_reconnect: calling _setupStream"),this._setupStream())},O.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(m("_setupReconnect :: emit `offline` state"),this.emit("offline"),m("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),m("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){m("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):m("_setupReconnect :: doing nothing...")},O.prototype._clearReconnect=function(){m("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},O.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(m("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),m("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&E(this.outgoing),m("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=g({cmd:"disconnect"},n);m("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(m("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(m("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(m("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},O.prototype._sendPacket=function(e,t,n){m("_sendPacket :: (%s) :: start",this.options.clientId),n=n||M,t=t||M;const r=_(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(m("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void T(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:T(this,e,t,n);break;default:k(this,e,t)}m("_sendPacket :: (%s) :: end",this.options.clientId)}},O.prototype._storePacket=function(e,t,n){m("_storePacket :: packet: %o",e),m("_storePacket :: cb? %s",!!t),n=n||M;let r=e;if("publish"===r.cmd){r=p(e);const n=S(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},O.prototype._setupPingTimer=function(){m("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},O.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},O.prototype._checkPing=function(){m("_checkPing :: checking ping..."),this.pingResp?(m("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(m("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},O.prototype._handlePingresp=function(){this.pingResp=!0},O.prototype._handleConnack=function(e){m("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},O.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},O.prototype.handleAuth=function(e,t){t()},O.prototype._handlePublish=function(e,t){m("_handlePublish: packet %o",e),t=void 0!==t?t:M;let n=e.topic.toString();const r=e.payload,o=e.qos,a=e.messageId,s=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return m("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,m("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));m("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(m("_handlePublish: qos %d",o),o){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?s.emit("error",n):-1===c.indexOf(r)?s.emit("error",new Error("Wrong reason code for pubrec")):void(r?s._sendPacket({cmd:"pubrec",messageId:a,reasonCode:r},t):s.incomingStore.put(e,(function(){s._sendPacket({cmd:"pubrec",messageId:a},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(o,i){return o instanceof Error||(i=o,o=null),o?s.emit("error",o):-1===c.indexOf(i)?s.emit("error",new Error("Wrong reason code for puback")):(i||s.emit("message",n,r,e),void s.handleMessage(e,(function(e){if(e)return t&&t(e);s._sendPacket({cmd:"puback",messageId:a,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:m("_handlePublish: unknown QoS. Doing nothing.")}},O.prototype.handleMessage=function(e,t){t()},O.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const o=this.outgoing[t]?this.outgoing[t].cb:null,a=this;let s;if(o){switch(m("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(s=new Error("Publish error: "+C[n]),s.code=n,o(s,e)),delete this.outgoing[t],this.outgoingStore.del(e,o),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(s=new Error("Publish error: "+C[n]),s.code=n,o(s,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete a._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),o(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),o(null);break;default:a.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else m("_handleAck :: Server sent an ack in error. Ignoring.")},O.prototype._handlePubrel=function(e,t){m("handling pubrel packet"),t=void 0!==t?t:M;const n=e.messageId,r=this,o={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(o,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,M),r._sendPacket(o,t)})))}))},O.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},O.prototype._nextId=function(){return this.messageIdProvider.allocate()},O.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},O.prototype._resubscribe=function(){m("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){m("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},O.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function o(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function a(){r.destroy(),r=null,t._flushStoreProcessingQueue(),o()}function s(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?s():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),s()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):m("messageId: %d has already used.",e.messageId)):r.once("readable",s)}t.once("close",a),r.on("error",(function(e){o(),t._flushStoreProcessingQueue(),t.removeListener("close",a),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(o(),t.removeListener("close",a),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),s()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},O.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},O.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},O.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=O}).call(this)}).call(this,e("_process"),void 0!==St?St:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),o=e("readable-stream").Transform,a=e("duplexify");let s,i,c,l=!1;function d(){const e=new o;return e._write=function(e,t,n){s.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){s.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,s.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),s.onSocketClose((function(){c.end(),c.destroy()})),s.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return s=t.my,s.connectSocket({url:r,protocols:n}),i=d(),c=a.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),o=e("debug")("mqttjs:tcp");function a(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,a=t.hostname;return o("port %d and host %s",n,a),r.createConnection(n,a)}t.exports=a},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),o=e("net"),a=e("debug")("mqttjs:tls");function s(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===o.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,a("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function s(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",s)})),n.on("error",s),n}t.exports=s},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),o=e("ws"),a=e("debug")("mqttjs:ws"),s=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){a("createWebSocket"),a("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return a("creating new Websocket for url: "+t+" and protocol: "+r),new o(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),o=new WebSocket(r,[n]);return o.binaryType="arraybuffer",o}function g(e,t){a("streamBuilder");const n=u(t),r=d(n,e),s=p(e,r,n),i=o.createWebSocketStream(s,n.wsOptions);return i.url=r,s.on("close",(()=>{i.destroy()})),i}function m(e,t){let n;a("browserStreamBuilder");const o=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=g(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function g(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function m(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>o&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=s(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",m):d.onopen=m),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?m:g}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),o=e("readable-stream").Transform,a=e("duplexify");let s,i,c;function l(){const e=new o;return e._write=function(e,t,n){s.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){s.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){s.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),s.onClose((function(){c.end(),c.destroy()})),s.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);s=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=a.obj(),c._destroy=function(e,t){s.close({success:function(){t&&t(e)}})};const o=c.destroy;return c.destroy=function(){c.destroy=o;const e=this;setTimeout((function(){s.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(c),h(),c}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),o=e("readable-stream").Readable,a={objectMode:!0},s={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(s,e),this._inflights=new Map}i.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},i.prototype.createStream=function(){const e=new o(a),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},i.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},i.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},i.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=i},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),o=e("number-allocator").NumberAllocator;function a(e){if(!(this instanceof a))return new a(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new o(1,e),this.max=e,this.length=0)}a.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},a.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},a.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},a.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},a.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=a},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function o(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:o}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),o=e("../store"),a=e("url"),s=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=a.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=s(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(l(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!c[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof c[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),i("calling streambuilder for",t.protocol),c[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const o=new r(n,t);return o.on("error",(function(){})),o}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(c.mqtt=e("./tcp"),c.tcp=e("./tcp"),c.ssl=e("./tls"),c.tls=e("./tls"),c.mqtts=e("./tls")):(c.wx=e("./wx"),c.wxs=e("./wx"),c.ali=e("./ali"),c.alis=e("./ali")),c.ws=e("./ws"),c.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=r,t.exports.Store=o}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=d,n.toByteArray=h,n.fromByteArray=g;for(var r=[],o=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=s.length;i<c;++i)r[i]=s[i],o[s.charCodeAt(i)]=i;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=l(e),s=r[0],i=r[1],c=new a(u(e,s,i)),d=0,h=i>0?s-4:s;for(n=0;n<h;n+=4)t=o[e.charCodeAt(n)]<<18|o[e.charCodeAt(n+1)]<<12|o[e.charCodeAt(n+2)]<<6|o[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function f(e,t,n){for(var r,o=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),o.push(p(r));return o.join("")}function g(e){for(var t,n=e.length,o=n%3,a=[],s=16383,i=0,c=n-o;i<c;i+=s)a.push(f(e,i,i+s>c?c:i+s));return 1===o?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),o=Symbol.for("BufferList");function a(e){if(!(this instanceof a))return new a(e);a._init.call(this,e)}a._init=function(e){Object.defineProperty(this,o,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},a.prototype._new=function(e){return new a(e)},a.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},a.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},a.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},a.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},a.prototype.copy=function(e,t,n,o){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof o||o>this.length)&&(o=this.length),n>=this.length)return e||r.alloc(0);if(o<=0)return e||r.alloc(0);const a=!!e,s=this._offset(n),i=o-n;let c=i,l=a&&t||0,d=s[1];if(0===n&&o===this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[s[0]].length-d)return a?this._bufs[s[0]].copy(e,t,d,d+c):this._bufs[s[0]].slice(d,d+c);a||(e=r.allocUnsafe(i));for(let t=s[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},a.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!==n[1]&&(o[0]=o[0].slice(n[1])),this._new(o)},a.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},a.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},a.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},a.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},a.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},a.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const o=this._offset(t);let a=o[0],s=o[1];for(;a<this._bufs.length;a++){const t=this._bufs[a];for(;s<t.length;)if(t.length-s>=e.length){const n=t.indexOf(e,s);if(-1!==n)return this._reverseOffset([a,n]);s=t.length-e.length+1}else{const t=this._reverseOffset([a,s]);if(this._match(t,e))return t;s++}s=0}return-1},a.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?a.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:a.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),a.prototype._isBufferList=function(e){return e instanceof a||a.isBufferList(e)},a.isBufferList=function(e){return null!=e&&e[o]},t.exports=a},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,o=e("inherits"),a=e("./BufferList");function s(e){if(!(this instanceof s))return new s(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}a._init.call(this,e),r.call(this)}o(s,r),Object.assign(s.prototype,a.prototype),s.prototype._new=function(e){return new s(e)},s.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},s.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},s.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},s.prototype._isBufferList=function(e){return e instanceof s||e instanceof a||s.isBufferList(e)},s.isBufferList=a.isBufferList,t.exports=s,t.exports.BufferListStream=s,t.exports.BufferList=a},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var o=2147483647;function a(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function s(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return p(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(J(e,ArrayBuffer)||e&&J(e.buffer,ArrayBuffer))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var o=g(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,n){return l(e),e<=0?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}function u(e){return l(e),s(e<0?0:0|m(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=s(n),o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}function p(e){for(var t=e.length<0?0:0|m(e.length),n=s(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,r}function g(e){if(i.isBuffer(e)){var t=0|m(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),i.alloc(+e)}function v(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||J(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(o)return r?-1:V(e).length;t=(""+t).toLowerCase(),o=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return j(this,t,n);case"utf8":case"utf-8":return O(this,t,n);case"ascii":return U(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return M(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:I(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,o){var a,s=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,i/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var d=-1;for(a=n;a<i;a++)if(l(e,a)===l(t,-1===d?0:a-d)){if(-1===d&&(d=a),a-d+1===c)return d*s}else-1!==d&&(a-=a-d),d=-1}else for(n+c>i&&(n=i-c),a=n;a>=0;a--){for(var u=!0,h=0;h<c;h++)if(l(e,a+h)!==l(t,h)){u=!1;break}if(u)return a}return-1}function _(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var a=t.length;r>a/2&&(r=a/2);for(var s=0;s<r;++s){var i=parseInt(t.substr(2*s,2),16);if(Y(i))return s;e[n+s]=i}return s}function S(e,t,n,r){return G(V(t,e.length-n),e,n,r)}function k(e,t,n,r){return G(Q(t),e,n,r)}function E(e,t,n,r){return k(e,t,n,r)}function A(e,t,n,r){return G(W(t),e,n,r)}function T(e,t,n,r){return G(H(t,e.length-n),e,n,r)}function M(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function O(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var a,s,i,c,l=e[o],d=null,u=l>239?4:l>223?3:l>191?2:1;if(o+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(a=e[o+1]))&&(c=(31&l)<<6|63&a)>127&&(d=c);break;case 3:a=e[o+1],s=e[o+2],128==(192&a)&&128==(192&s)&&(c=(15&l)<<12|(63&a)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[o+1],s=e[o+2],i=e[o+3],128==(192&a)&&128==(192&s)&&128==(192&i)&&(c=(15&l)<<18|(63&a)<<12|(63&s)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),o+=u}return R(r)}n.kMaxLength=o,i.TYPED_ARRAY_SUPPORT=a(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(J(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),J(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,o=0,a=Math.min(n,r);o<a;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=i.allocUnsafe(t),o=0;for(n=0;n<e.length;++n){var a=e[n];if(J(a,Uint8Array)&&(a=i.from(a)),!i.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,o),o+=a.length}return r},i.byteLength=v,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},i.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},i.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},i.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?O(this,0,e):b.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},i.prototype.compare=function(e,t,n,r,o){if(J(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(a,s),l=this.slice(r,o),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){a=l[u],s=d[u];break}return a<s?-1:s<a?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var a=!1;;)switch(r){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function R(e){var t=e.length;if(t<=P)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=P));return n}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function x(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function j(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",a=t;a<n;++a)o+=z(e[a]);return o}function D(e,t,n){for(var r=e.slice(t,n),o="",a=0;a<r.length;a+=2)o+=String.fromCharCode(r[a]+256*r[a+1]);return o}function N(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,n,r,o,a){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<a)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function F(e,t,n,r,o,a){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function q(e,t,n,o,a){return t=+t,n>>>=0,a||F(e,t,n,4),r.write(e,t,n,o,23,4),n+4}function L(e,t,n,o,a){return t=+t,n>>>=0,a||F(e,t,n,8),r.write(e,t,n,o,52,8),n+8}i.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=i.prototype,r},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],o=1,a=0;++a<t&&(o*=256);)r+=this[e+a]*o;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],o=1,a=0;++a<t&&(o*=256);)r+=this[e+a]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=t,o=1,a=this[e+--r];r>0&&(o*=256);)a+=this[e+--r]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},i.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,a=0;for(this[t]=255&e;++a<n&&(o*=256);)this[t+a]=e/o&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var o=n-1,a=1;for(this[t+o]=255&e;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);B(this,e,t,n,o-1,-o)}var a=0,s=1,i=0;for(this[t]=255&e;++a<n&&(s*=256);)e<0&&0===i&&0!==this[t+a-1]&&(i=1),this[t+a]=(e/s>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);B(this,e,t,n,o-1,-o)}var a=n-1,s=1,i=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===i&&0!==this[t+a+1]&&(i=1),this[t+a]=(e/s>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return q(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return q(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var a=o-1;a>=0;--a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return o},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var o=e.charCodeAt(0);("utf8"===r&&o<128||"latin1"===r)&&(e=o)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{var s=i.isBuffer(e)?e:i.from(e,r),c=s.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=s[a%c]}return this};var $=/[^+/0-9A-Za-z-_]/g;function K(e){if((e=(e=e.split("=")[0]).trim().replace($,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function z(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){var n;t=t||1/0;for(var r=e.length,o=null,a=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&a.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function Q(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,r,o,a=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,o=n%256,a.push(o),a.push(r);return a}function W(e){return t.toByteArray(K(e))}function G(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function J(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function a(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(o=r))})),e.splice(o,0,n)}function s(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function i(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=a,n.save=s,n.load=i,n.useColors=o,n.storage=c(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:l}=t.exports;l.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,a,s=null;function i(...e){if(!i.enabled)return;const n=i,o=Number(new Date),a=o-(t||o);n.diff=a,n.prev=t,n.curr=o,t=o,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,o)=>{if("%%"===t)return"%";s++;const a=r.formatters[o];if("function"==typeof a){const r=e[s];t=a.call(n,r),e.splice(s,1),s--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return i.namespace=e,i.useColors=r.useColors(),i.color=r.selectColor(e),i.extend=o,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(n!==r.namespaces&&(n=r.namespaces,a=r.enabled(e)),a),set:e=>{s=e}}),"function"==typeof r.init&&r.init(i),i}function o(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function a(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(t=0;t<o;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function s(){const e=[...r.names.map(c),...r.skips.map(c).map((e=>"-"+e))].join(",");return r.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function c(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function l(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=l,r.disable=s,r.enable=a,r.enabled=i,r.humanize=e("ms"),r.destroy=d,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var o=e("readable-stream"),a=e("end-of-stream"),s=e("inherits"),i=e("stream-shift"),c=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),l=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(n){n?d(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},p=function(){},f=function(e){return new o.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},g=function(e,t,n){if(!(this instanceof g))return new g(e,t,n);o.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};s(g,o.Duplex),g.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new g(e,t,n)},g.prototype.cork=function(){1==++this._corked&&this.emit("cork")},g.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},g.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=a(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),o=function(){var e=t._ondrain;t._ondrain=null,e&&e()},s=function(){t._writable.removeListener("drain",o),r()};this._unwrite&&n.nextTick(o),this._writable=e,this._writable.on("drain",o),this._unwrite=s,this.uncork()}else this.end()},g.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=a(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},o=function(){t.push(null)},s=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",o),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",o),this._unread=s,this._forward()}},g.prototype._read=function(){this._drained=!0,this._forward()},g.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=i(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},g.prototype.destroy=function(e,t){if(t||(t=p),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},g.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},g.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?l(this,this._write.bind(this,e,t,n)):e===c?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},g.prototype._finish=function(e){var t=this;this.emit("preend"),l(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),l(t,e)}))}))},g.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(c),o.Writable.prototype.end.call(this,n))},t.exports=g}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),o=function(){},a=function(e){return e.setHeader&&"function"==typeof e.abort},s=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},i=function(e,t,c){if("function"==typeof t)return i(e,null,t);t||(t={}),c=r(c||o);var l=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,p=!1,f=function(){e.writable||g()},g=function(){h=!1,u||c.call(e)},m=function(){u=!1,h||c.call(e)},y=function(t){c.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){c.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!p)return(!u||d&&d.ended&&!d.destroyed)&&(!h||l&&l.ended&&!l.destroyed)?void 0:c.call(e,new Error("premature close"))},C=function(){e.req.on("finish",g)};return a(e)?(e.on("complete",g),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),s(e)&&e.on("exit",y),e.on("end",m),e.on("finish",g),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",g),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",g),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",g),e.removeListener("exit",y),e.removeListener("end",m),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=i}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||S,o=Object.keys||k,a=Function.prototype.bind||E;function s(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._maxListeners=void 0;var i,c=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),i=0===l.x}catch(e){i=!1}function d(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,o=I(e,r),a=0;a<r;++a)o[a].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var o=e.length,a=I(e,o),s=0;s<o;++s)a[s].call(n,r)}function p(e,t,n,r,o){if(t)e.call(n,r,o);else for(var a=e.length,s=I(e,a),i=0;i<a;++i)s[i].call(n,r,o)}function f(e,t,n,r,o,a){if(t)e.call(n,r,o,a);else for(var s=e.length,i=I(e,s),c=0;c<s;++c)i[c].call(n,r,o,a)}function g(e,t,n,r){if(t)e.apply(n,r);else for(var o=e.length,a=I(e,o),s=0;s<o;++s)a[s].apply(n,r)}function m(e,t,n,o){var a,s,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),i=s[t]):(s=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=s[t]=o?[n,i]:[i,n]:o?i.unshift(n):i.push(n),!i.warned&&(a=d(e))&&a>0&&i.length>a){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=s[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=a.call(y,r);return o.listener=n,r.wrapFn=o,o}function b(e,t,n){var r=e._events;if(!r)return[];var o=r[t];return o?"function"==typeof o?n?[o.listener||o]:[o]:n?_(o):I(o,o.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=t,r=n+1,o=e.length;r<o;n+=1,r+=1)e[n]=e[r];e.pop()}function I(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function S(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function E(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');c=e}}):s.defaultMaxListeners=c,s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(e){var t,n,r,o,a,s,i="error"===e;if(s=this._events)i=i&&null==s.error;else if(!i)return!1;if(i){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var c=new Error('Unhandled "error" event. ('+t+")");throw c.context=t,c}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:u(n,l,this);break;case 2:h(n,l,this,arguments[1]);break;case 3:p(n,l,this,arguments[1],arguments[2]);break;case 4:f(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(r-1),a=1;a<r;a++)o[a-1]=arguments[a];g(n,l,this,o)}return!0},s.prototype.addListener=function(e,t){return m(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return m(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,o,a,s,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(o=this._events))return this;if(!(n=o[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete o[e],o.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(a=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){i=n[s].listener,a=s;break}if(a<0)return this;0===a?n.shift():C(n,a),1===n.length&&(o[e]=n[0]),o.removeListener&&this.emit("removeListener",e,i||t)}return this},s.prototype.removeAllListeners=function(e){var t,n,a;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var s,i=o(n);for(a=0;a<i.length;++a)"removeListener"!==(s=i[a])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(a=t.length-1;a>=0;a--)this.removeListener(e,t[a]);return this},s.prototype.listeners=function(e){return b(this,e,!0)},s.prototype.rawListeners=function(e){return b(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},s.prototype.listenerCount=w,s.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
3
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
4
- n.read=function(e,t,n,r,s){var i,o,a=8*s-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?s-1:0,h=n?-1:1,f=e[t+d];for(d+=h,i=f&(1<<-u)-1,f>>=-u,u+=a;u>0;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),i-=c}return(f?-1:1)*o*Math.pow(2,i-r)},n.write=function(e,t,n,r,s,i){var o,a,l,c=8*i-s-1,u=(1<<c)-1,d=u>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(o++,l/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*l-1)*Math.pow(2,s),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;e[n+f]=255&a,f+=p,a/=256,s-=8);for(o=o<<s|a,c+=s;c>0;e[n+f]=255&o,f+=p,o/=256,c-=8);e[n+f-p]|=128*g}},{}],24:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var s=r.leftChild,i=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=i,t&&(t.brother=r),this.parent=r,this.brother=i,this.leftChild=n,this.rightChild=s,i&&(i.parent=r,i.brother=this),n&&(n.parent=this,n.brother=s),s&&(s.parent=this,s.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,s=n.leftChild,i=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=s,n.rightChild=this,t&&(t.brother=n),s&&(s.parent=n,s.brother=this),this.parent=n,this.brother=s,this.leftChild=i,this.rightChild=r,i&&(i.parent=this,i.brother=r),r&&(r.parent=this,r.brother=i),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}};function s(e){var t=this;void 0===e&&(e=[]);var n=[],i=0,o=0,a=0,l=0,c=0,u=0;this.size=function(){return u},this.empty=function(){return 0===u},this.clear=function(){i=a=o=l=c=u=0,h.call(this,s.bucketSize),u=0},this.front=function(){return n[i][o]},this.back=function(){return n[a][l]},this.forEach=function(e){if(!this.empty()){var t=0;if(i!==a){for(c=o;c<s.bucketSize;++c)e(n[i][c],t++);for(c=i+1;c<a;++c)for(var r=0;r<s.bucketSize;++r)e(n[c][r],t++);for(c=0;c<=l;++c)e(n[a][c],t++)}else for(var c=o;c<=l;++c)e(n[i][c],t++)}};var d=function(e){var t=i*s.bucketSize+o,n=t+e,r=a*s.bucketSize+l;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/s.bucketSize),curNodePointerIndex:n%s.bucketSize}};this.getElementByPos=function(e){var t=d(e),r=t.curNodeBucketIndex,s=t.curNodePointerIndex;return n[r][s]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>u)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<u;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*s.sigma,d=Math.max(Math.ceil(r/s.bucketSize),2),h=0;h<d;++h)t.push(new Array(s.bucketSize));var f=Math.ceil(e/s.bucketSize),p=Math.floor(d/2)-Math.floor(f/2),g=p,m=0;if(this.size())for(h=0;h<f;++h){for(var y=0;y<s.bucketSize;++y)if(t[p+h][y]=this.front(),this.popFront(),this.empty()){g=p+h,m=y;break}if(this.empty())break}n=t,i=p,o=0,a=g,l=m,c=d,u=e};this.pushBack=function(e){this.empty()||(a===c-1&&l===s.bucketSize-1&&h.call(this,this.size()),l<s.bucketSize-1?++l:a<c-1&&(++a,l=0)),++u,n[a][l]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(l>0?--l:i<a&&(--a,l=s.bucketSize-1)),u>0&&--u)},this.setElementByPos=function(e,t){var r=d(e),s=r.curNodeBucketIndex,i=r.curNodePointerIndex;n[s][i]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var s=[],i=e;i<u;++i)s.push(this.getElementByPos(i));for(this.cut(e-1),i=0;i<n;++i)this.pushBack(t);s.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(i===a){for(var t=o;t<=l;++t)if(n[i][t]===e)return!0;return!1}for(t=o;t<s.bucketSize;++t)if(n[i][t]===e)return!0;for(t=i+1;t<a;++t)for(var r=0;r<s.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=l;++t)if(n[a][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=u-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<u;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<u;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===i&&0===o&&h.call(this,this.size()),o>0?--o:i>0&&(--i,o=s.bucketSize-1)),++u,n[i][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<s.bucketSize-1?++o:i<a&&(++i,o=0)),u>0&&--u)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var i=Math.ceil(r/s.bucketSize),o=0;o<i;++o)n.push(new Array(s.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=d(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;a=n,l=r,u=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===u)return[2];if(i!==a)return[3,5];t=o,r.label=1;case 1:return t<=l?[4,n[i][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=o,r.label=6;case 6:return t<s.bucketSize?[4,n[i][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=i+1,r.label=10;case 10:if(!(t<a))return[3,15];e=0,r.label=11;case 11:return e<s.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=l?[4,n[a][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=s.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var o=r*s.sigma;c=Math.ceil(o/s.bucketSize),c=Math.max(c,3);for(var l=0;l<c;++l)n.push(new Array(s.bucketSize));var u=Math.ceil(r/s.bucketSize);i=Math.floor(c/2)-Math.floor(u/2),a=i,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),s.sigma=3,s.bucketSize=5e3,Object.freeze(s),n.default=s},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var i=e("../LinkList/LinkList"),o=e("../Map/Map");function a(e,t,n){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.initSize),n=n||function(e){var t,n,r=0,i="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{i="string"!=typeof e?JSON.stringify(e):e;try{for(var o=s(i),a=o.next();!a.done;a=o.next())r=(r<<5)-r+a.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.forEach((function(r,s){if(!r.empty()){if(r instanceof i.default&&1===r.size()){var l=r.front(),c=l.key,h=l.value;t[n(c)&d-1]=new i.default([{key:c,value:h}])}else if(r instanceof o.default){var f=new i.default,p=new i.default;r.forEach((function(t){0==(n(t.key)&e)?f.pushBack(t):p.pushBack(t)})),f.size()>a.untreeifyThreshold?t[s]=new o.default(f):f.size()&&(t[s]=f),p.size()>a.untreeifyThreshold?t[s+e]=new o.default(p):p.size()&&(t[s+e]=p)}else{var g=new i.default,m=new i.default;r.forEach((function(t){0==(n(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[s]=g),m.size()&&(t[s+e]=m)}u[s].clear()}})),u=t}};this.setElement=function(e,t){var r,l;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var f=n(e)&d-1;if(u[f]){var p=u[f].size();if(u[f]instanceof i.default){try{for(var g=s(u[f]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{m&&!m.done&&(l=g.return)&&l.call(g)}finally{if(r)throw r.error}}u[f].pushBack({key:e,value:t}),u[f].size()>=a.treeifyThreshold&&(u[f]=new o.default(u[f]))}else u[f].setElement(e,t);var v=u[f].size();c+=v-p}else++c,u[f]=new i.default([{key:e,value:t}]);c>d*a.sigma&&h.call(this,d)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,i=n(e)&d-1;if(u[i]){if(u[i]instanceof o.default)return u[i].getElementByKey(e);try{for(var a=s(u[i]),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.key===e)return c.value}}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,l=n(e)&d-1;if(u[l]){var h=u[l].size();if(u[l]instanceof o.default)u[l].eraseElementByKey(e),u[l].size()<=a.untreeifyThreshold&&(u[l]=new i.default(u[l]));else{var f=-1;try{for(var p=s(u[l]),g=p.next();!g.done;g=p.next()){var m=g.value;if(++f,m.key===e){u[l].eraseElementByPos(f);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(r=p.return)&&r.call(p)}finally{if(t)throw t.error}}}var y=u[l].size();c+=y-h}},this.find=function(e){var t,r,i=n(e)&d-1;if(!u[i])return!1;if(u[i]instanceof o.default)return u[i].find(e);try{for(var a=s(u[i]),l=a.next();!l.done;l=a.next())if(l.value.key===e)return!0}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,i,o,a;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=s(u[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return i=r.sent(),o={error:i},[3,9];case 8:try{n&&!n.done&&(a=t.return)&&a.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return l.setElement(t,n)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),n.default=a},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var i=e("../Set/Set"),o=e("../LinkList/LinkList");function a(e,t,n){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.forEach((function(r,s){if(!r.empty()){if(r instanceof o.default&&1===r.size()){var l=r.front();if(void 0===l)throw new Error("unknown error");t[n(l)&d-1]=new o.default([l])}else if(r instanceof i.default){var c=new o.default,h=new o.default;r.forEach((function(t){0==(n(t)&e)?c.pushBack(t):h.pushBack(t)})),c.size()>a.untreeifyThreshold?t[s]=new i.default(c):c.size()&&(t[s]=c),h.size()>a.untreeifyThreshold?t[s+e]=new i.default(h):h.size()&&(t[s+e]=h)}else{var f=new o.default,p=new o.default;r.forEach((function(t){0==(n(t)&e)?f.pushBack(t):p.pushBack(t)})),f.size()&&(t[s]=f),p.size()&&(t[s+e]=p)}u[s].clear()}})),u=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&d-1;if(u[t]){var r=u[t].size();if(u[t]instanceof o.default){if(u[t].find(e))return;u[t].pushBack(e),u[t].size()>=a.treeifyThreshold&&(u[t]=new i.default(u[t]))}else u[t].insert(e);var s=u[t].size();c+=s-r}else u[t]=new o.default([e]),++c;c>d*a.sigma&&h.call(this,d)},this.eraseElementByValue=function(e){var t=n(e)&d-1;if(u[t]){var r=u[t].size();u[t].eraseElementByValue(e),u[t]instanceof i.default&&u[t].size()<=a.untreeifyThreshold&&(u[t]=new o.default(u[t]));var s=u[t].size();c+=s-r}},this.find=function(e){var t=n(e)&d-1;return!!u[t]&&u[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,i,o,a;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=s(u[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return i=r.sent(),o={error:i},[3,9];case 8:try{n&&!n.done&&(a=t.return)&&a.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return l.insert(e)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),n.default=a},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var s=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){i=o=void 0,n=0},this.front=function(){return null==i?void 0:i.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=i,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=i;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=i;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var r=t.pre,s=t.next;s.pre=r,r.next=s,n>0&&--n}},this.eraseElementByValue=function(e){for(;i&&i.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(i)for(var t=i;t;){if(t.value===e){var r=t.pre,s=t.next;s&&(s.pre=r),r&&(r.next=s),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);o?(o.next=t,t.pre=o,o=t):i=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(i===o?i=o=void 0:(o=o.pre)&&(o.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=i;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var o=i,a=1;a<e;++a){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var l=o.next;for(n+=r;r--;)o.next=new s(t),o.next.pre=o,o=o.next;o.next=l,l&&(l.pre=o)}},this.find=function(e){for(var t=i;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=i,t=o,r=0;e&&t&&2*r<n;){var s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=i;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=i;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);i?(t.next=i,i.pre=t,i=t):i=o=t},this.popFront=function(){i&&(n>0&&--n,i&&(i===o?i=o=void 0:(i=i.next)&&(i.pre=void 0)))},this.merge=function(e){var t=this,r=i;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=o;else if(r===i)t.pushFront(e),r=i;else{++n;var a=r.pre;a&&(a.next=new s(e),a.next.pre=a,a.next.next=r,r&&(r.pre=a.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=i,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(i),n.default=i},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var i=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,a=new i.default;a.color=i.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,a.key=a.value=void 0,a.leftChild=a.rightChild=a.brother=void 0};var l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?l(e.leftChild):e},c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?c(e.rightChild):e};this.front=function(){if(!this.empty()){var e=l(a);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=c(a);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,n,r=0;try{for(var i=s(this),o=i.next();!o.done;o=i.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var i=s(this),o=i.next();!o.done;o=i.next()){var a=o.value;if(r===e)return a;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return u(a,e)};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return d(a,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(a,e)};var f=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?f(e.leftChild,n):f(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return f(a,e)};var p=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(e.color!==i.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===i.default.TreeNodeColorType.red){n.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red;var r=t.rotateLeft();a===t&&(a=r),p(e)}else n.color===i.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===i.default.TreeNodeColorType.red?(n.color=t.color,t.color=i.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=i.default.TreeNodeColorType.black),r=t.rotateLeft(),a===t&&(a=r),e.color=i.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==i.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||(n.color=i.default.TreeNodeColorType.red,p(t)):(n.color=i.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=i.default.TreeNodeColorType.black),r=n.rotateRight(),a===n&&(a=r),p(e)));else e===t.rightChild&&(n.color===i.default.TreeNodeColorType.red?(n.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red,r=t.rotateRight(),a===t&&(a=r),p(e)):n.color===i.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===i.default.TreeNodeColorType.red?(n.color=t.color,t.color=i.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=i.default.TreeNodeColorType.black),r=t.rotateRight(),a===t&&(a=r),e.color=i.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==i.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||(n.color=i.default.TreeNodeColorType.red,p(t)):(n.color=i.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=i.default.TreeNodeColorType.black),r=n.rotateLeft(),a===n&&(a=r),p(e))))}else e.color=i.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=l(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=c(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}p(t),t&&t.remove(),--o,a.color=i.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;m(a,(function(n){return e===t?(g(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(a,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&g(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new i.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new i.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(t.color!==i.default.TreeNodeColorType.black&&t.color===i.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===i.default.TreeNodeColorType.red)n.color=t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red,v(r);else if(!n||n.color===i.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red;var s=r.rotateRight();r===a&&(a=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===a&&(a=s),v(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===a&&(a=s),v(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red,s=r.rotateLeft(),r===a&&(a=s)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++o,a.key=e,a.value=n,void(a.color=i.default.TreeNodeColorType.black);var r=y(a,e);void 0===r.key||0!==t(r.key,e)?(++o,r.key=e,r.value=n,v(r),a.color=i.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(a,e)},this.getElementByKey=function(e){var t=b(a,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var n=e.key,r=e.value;return t.setElement(n,r)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(a)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(a)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,s=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var s=n[e];n[e]=n[t],n[t]=s},i=function(e){if(e<0||e>=r)throw new Error("unknown error");var i=2*e+1,o=2*e+2;i<r&&t(n[e],n[i])>0&&s(e,i),o<r&&t(n[e],n[o])>0&&s(e,o)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var i=e,o=2*i+1;o<r;){var a=o+1,l=o;if(a<r&&t(n[o],n[a])>0&&(l=a),t(n[i],n[l])<=0)break;s(i,l),o=2*(i=l)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var s=r-1;s>0;){var o=Math.floor((s-1)/2);if(t(n[o],e)<=0)break;i(o),s=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var s=0;s<this.size();){var i=2*s+1,o=2*s+2;if(i>=this.size())break;var a=i;if(o<this.size()&&t(n[i],n[o])>0&&(a=o),t(n[a],e)>=0)break;n[s]=n[a],s=a}n[s]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function s(e){void 0===e&&(e=[]);var t=new r.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(s),n.default=s},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var i=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,a=new i.default;a.color=i.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,a.key=void 0,a.leftChild=a.rightChild=a.brother=a.parent=void 0,a.color=i.default.TreeNodeColorType.black};var l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?l(e.leftChild):e},c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?c(e.rightChild):e};this.front=function(){if(!this.empty())return l(a).key},this.back=function(){if(!this.empty())return c(a).key},this.forEach=function(e){var t,n,r=0;try{for(var i=s(this),o=i.next();!o.done;o=i.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var i=s(this),o=i.next();!o.done;o=i.next()){var a=o.value;if(r===e)return a;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}throw new Error("unknown error")};var u=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(e.color!==i.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===i.default.TreeNodeColorType.red){n.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red;var r=t.rotateLeft();a===t&&(a=r),u(e)}else n.color===i.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===i.default.TreeNodeColorType.red?(n.color=t.color,t.color=i.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=i.default.TreeNodeColorType.black),r=t.rotateLeft(),a===t&&(a=r),e.color=i.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==i.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||(n.color=i.default.TreeNodeColorType.red,u(t)):(n.color=i.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=i.default.TreeNodeColorType.black),r=n.rotateRight(),a===n&&(a=r),u(e)));else e===t.rightChild&&(n.color===i.default.TreeNodeColorType.red?(n.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red,r=t.rotateRight(),a===t&&(a=r),u(e)):n.color===i.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===i.default.TreeNodeColorType.red?(n.color=t.color,t.color=i.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=i.default.TreeNodeColorType.black),r=t.rotateRight(),a===t&&(a=r),e.color=i.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==i.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==i.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==i.default.TreeNodeColorType.black||(n.color=i.default.TreeNodeColorType.red,u(t)):(n.color=i.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=i.default.TreeNodeColorType.black),r=n.rotateLeft(),a===n&&(a=r),u(e))))}else e.color=i.default.TreeNodeColorType.black},d=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=l(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=c(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}u(t),t&&t.remove(),--o,a.color=i.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;h(a,(function(n){return e===t?(d(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=g(a,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&d(n)}};var f=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?f(e.leftChild,n):(e.leftChild=new i.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?f(e.rightChild,n):(e.rightChild=new i.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},p=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(t.color!==i.default.TreeNodeColorType.black&&t.color===i.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===i.default.TreeNodeColorType.red)n.color=t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red,p(r);else if(!n||n.color===i.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red;var s=r.rotateRight();r===a&&(a=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===a&&(a=s),p(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===a&&(a=s),p(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,r.color=i.default.TreeNodeColorType.red,s=r.rotateLeft(),r===a&&(a=s)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++o,a.key=e,void(a.color=i.default.TreeNodeColorType.black);var n=f(a,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,p(n),a.color=i.default.TreeNodeColorType.black)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?g(e.leftChild,n):r>0?g(e.rightChild,n):e}};this.find=function(e){var n=g(a,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return m(e.rightChild,n);var s=m(e.leftChild,n);return void 0!==s?s:e.key}};this.lowerBound=function(e){return m(a,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(a,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var s=v(e.rightChild,n);return void 0!==s?s:e.key}};this.reverseLowerBound=function(e){return v(a,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(a,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(a)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(a)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,i=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o},i=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,s=0,i=t.length;s<i;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,a.length=0},this.front=function(){if(!this.empty())return a[0]},this.back=function(){if(!this.empty())return a[n-1]},this.forEach=function(e){a.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return a[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)a[t]=a[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){a[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){a.push(e),++n},this.popBack=function(){a.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");a[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");a.splice.apply(a,i([e,0],s(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return a.includes(e)},this.reverse=function(){a.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){a[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){a.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,o(a)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var s=e("./Stack/Stack");n.Stack=s.default;var i=e("./Queue/Queue");n.Queue=i.default;var o=e("./LinkList/LinkList");n.LinkList=o.default;var a=e("./Deque/Deque");n.Deque=a.default;var l=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=l.default;var c=e("./Set/Set");n.Set=c.default;var u=e("./Map/Map");n.Map=u.default;var d=e("./HashSet/HashSet");n.HashSet=d.default;var h=e("./HashMap/HashMap");n.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,n){const r=e("yallist"),s=Symbol("max"),i=Symbol("length"),o=Symbol("lengthCalculator"),a=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),u=Symbol("noDisposeOnSet"),d=Symbol("lruList"),h=Symbol("cache"),f=Symbol("updateAgeOnGet"),p=()=>1;class g{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[s]=e.max||1/0;const t=e.length||p;if(this[o]="function"!=typeof t?p:t,this[a]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[l]=e.maxAge||0,this[c]=e.dispose,this[u]=e.noDisposeOnSet||!1,this[f]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[s]=e||1/0,v(this)}get max(){return this[s]}set allowStale(e){this[a]=!!e}get allowStale(){return this[a]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[l]=e,v(this)}get maxAge(){return this[l]}set lengthCalculator(e){"function"!=typeof e&&(e=p),e!==this[o]&&(this[o]=e,this[i]=0,this[d].forEach((e=>{e.length=this[o](e.value,e.key),this[i]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[i]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let n=this[d].tail;null!==n;){const r=n.prev;E(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[d].head;null!==n;){const r=n.next;E(this,e,n,t),n=r}}keys(){return this[d].toArray().map((e=>e.key))}values(){return this[d].toArray().map((e=>e.value))}reset(){this[c]&&this[d]&&this[d].length&&this[d].forEach((e=>this[c](e.key,e.value))),this[h]=new Map,this[d]=new r,this[i]=0}dump(){return this[d].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[d]}set(e,t,n){if((n=n||this[l])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,a=this[o](t,e);if(this[h].has(e)){if(a>this[s])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[c]&&(this[u]||this[c](e,o.value)),o.now=r,o.maxAge=n,o.value=t,this[i]+=a-o.length,o.length=a,this.get(e),v(this),!0}const f=new w(e,t,a,r,n);return f.length>this[s]?(this[c]&&this[c](e,t),!1):(this[i]+=f.length,this[d].unshift(f),this[h].set(e,this[d].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[d].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],s=r.e||0;if(0===s)this.set(r.k,r.v);else{const e=s-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[a])return}else n&&(e[f]&&(r.value.now=Date.now()),e[d].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[l])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[l]&&n>e[l]},v=e=>{if(e[i]>e[s])for(let t=e[d].tail;e[i]>e[s]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[c]&&e[c](n.key,n.value),e[i]-=n.length,e[h].delete(n.key),e[d].removeNode(t)}};class w{constructor(e,t,n,r,s){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=s||0}}const E=(e,t,n,r)=>{let s=n.value;y(e,s)&&(b(e,n),e[a]||(s=void 0)),s&&t.call(r,s.value,s.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((s=>[0,1].map((i=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(s?n.DUP_MASK:0)|r<<n.QOS_SHIFT|i,0,!0),o}))))))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),s=e("events");function i(e,t){const n=new o;return r(e,n,t),n.concat()}class o extends s{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let s,i=0;for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?t[s]=r[s].length:t[s]=n.byteLength(r[s]),e+=t[s];const o=n.allocUnsafe(e);for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?(r[s].copy(o,i),i+=t[s]):(o.write(r[s],i),i+=t[s]);return o}}t.exports=i}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},s=e.isBuffer(e.from([1,2]).subarray(0,1));function i(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function o(){for(let e=0;e<n;e++)r[e]=i(e)}function a(t){const n=4;let r=0,i=0;const o=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),o.writeUInt8(r,i++)}while(t>0&&i<n);return t>0&&(i=0),s?o.subarray(0,i):o.slice(0,i)}function l(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:o,generateNumber:i,genBufVariableByteInt:a,generate4ByteBuffer:l}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),s=e("events"),i=e("./packet"),o=e("./constants"),a=e("debug")("mqtt-packet:parser");class l extends s{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof l?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new l).parser(e)}_resetState(){a("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),a("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),a("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),a("_parseLength %d",e.value),!!e}_parsePayload(){a("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return a("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;a("_parseConnect");const s={},i=this.packet,l=this._parseString();if(null===l)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==l&&"MQIsdp"!==l)return this._emitError(new Error("Invalid protocolId"));if(i.protocolId=l,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(i.protocolVersion=this._list.readUInt8(this._pos),i.protocolVersion>=128&&(i.bridgeMode=!0,i.protocolVersion=i.protocolVersion-128),3!==i.protocolVersion&&4!==i.protocolVersion&&5!==i.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,s.will&&(i.will={},i.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),i.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),i.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,i.keepalive=this._parseNum(),-1===i.keepalive)return this._emitError(new Error("Packet too short"));if(5===i.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(i.properties=e)}const c=this._parseString();if(null===c)return this._emitError(new Error("Packet too short"));if(i.clientId=c,a("_parseConnect: packet.clientId: %s",i.clientId),s.will){if(5===i.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(i.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(i.will.topic=e,a("_parseConnect: packet.will.topic: %s",i.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));i.will.payload=t,a("_parseConnect: packet.will.paylaod: %s",i.will.payload)}if(s.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));i.username=r,a("_parseConnect: packet.username: %s",i.username)}if(s.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));i.password=n}return this.settings=i,a("_parseConnect: complete"),i}_parseConnack(){a("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}a("_parseConnack: complete")}_parsePublish(){a("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),a("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){a("_parseSubscribe");const e=this.packet;let t,n,r,s,i,l,c;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),r=n&o.SUBSCRIBE_OPTIONS_QOS_MASK,l=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),i=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),s=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,c={topic:t,qos:r},5===this.settings.protocolVersion?(c.nl=l,c.rap=i,c.rh=s):this.settings.bridgeMode&&(c.rh=0,c.rap=!0,c.nl=!0),a("_parseSubscribe: push subscription `%s` to subscription",c),e.subscriptions.push(c)}}}_parseSuback(){a("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){a("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));a("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){a("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){a("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),a("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(a("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return a("_parseDisconnect result: true"),!0}_parseAuth(){a("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),a("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(a("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,a("_parseString: result: %s",r),r}_parseStringPair(){return a("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const n=this._list.slice(this._pos,t);return this._pos+=e,a("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,a("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,a("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){a("_parseVarByteNum");const t=4;let n,r=0,s=1,i=0,l=!1;const c=this._pos?this._pos:0;for(;r<t&&c+r<this._list.length;){if(n=this._list.readUInt8(c+r++),i+=s*(n&o.VARBYTEINT_MASK),s*=128,0==(n&o.VARBYTEINT_FIN_MASK)){l=!0;break}if(this._list.length<=r)break}return!l&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),c&&(this._pos+=r),l=!!l&&(e?{bytes:r,value:i}:i),a("_parseVarByteNum: result: %o",l),l}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),a("_parseByte: result: %o",e),e}_parseByType(e){switch(a("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){a("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=o.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(o.propertiesTypes[t]))):n[t]=this._parseByType(o.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(o.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return a("_newPacket"),this.packet&&(this._list.consume(this.packet.length),a("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),a("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(e){a("_emitError"),this.error=e,this.emit("error",e)}}t.exports=l},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),s=n.allocUnsafe(0),i=n.from([0]),o=e("./numbers"),a=e("process-nextick-args").nextTick,l=e("debug")("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,h=o.genBufVariableByteInt,f=o.generate4ByteBuffer;let p=x,g=!0;function m(e,t,n){switch(l("generate called"),t.cork&&(t.cork(),a(y,t)),g&&(g=!1,d()),l("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return E(e,t,n);case"subscribe":return S(e,t,n);case"suback":return C(e,t,n);case"unsubscribe":return T(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return _(e,t);case"disconnect":return I(e,t,n);case"auth":return A(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,s){const i=e||{},o=i.protocolId||"MQTT";let a=i.protocolVersion||4;const l=i.will;let c=i.clean;const u=i.keepalive||0,d=i.clientId||"",h=i.username,f=i.password,g=i.properties;void 0===c&&(c=!0);let m=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=o.length+2,3!==a&&4!==a&&5!==a)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof d||n.isBuffer(d))&&(d||a>=4)&&(d||c))m+=n.byteLength(d)+2;else{if(a<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*c==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof u||u<0||u>65535||u%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===a){var y=U(t,g);if(!y)return!1;m+=y.length}if(l){if("object"!=typeof l)return t.emit("error",new Error("Invalid will")),!1;if(!l.topic||"string"!=typeof l.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=n.byteLength(l.topic)+2,m+=2,l.payload){if(!(l.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof l.payload?m+=n.byteLength(l.payload):m+=l.payload.length}var v={};if(5===a){if(!(v=U(t,l.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!q(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=n.byteLength(h)+2}if(null!=f){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!q(f))return t.emit("error",new Error("Invalid password")),!1;m+=$(f)+2}t.write(r.CONNECT_HEADER),L(t,m),F(t,o),i.bridgeMode&&(a+=128),t.write(131===a?r.VERSION131:132===a?r.VERSION132:4===a?r.VERSION4:5===a?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=f?r.PASSWORD_MASK:0,w|=l&&l.retain?r.WILL_RETAIN_MASK:0,w|=l&&l.qos?l.qos<<r.WILL_QOS_SHIFT:0,w|=l?r.WILL_FLAG_MASK:0,w|=c?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),p(t,u),5===a&&y.write(),F(t,d),l&&(5===a&&v.write(),D(t,l.topic),F(t,l.payload)),null!=h&&F(t,h),null!=f&&F(t,f),!0}function b(e,t,s){const o=s?s.protocolVersion:4,a=e||{},l=5===o?a.reasonCode:a.returnCode,c=a.properties;let u=2;if("number"!=typeof l)return t.emit("error",new Error("Invalid return code")),!1;let d=null;if(5===o){if(d=U(t,c),!d)return!1;u+=d.length}return t.write(r.CONNACK_HEADER),L(t,u),t.write(a.sessionPresent?r.SESSIONPRESENT_HEADER:i),t.write(n.from([l])),null!=d&&d.write(),!0}function w(e,t,i){l("publish: packet: %o",e);const o=i?i.protocolVersion:4,a=e||{},c=a.qos||0,u=a.retain?r.RETAIN_MASK:0,d=a.topic,h=a.payload||s,f=a.messageId,g=a.properties;let m=0;if("string"==typeof d)m+=n.byteLength(d)+2;else{if(!n.isBuffer(d))return t.emit("error",new Error("Invalid topic")),!1;m+=d.length+2}if(n.isBuffer(h)?m+=h.length:m+=n.byteLength(h),c&&"number"!=typeof f)return t.emit("error",new Error("Invalid messageId")),!1;c&&(m+=2);let y=null;if(5===o){if(y=U(t,g),!y)return!1;m+=y.length}return t.write(r.PUBLISH_HEADER[c][a.dup?1:0][u?1:0]),L(t,m),p(t,$(d)),t.write(d),c>0&&p(t,f),null!=y&&y.write(),l("publish: payload: %o",h),t.write(h)}function E(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.cmd||"puback",l=o.messageId,c=o.dup&&"pubrel"===a?r.DUP_MASK:0;let u=0;const d=o.reasonCode,h=o.properties;let f=5===i?3:2;if("pubrel"===a&&(u=1),"number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===i&&"object"==typeof h){if(g=N(t,h,s,f),!g)return!1;f+=g.length}return t.write(r.ACKS[a][u][c][0]),L(t,f),p(t,l),5===i&&t.write(n.from([d])),null!==g&&g.write(),!0}function S(e,t,s){l("subscribe: packet: ");const i=s?s.protocolVersion:4,o=e||{},a=o.dup?r.DUP_MASK:0,c=o.messageId,u=o.subscriptions,d=o.properties;let h=0;if("number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let f=null;if(5===i){if(f=U(t,d),!f)return!1;h+=f.length}if("object"!=typeof u||!u.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<u.length;e+=1){const r=u[e].topic,s=u[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof s)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===i){if("boolean"!=typeof(u[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(u[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=u[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}l("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][a?1:0][0]),L(t,h),p(t,c),null!==f&&f.write();let g=!0;for(const e of u){const s=e.topic,o=e.qos,a=+e.nl,l=+e.rap,c=e.rh;let u;D(t,s),u=r.SUBSCRIBE_OPTIONS_QOS[o],5===i&&(u|=a?r.SUBSCRIBE_OPTIONS_NL:0,u|=l?r.SUBSCRIBE_OPTIONS_RAP:0,u|=c?r.SUBSCRIBE_OPTIONS_RH[c]:0),g=t.write(n.from([u]))}return g}function C(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.messageId,l=o.granted,c=o.properties;let u=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;u+=1}let d=null;if(5===i){if(d=N(t,c,s,u),!d)return!1;u+=d.length}return t.write(r.SUBACK_HEADER),L(t,u),p(t,a),null!==d&&d.write(),t.write(n.from(l))}function T(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.messageId,l=o.dup?r.DUP_MASK:0,c=o.unsubscriptions,u=o.properties;let d=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<c.length;e+=1){if("string"!=typeof c[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;d+=n.byteLength(c[e])+2}let h=null;if(5===i){if(h=U(t,u),!h)return!1;d+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][l?1:0][0]),L(t,d),p(t,a),null!==h&&h.write();let f=!0;for(let e=0;e<c.length;e++)f=D(t,c[e]);return f}function k(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.messageId,l=o.dup?r.DUP_MASK:0,c=o.granted,u=o.properties,d=o.cmd,h=0;let f=2;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(5===i){if("object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;f+=1}}let g=null;if(5===i){if(g=N(t,u,s,f),!g)return!1;f+=g.length}return t.write(r.ACKS[d][h][l][0]),L(t,f),p(t,a),null!==g&&g.write(),5===i&&t.write(n.from(c)),!0}function _(e,t,n){return t.write(r.EMPTY[e.cmd])}function I(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.reasonCode,l=o.properties;let c=5===i?1:0,u=null;if(5===i){if(u=N(t,l,s,c),!u)return!1;c+=u.length}return t.write(n.from([r.codes.disconnect<<4])),L(t,c),5===i&&t.write(n.from([a])),null!==u&&u.write(),!0}function A(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.reasonCode,l=o.properties;let c=5===i?1:0;5!==i&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const u=N(t,l,s,c);return!!u&&(c+=u.length,t.write(n.from([r.codes.auth<<4])),L(t,c),t.write(n.from([a])),null!==u&&u.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>p===x,set(e){e?(c&&0!==Object.keys(c).length||(g=!0),p=x):(g=!1,p=P)}});const R={};function L(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=R[t];return n||(n=h(t),t<16384&&(R[t]=n)),l("writeVarByteInt: writing to stream: %o",n),e.write(n)}function D(e,t){const r=n.byteLength(t);return p(e,r),l("writeString: %s",t),e.write(t,"utf8")}function O(e,t,n){D(e,t),D(e,n)}function x(e,t){return l("writeNumberCached: number: %d",t),l("writeNumberCached: %o",c[t]),e.write(c[t])}function P(e,t){const n=u(t);return l("writeNumberGenerated: %o",n),e.write(n)}function M(e,t){const n=f(t);return l("write4ByteNumber: %o",n),e.write(n)}function F(e,t){"string"==typeof t?D(e,t):t?(p(e,t.length),e.write(t)):p(e,0)}function U(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){j(e,{},0)}};let s=0;function i(t,s){let i=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=2;break;case"int8":if("number"!=typeof s||s<0||s>255)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=2;break;case"binary":if(s&&null===s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=1+n.byteLength(s)+2;break;case"int16":if("number"!=typeof s||s<0||s>65535)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=3;break;case"int32":if("number"!=typeof s||s<0||s>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=5;break;case"var":if("number"!=typeof s||s<0||s>268435455)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=1+n.byteLength(h(s));break;case"string":if("string"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=3+n.byteLength(s.toString());break;case"pair":if("object"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=Object.getOwnPropertyNames(s).reduce(((e,t)=>{const r=s[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(s[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${s}`)),!1}return i}if(t)for(const e in t){let n=0,r=0;const o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(r=i(e,o[t]),!r)return!1;n+=r}else{if(r=i(e,o),!r)return!1;n=r}if(!n)return!1;s+=n}return{length:n.byteLength(h(s))+s,write(){j(e,t,s)}}}function N(e,t,n,r){const s=["reasonString","userProperties"],i=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=U(e,t);if(i)for(;r+o.length>i;){const n=s.shift();if(!n||!t[n])return!1;delete t[n],o=U(e,t)}return o}function B(e,t,s){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+s]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([s]));break;case"binary":e.write(n.from([r.properties[t]])),F(e,s);break;case"int16":e.write(n.from([r.properties[t]])),p(e,s);break;case"int32":e.write(n.from([r.properties[t]])),M(e,s);break;case"var":e.write(n.from([r.properties[t]])),L(e,s);break;case"string":e.write(n.from([r.properties[t]])),D(e,s);break;case"pair":Object.getOwnPropertyNames(s).forEach((i=>{const o=s[i];Array.isArray(o)?o.forEach((s=>{e.write(n.from([r.properties[t]])),O(e,i.toString(),s.toString())})):(e.write(n.from([r.properties[t]])),O(e,i.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${s}`)),!1}}function j(e,t,n){L(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)B(e,n,r[t]);else B(e,n,r)}}function $(e){return e?e instanceof n?e.length:n.byteLength(e):0}function q(e){return"string"==typeof e||e instanceof n}t.exports=m}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,n){var r=1e3,s=60*r,i=60*s,o=24*i,a=7*o,l=365.25*o;function c(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"weeks":case"week":case"w":return n*a;case"days":case"day":case"d":return n*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*i;case"minutes":case"minute":case"mins":case"min":case"m":return n*s;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function u(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"d":t>=i?Math.round(e/i)+"h":t>=s?Math.round(e/s)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function d(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=i?h(e,t,i,"hour"):t>=s?h(e,t,s,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return c(e);if("number"===n&&isFinite(e))return t.long?d(e):u(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,s=e("debug")("number-allocator:trace"),i=e("debug")("number-allocator:error");function o(e,t){this.low=e,this.high=t}function a(e,t){if(!(this instanceof a))return new a(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),s("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},a.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},a.prototype.alloc=function(){if(0===this.ss.size())return s("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),s("alloc():"+t),t},a.prototype.use=function(e){const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),s("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,s("use():"+e),!0;if(n.high===e)return--n.high,s("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new o(r,e-1)),s("use():"+e),!0}return s("use():failed"),!1},a.prototype.free=function(e){if(e<this.min||e>this.max)return void i("free():"+e+" is out of range");const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void i("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}s("free():"+e)},a.prototype.clear=function(){s("clear()"),this.ss.clear(),this.ss.insert(new o(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=a},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function s(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(s),t.exports.strict=r(i),s.proto=s((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return s(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return i(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,s){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var i,o,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,s)}));default:for(i=new Array(a-1),o=0;o<i.length;)i[o++]=arguments[o];return e.nextTick((function(){t.apply(null,i)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,s,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function c(e){if(s===clearTimeout)return clearTimeout(e);if((s===a||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{return s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{s="function"==typeof clearTimeout?clearTimeout:a}catch(e){s=a}}();var u,d=[],h=!1,f=-1;function p(){h&&u&&(h=!1,u.length?d=u.concat(d):f=-1,d.length&&g())}function g(){if(!h){var e=l(p);h=!0;for(var t=d.length;t;){for(u=d,d=[];++f<t;)u&&u[f].run();f=-1,t=d.length}u=null,h=!1,c(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];d.push(new m(e,t)),1!==d.length||h||l(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=y,i.addListener=y,i.once=y,i.off=y,i.removeListener=y,i.removeAllListeners=y,i.emit=y,i.prependListener=y,i.prependOnceListener=y,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var s="object"==typeof n&&n&&!n.nodeType&&n,i="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(r=o);var a,l,c=2147483647,u=36,d=1,h=26,f=38,p=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,E={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=u-d,C=Math.floor,T=String.fromCharCode;function k(e){throw new RangeError(E[e])}function _(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function I(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+_((e=e.replace(w,".")).split("."),t).join(".")}function A(e){for(var t,n,r=[],s=0,i=e.length;s<i;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<i?56320==(64512&(n=e.charCodeAt(s++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),s--):r.push(t);return r}function R(e){return _(e,(function(e){var t="";return e>65535&&(t+=T((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=T(e)})).join("")}function L(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:u}function D(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function O(e,t,n){var r=0;for(e=n?C(e/p):e>>1,e+=C(e/t);e>S*h>>1;r+=u)e=C(e/S);return C(r+(S+1)*e/(e+f))}function x(e){var t,n,r,s,i,o,a,l,f,p,v=[],b=e.length,w=0,E=m,S=g;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(s=n>0?n+1:0;s<b;){for(i=w,o=1,a=u;s>=b&&k("invalid-input"),((l=L(e.charCodeAt(s++)))>=u||l>C((c-w)/o))&&k("overflow"),w+=l*o,!(l<(f=a<=S?d:a>=S+h?h:a-S));a+=u)o>C(c/(p=u-f))&&k("overflow"),o*=p;S=O(w-i,t=v.length+1,0==i),C(w/t)>c-E&&k("overflow"),E+=C(w/t),w%=t,v.splice(w++,0,E)}return R(v)}function P(e){var t,n,r,s,i,o,a,l,f,p,v,b,w,E,S,_=[];for(b=(e=A(e)).length,t=m,n=0,i=g,o=0;o<b;++o)(v=e[o])<128&&_.push(T(v));for(r=s=_.length,s&&_.push(y);r<b;){for(a=c,o=0;o<b;++o)(v=e[o])>=t&&v<a&&(a=v);for(a-t>C((c-n)/(w=r+1))&&k("overflow"),n+=(a-t)*w,t=a,o=0;o<b;++o)if((v=e[o])<t&&++n>c&&k("overflow"),v==t){for(l=n,f=u;!(l<(p=f<=i?d:f>=i+h?h:f-i));f+=u)S=l-p,E=u-p,_.push(T(D(p+S%E,0))),l=C(S/E);_.push(T(D(l,0))),i=O(n,w,r==s),n=0,++r}++n,++t}return _.join("")}function M(e){return I(e,(function(e){return v.test(e)?x(e.slice(4).toLowerCase()):e}))}function F(e){return I(e,(function(e){return b.test(e)?"xn--"+P(e):e}))}if(a={version:"1.4.1",ucs2:{decode:A,encode:R},decode:x,encode:P,toASCII:F,toUnicode:M},s&&i)if(t.exports==s)i.exports=a;else for(l in a)a.hasOwnProperty(l)&&(s[l]=a[l]);else r.punycode=a}(this)}).call(this)}).call(this,void 0!==gt?gt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,i){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var a=/\+/g;e=e.split(t);var l=1e3;i&&"number"==typeof i.maxKeys&&(l=i.maxKeys);var c=e.length;l>0&&c>l&&(c=l);for(var u=0;u<c;++u){var d,h,f,p,g=e[u].replace(a,"%20"),m=g.indexOf(n);m>=0?(d=g.substr(0,m),h=g.substr(m+1)):(d=g,h=""),f=decodeURIComponent(d),p=decodeURIComponent(h),r(o,f)?s(o[f])?o[f].push(p):o[f]=[o[f],p]:o[f]=p}return o};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?i(o(e),(function(o){var a=encodeURIComponent(r(o))+n;return s(e[o])?i(e[o],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[o]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var s={};function i(e,t,n){function i(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var o=function(e){function t(t,n,r){return e.call(this,i(t,n,r))||this}return r(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,s[e]=o}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function l(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function c(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,s;if("string"==typeof t&&a(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",l(e," argument"))s="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var i=c(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(i," ").concat(r," ").concat(o(t,"type"))}return s+=". Received type ".concat(typeof n)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=s},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var s=e("./_stream_readable"),i=e("./_stream_writable");e("inherits")(c,s);for(var o=r(i.prototype),a=0;a<o.length;a++){var l=o[a];c.prototype[l]||(c.prototype[l]=i.prototype[l])}function c(e){if(!(this instanceof c))return new c(e);s.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",u)))}function u(){this._writableState.ended||n.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=s;var r=e("./_stream_transform");function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}e("inherits")(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var s;t.exports=A,A.ReadableState=I,e("events").EventEmitter;var i=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),a=e("buffer").Buffer,l=r.Uint8Array||function(){};function c(e){return a.from(e)}function u(e){return a.isBuffer(e)||e instanceof l}var d,h=e("util");d=h&&h.debuglog?h.debuglog("stream"):function(){};var f,p,g,m=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,E=b.ERR_STREAM_PUSH_AFTER_EOF,S=b.ERR_METHOD_NOT_IMPLEMENTED,C=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(A,o);var T=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function _(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function I(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new m,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(f||(f=e("string_decoder/").StringDecoder),this.decoder=new f(t.encoding),this.encoding=t.encoding)}function A(t){if(s=s||e("./_stream_duplex"),!(this instanceof A))return new A(t);var n=this instanceof s;this._readableState=new I(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function R(e,t,n,r,s){d("readableAddChunk",t);var i,o=e._readableState;if(null===t)o.reading=!1,M(e,o);else if(s||(i=D(o,t)),i)T(e,i);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=c(t)),r)o.endEmitted?T(e,new C):L(e,o,t,!0);else if(o.ended)T(e,new E);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?L(e,o,t,!1):N(e,o)):L(e,o,t,!1)}else r||(o.reading=!1,N(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function L(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&F(e)),N(e,t)}function D(e,t){var n;return u(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),A.prototype.destroy=y.destroy,A.prototype._undestroy=y.undestroy,A.prototype._destroy=function(e,t){t(e)},A.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=a.from(e,t),t=""),n=!0),R(this,e,t,!1,n)},A.prototype.unshift=function(e){return R(this,e,null,!0,!1)},A.prototype.isPaused=function(){return!1===this._readableState.flowing},A.prototype.setEncoding=function(t){f||(f=e("string_decoder/").StringDecoder);var n=new f(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,s="";null!==r;)s+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==s&&this._readableState.buffer.push(s),this._readableState.length=s.length,this};var O=1073741824;function x(e){return e>=O?e=O:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function P(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=x(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function M(e,t){if(d("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?F(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,U(e)))}}function F(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(U,e))}function U(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,H(e)}function N(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(B,e,t))}function B(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(d("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function j(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,H(e))}}function $(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function q(e){d("readable nexttick read 0"),e.read(0)}function K(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(G,e,t))}function G(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),H(e),t.flowing&&!t.reading&&e.read(0)}function H(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function z(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(W,t,e))}function W(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function Y(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}A.prototype.read=function(e){d("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?z(this):F(this),null;if(0===(e=P(e,t))&&t.ended)return 0===t.length&&z(this),null;var r,s=t.needReadable;return d("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",s=!0),t.ended||t.reading?d("reading or ended",s=!1):s&&(d("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=P(n,t))),null===(r=e>0?V(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&z(this)),null!==r&&this.emit("data",r),r},A.prototype._read=function(e){T(this,new S("_read()"))},A.prototype.pipe=function(e,t){var r=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,d("pipe count=%d opts=%j",s.pipesCount,t);var o=t&&!1===t.end||e===n.stdout||e===n.stderr?y:l;function a(e,t){d("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function l(){d("onend"),e.end()}s.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",a);var c=j(r);e.on("drain",c);var u=!1;function h(){d("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",l),r.removeListener("end",y),r.removeListener("data",f),u=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||c()}function f(t){d("ondata");var n=e.write(t);d("dest.write",n),!1===n&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==Y(s.pipes,e))&&!u&&(d("false write response, pause",s.awaitDrain),s.awaitDrain++),r.pause())}function p(t){d("onerror",t),y(),e.removeListener("error",p),0===i(e,"error")&&T(e,t)}function g(){e.removeListener("finish",m),y()}function m(){d("onfinish"),e.removeListener("close",g),y()}function y(){d("unpipe"),r.unpipe(e)}return r.on("data",f),_(e,"error",p),e.once("close",g),e.once("finish",m),e.emit("pipe",r),s.flowing||(d("pipe resume"),r.resume()),e},A.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<s;i++)r[i].emit("unpipe",this,{hasUnpiped:!1});return this}var o=Y(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},A.prototype.on=function(e,t){var r=o.prototype.on.call(this,e,t),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,d("on readable",s.length,s.reading),s.length?F(this):s.reading||n.nextTick(q,this))),r},A.prototype.addListener=A.prototype.on,A.prototype.removeListener=function(e,t){var r=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick($,this),r},A.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick($,this),t},A.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,K(this,e)),e.paused=!1,this},A.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},A.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",(function(){if(d("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(s){d("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var i=0;i<k.length;i++)e.on(k[i],this.emit.bind(this,k[i]));return this._read=function(t){d("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(A.prototype[Symbol.asyncIterator]=function(){return void 0===p&&(p=e("./internal/streams/async_iterator")),p(this)}),Object.defineProperty(A.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(A.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(A.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),A._fromList=V,Object.defineProperty(A.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(A.from=function(t,n){return void 0===g&&(g=e("./internal/streams/from")),g(A,t,n)})}).call(this)}).call(this,e("_process"),void 0!==gt?gt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,n){t.exports=u;var r=e("../errors").codes,s=r.ERR_METHOD_NOT_IMPLEMENTED,i=r.ERR_MULTIPLE_CALLBACK,o=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,l=e("./_stream_duplex");function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new i);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function u(e){if(!(this instanceof u))return new u(e);l.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",d)}function d(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new a;if(e._transformState.transforming)throw new o;return e.push(null)}e("inherits")(u,l),u.prototype.push=function(e,t){return this._transformState.needTransform=!1,l.prototype.push.call(this,e,t)},u.prototype._transform=function(e,t,n){n(new s("_transform()"))},u.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var s=this._readableState;(r.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},u.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},u.prototype._destroy=function(e,t){l.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){G(t,e)}}var i;t.exports=I,I.WritableState=_;var o={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),l=e("buffer").Buffer,c=r.Uint8Array||function(){};function u(e){return l.from(e)}function d(e){return l.isBuffer(e)||e instanceof c}var h,f=e("./internal/streams/destroy"),p=e("./internal/streams/state").getHighWaterMark,g=e("../errors").codes,m=g.ERR_INVALID_ARG_TYPE,y=g.ERR_METHOD_NOT_IMPLEMENTED,v=g.ERR_MULTIPLE_CALLBACK,b=g.ERR_STREAM_CANNOT_PIPE,w=g.ERR_STREAM_DESTROYED,E=g.ERR_STREAM_NULL_VALUES,S=g.ERR_STREAM_WRITE_AFTER_END,C=g.ERR_UNKNOWN_ENCODING,T=f.errorOrDestroy;function k(){}function _(t,n,r){i=i||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof i),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=p(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){M(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function I(t){var n=this instanceof(i=i||e("./_stream_duplex"));if(!n&&!h.call(I,this))return new I(t);this._writableState=new _(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function A(e,t){var r=new S;T(e,r),n.nextTick(t,r)}function R(e,t,r,s){var i;return null===r?i=new E:"string"==typeof r||t.objectMode||(i=new m("chunk",["string","Buffer"],r)),!i||(T(e,i),n.nextTick(s,i),!1)}function L(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n)),t}function D(e,t,n,r,s,i){if(!n){var o=L(t,r,s);r!==o&&(n=!0,s="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:s,isBuf:n,callback:i,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else O(e,t,!1,a,r,s,i);return l}function O(e,t,n,r,s,i,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(s,t.onwrite):e._write(s,i,t.onwrite),t.sync=!1}function x(e,t,r,s,i){--t.pendingcb,r?(n.nextTick(i,s),n.nextTick(q,e,t),e._writableState.errorEmitted=!0,T(e,s)):(i(s),e._writableState.errorEmitted=!0,T(e,s),q(e,t))}function P(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function M(e,t){var r=e._writableState,s=r.sync,i=r.writecb;if("function"!=typeof i)throw new v;if(P(r),t)x(e,r,s,t,i);else{var o=B(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||N(e,r),s?n.nextTick(F,e,r,o,i):F(e,r,o,i)}}function F(e,t,n,r){n||U(e,t),t.pendingcb--,r(),q(e,t)}function U(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function N(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,l=!0;n;)i[a]=n,n.isBuf||(l=!1),n=n.next,a+=1;i.allBuffers=l,O(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,u=n.encoding,d=n.callback;if(O(e,t,!1,t.objectMode?1:c.length,c,u,d),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function B(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function j(e,t){e._final((function(n){t.pendingcb--,n&&T(e,n),t.prefinished=!0,e.emit("prefinish"),q(e,t)}))}function $(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(j,e,t)))}function q(e,t){var n=B(t);if(n&&($(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function K(e,t,r){t.ending=!0,q(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function G(e,t,n){var r=e.entry;for(e.entry=null;r;){var s=r.callback;t.pendingcb--,s(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(I,a),_.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(_.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===I&&e&&e._writableState instanceof _}})):h=function(e){return e instanceof this},I.prototype.pipe=function(){T(this,new b)},I.prototype.write=function(e,t,n){var r=this._writableState,s=!1,i=!r.objectMode&&d(e);return i&&!l.isBuffer(e)&&(e=u(e)),"function"==typeof t&&(n=t,t=null),i?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?A(this,n):(i||R(this,r,e,n))&&(r.pendingcb++,s=D(this,r,i,e,t,n)),s},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},I.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new C(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,n){n(new y("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||K(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=f.destroy,I.prototype._undestroy=f.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==gt?gt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,n){(function(n){(function(){var r;function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var i=e("./end-of-stream"),o=Symbol("lastResolve"),a=Symbol("lastReject"),l=Symbol("error"),c=Symbol("ended"),u=Symbol("lastPromise"),d=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[o];if(null!==t){var n=e[h].read();null!==n&&(e[u]=null,e[o]=null,e[a]=null,t(f(n,!1)))}}function g(e){n.nextTick(p,e)}function m(e,t){return function(n,r){e.then((function(){t[c]?n(f(void 0,!0)):t[d](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((s(r={get stream(){return this[h]},next:function(){var e=this,t=this[l];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[l]?r(e[l]):t(f(void 0,!0))}))}));var r,s=this[u];if(s)r=new Promise(m(s,this));else{var i=this[h].read();if(null!==i)return Promise.resolve(f(i,!1));r=new Promise(this[d])}return this[u]=r,r}},Symbol.asyncIterator,(function(){return this})),s(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(f(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(s(t={},h,{value:e,writable:!0}),s(t,o,{value:null,writable:!0}),s(t,a,{value:null,writable:!0}),s(t,l,{value:null,writable:!0}),s(t,c,{value:e._readableState.endEmitted,writable:!0}),s(t,d,{value:function(e,t){var r=n[h].read();r?(n[u]=null,n[o]=null,n[a]=null,e(f(r,!1))):(n[o]=e,n[a]=t)},writable:!0}),t));return n[u]=null,i(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[a];return null!==t&&(n[u]=null,n[o]=null,n[a]=null,t(e)),void(n[l]=e)}var r=n[o];null!==r&&(n[u]=null,n[o]=null,n[a]=null,r(f(void 0,!0))),n[c]=!0})),e.on("readable",g.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(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 s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function l(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),e}var c=e("buffer").Buffer,u=e("util").inspect,d=u&&u.custom||"inspect";function h(e,t,n){c.prototype.copy.call(e,t,n)}t.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return l(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return c.alloc(0);for(var t=c.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var s=t.data,i=e>s.length?s.length:e;if(i===s.length?r+=s:r+=s.slice(0,e),0==(e-=i)){i===s.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=s.slice(i));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=c.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var s=n.data,i=e>s.length?s.length:e;if(s.copy(t,t.length-e,0,i),0==(e-=i)){i===s.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=s.slice(i));break}++r}return this.length-=r,t}},{key:d,value:function(e,t){return u(this,s({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var i=this,a=this._readableState&&this._readableState.destroyed,l=this._writableState&&this._writableState.destroyed;return a||l?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(s,i):(i._writableState.errorEmitted=!0,e.nextTick(r,i,t)):e.nextTick(r,i,t):n?(e.nextTick(s,i),n(t)):e.nextTick(s,i)})),this)}function r(e,t){o(e,t),s(e)}function s(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit("error",t)}function a(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:i,errorOrDestroy:a}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function s(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.apply(this,r)}}}function i(){}function o(e){return e.setHeader&&"function"==typeof e.abort}function a(e,t,n){if("function"==typeof t)return a(e,null,t);t||(t={}),n=s(n||i);var l=t.readable||!1!==t.readable&&e.readable,c=t.writable||!1!==t.writable&&e.writable,u=function(){e.writable||h()},d=e._writableState&&e._writableState.finished,h=function(){c=!1,d=!0,l||n.call(e)},f=e._readableState&&e._readableState.endEmitted,p=function(){l=!1,f=!0,c||n.call(e)},g=function(t){n.call(e,t)},m=function(){var t;return l&&!f?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):c&&!d?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):c&&!e._writableState&&(e.on("end",u),e.on("close",u)),e.on("end",p),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",u),e.removeListener("close",u),e.removeListener("finish",h),e.removeListener("end",p),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=a},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function s(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=e("../../../errors").codes,o=i.ERR_MISSING_ARGS,a=i.ERR_STREAM_DESTROYED;function l(e){if(e)throw e}function c(e){return e.setHeader&&"function"==typeof e.abort}function u(t,n,i,o){o=s(o);var l=!1;t.on("close",(function(){l=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:i},(function(e){if(e)return o(e);l=!0,o()}));var u=!1;return function(e){if(!l&&!u)return u=!0,c(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new a("pipe"))}}function d(e){e()}function h(e,t){return e.pipe(t)}function f(e){return e.length?"function"!=typeof e[e.length-1]?l:e.pop():l}function p(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,s=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var i=t.map((function(e,n){var o=n<t.length-1;return u(e,o,n>0,(function(e){r||(r=e),e&&i.forEach(d),o||(i.forEach(d),s(r))}))}));return t.reduce(h)}t.exports=p},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function s(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function i(e,t,n,i){var o=s(t,i,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new r(i?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function s(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new r(arguments[0],arguments[1],e)}t.exports=s},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?s(e):e.proto?i:r;function t(e,t){for(var r=Object.keys(e),s=new Array(r.length),i=0;i<r.length;i++){var o=r[i],a=e[o];"object"!=typeof a||null===a?s[o]=a:a instanceof Date?s[o]=new Date(a):ArrayBuffer.isView(a)?s[o]=n(a):s[o]=t(a)}return s}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var s={};for(var i in e)if(!1!==Object.hasOwnProperty.call(e,i)){var o=e[i];"object"!=typeof o||null===o?s[i]=o:o instanceof Date?s[i]=new Date(o):o instanceof Map?s[i]=new Map(t(Array.from(o),r)):o instanceof Set?s[i]=new Set(t(Array.from(o),r)):ArrayBuffer.isView(o)?s[i]=n(o):s[i]=r(o)}return s}function i(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,i);if(e instanceof Map)return new Map(t(Array.from(e),i));if(e instanceof Set)return new Set(t(Array.from(e),i));var r={};for(var s in e){var o=e[s];"object"!=typeof o||null===o?r[s]=o:o instanceof Date?r[s]=new Date(o):o instanceof Map?r[s]=new Map(t(Array.from(o),i)):o instanceof Set?r[s]=new Set(t(Array.from(o),i)):ArrayBuffer.isView(o)?r[s]=n(o):r[s]=i(o)}return r}}function s(e){var t=[],r=[];return e.proto?o:i;function s(e,s){for(var i=Object.keys(e),o=new Array(i.length),a=0;a<i.length;a++){var l=i[a],c=e[l];if("object"!=typeof c||null===c)o[l]=c;else if(c instanceof Date)o[l]=new Date(c);else if(ArrayBuffer.isView(c))o[l]=n(c);else{var u=t.indexOf(c);o[l]=-1!==u?r[u]:s(c)}}return o}function i(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,i);if(e instanceof Map)return new Map(s(Array.from(e),i));if(e instanceof Set)return new Set(s(Array.from(e),i));var o={};for(var a in t.push(e),r.push(o),e)if(!1!==Object.hasOwnProperty.call(e,a)){var l=e[a];if("object"!=typeof l||null===l)o[a]=l;else if(l instanceof Date)o[a]=new Date(l);else if(l instanceof Map)o[a]=new Map(s(Array.from(l),i));else if(l instanceof Set)o[a]=new Set(s(Array.from(l),i));else if(ArrayBuffer.isView(l))o[a]=n(l);else{var c=t.indexOf(l);o[a]=-1!==c?r[c]:i(l)}}return t.pop(),r.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,o);if(e instanceof Map)return new Map(s(Array.from(e),o));if(e instanceof Set)return new Set(s(Array.from(e),o));var i={};for(var a in t.push(e),r.push(i),e){var l=e[a];if("object"!=typeof l||null===l)i[a]=l;else if(l instanceof Date)i[a]=new Date(l);else if(l instanceof Map)i[a]=new Map(s(Array.from(l),o));else if(l instanceof Set)i[a]=new Set(s(Array.from(l),o));else if(ArrayBuffer.isView(l))i[a]=n(l);else{var c=t.indexOf(l);i[a]=-1!==c?r[c]:o(l)}}return t.pop(),r.pop(),i}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
3
+ n.read=function(e,t,n,r,o){var a,s,i=8*o-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?o-1:0,h=n?-1:1,p=e[t+u];for(u+=h,a=p&(1<<-d)-1,p>>=-d,d+=i;d>0;a=256*a+e[t+u],u+=h,d-=8);for(s=a&(1<<-d)-1,a>>=-d,d+=r;d>0;s=256*s+e[t+u],u+=h,d-=8);if(0===a)a=1-l;else{if(a===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,r),a-=l}return(p?-1:1)*s*Math.pow(2,a-r)},n.write=function(e,t,n,r,o,a){var s,i,c,l=8*a-o-1,d=(1<<l)-1,u=d>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:a-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=d?(i=0,s=d):s+u>=1?(i=(t*c-1)*Math.pow(2,o),s+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,o),s=0));o>=8;e[n+p]=255&i,p+=f,i/=256,o-=8);for(s=s<<o|i,l+=o;l>0;e[n+p]=255&s,p+=f,s/=256,l-=8);e[n+p-f]|=128*g}},{}],24:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var o=r.leftChild,a=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=a,t&&(t.brother=r),this.parent=r,this.brother=a,this.leftChild=n,this.rightChild=o,a&&(a.parent=r,a.brother=this),n&&(n.parent=this,n.brother=o),o&&(o.parent=this,o.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,o=n.leftChild,a=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=o,n.rightChild=this,t&&(t.brother=n),o&&(o.parent=n,o.brother=this),this.parent=n,this.brother=o,this.leftChild=a,this.rightChild=r,a&&(a.parent=this,a.brother=r),r&&(r.parent=this,r.brother=a),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};function o(e){var t=this;void 0===e&&(e=[]);var n=[],a=0,s=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){a=i=s=c=l=d=0,h.call(this,o.bucketSize),d=0},this.front=function(){return n[a][s]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(a!==i){for(l=s;l<o.bucketSize;++l)e(n[a][l],t++);for(l=a+1;l<i;++l)for(var r=0;r<o.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=s;l<=c;++l)e(n[a][l],t++)}};var u=function(e){var t=a*o.bucketSize+s,n=t+e,r=i*o.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/o.bucketSize),curNodePointerIndex:n%o.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,o=t.curNodePointerIndex;return n[r][o]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<d;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*o.sigma,u=Math.max(Math.ceil(r/o.bucketSize),2),h=0;h<u;++h)t.push(new Array(o.bucketSize));var p=Math.ceil(e/o.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),g=f,m=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<o.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){g=f+h,m=y;break}if(this.empty())break}n=t,a=f,s=0,i=g,c=m,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===o.bucketSize-1&&h.call(this,this.size()),c<o.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:a<i&&(--i,c=o.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),o=r.curNodeBucketIndex,a=r.curNodePointerIndex;n[o][a]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var o=[],a=e;a<d;++a)o.push(this.getElementByPos(a));for(this.cut(e-1),a=0;a<n;++a)this.pushBack(t);o.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(a===i){for(var t=s;t<=c;++t)if(n[a][t]===e)return!0;return!1}for(t=s;t<o.bucketSize;++t)if(n[a][t]===e)return!0;for(t=a+1;t<i;++t)for(var r=0;r<o.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[i][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===a&&0===s&&h.call(this,this.size()),s>0?--s:a>0&&(--a,s=o.bucketSize-1)),++d,n[a][s]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(s<o.bucketSize-1?++s:a<i&&(++a,s=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var a=Math.ceil(r/o.bucketSize),s=0;s<a;++s)n.push(new Array(o.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;i=n,c=r,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===d)return[2];if(a!==i)return[3,5];t=s,r.label=1;case 1:return t<=c?[4,n[a][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=s,r.label=6;case 6:return t<o.bucketSize?[4,n[a][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=a+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<o.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=o.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var s=r*o.sigma;l=Math.ceil(s/o.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(o.bucketSize));var d=Math.ceil(r/o.bucketSize);a=Math.floor(l/2)-Math.floor(d/2),i=a,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),o.sigma=3,o.bucketSize=5e3,Object.freeze(o),n.default=o},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../LinkList/LinkList"),s=e("../Map/Map");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t,n,r=0,a="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{a="string"!=typeof e?JSON.stringify(e):e;try{for(var s=o(a),i=s.next();!i.done;i=s.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,o){if(!r.empty()){if(r instanceof a.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new a.default([{key:l,value:h}])}else if(r instanceof s.default){var p=new a.default,f=new a.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[o]=new s.default(p):p.size()&&(t[o]=p),f.size()>i.untreeifyThreshold?t[o+e]=new s.default(f):f.size()&&(t[o+e]=f)}else{var g=new a.default,m=new a.default;r.forEach((function(t){0==(n(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[o]=g),m.size()&&(t[o+e]=m)}d[o].clear()}})),d=t}};this.setElement=function(e,t){var r,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof a.default){try{for(var g=o(d[p]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{m&&!m.done&&(c=g.return)&&c.call(g)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new s.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new a.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,a=n(e)&u-1;if(d[a]){if(d[a]instanceof s.default)return d[a].getElementByKey(e);try{for(var i=o(d[a]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof s.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new a.default(d[c]));else{var p=-1;try{for(var f=o(d[c]),g=f.next();!g.done;g=f.next()){var m=g.value;if(++p,m.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,r,a=n(e)&u-1;if(!d[a])return!1;if(d[a]instanceof s.default)return d[a].find(e);try{for(var i=o(d[a]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,a,s,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),s=void 0,t=o(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return a=r.sent(),s={error:a},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(s)throw s.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Set/Set"),s=e("../LinkList/LinkList");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,o){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new s.default([c])}else if(r instanceof a.default){var l=new s.default,h=new s.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[o]=new a.default(l):l.size()&&(t[o]=l),h.size()>i.untreeifyThreshold?t[o+e]=new a.default(h):h.size()&&(t[o+e]=h)}else{var p=new s.default,f=new s.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[o]=p),f.size()&&(t[o+e]=f)}d[o].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&u-1;if(d[t]){var r=d[t].size();if(d[t]instanceof s.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new a.default(d[t]))}else d[t].insert(e);var o=d[t].size();l+=o-r}else d[t]=new s.default([e]),++l;l>u*i.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=n(e)&u-1;if(d[t]){var r=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof a.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new s.default(d[t]));var o=d[t].size();l+=o-r}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,a,s,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),s=void 0,t=o(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return a=r.sent(),s={error:a},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(s)throw s.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=void 0,s=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){a=s=void 0,n=0},this.front=function(){return null==a?void 0:a.value},this.back=function(){return null==s?void 0:s.value},this.forEach=function(e){for(var t=a,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=a;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=a;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var r=t.pre,o=t.next;o.pre=r,r.next=o,n>0&&--n}},this.eraseElementByValue=function(e){for(;a&&a.value===e;)this.popFront();for(;s&&s.value===e;)this.popBack();if(a)for(var t=a;t;){if(t.value===e){var r=t.pre,o=t.next;o&&(o.pre=r),r&&(r.next=o),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);s?(s.next=t,t.pre=s,s=t):a=s=t},this.popBack=function(){s&&(n>0&&--n,s&&(a===s?a=s=void 0:(s=s.pre)&&(s.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=a;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var s=a,i=1;i<e;++i){if(!(null==s?void 0:s.next))throw new Error("unknown error");s=null==s?void 0:s.next}if(!s)throw new Error("unknown error");var c=s.next;for(n+=r;r--;)s.next=new o(t),s.next.pre=s,s=s.next;s.next=c,c&&(c.pre=s)}},this.find=function(e){for(var t=a;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=a,t=s,r=0;e&&t&&2*r<n;){var o=e.value;e.value=t.value,t.value=o,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=a;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=a;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);a?(t.next=a,a.pre=t,a=t):a=s=t},this.popFront=function(){a&&(n>0&&--n,a&&(a===s?a=s=void 0:(a=a.next)&&(a.pre=void 0)))},this.merge=function(e){var t=this,r=a;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=s;else if(r===a)t.pushFront(e),r=a;else{++n;var i=r.pre;i&&(i.next=new o(e),i.next.pre=i,i.next.next=r,r&&(r.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=a,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(a),n.default=a},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Base/TreeNode");function s(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var s=0,i=new a.default;i.color=a.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=0,i.key=i.value=void 0,i.leftChild=i.rightChild=i.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=l(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,n,r=0;try{for(var a=o(this),s=a.next();!s.done;s=a.next())e(s.value,r++)}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var a=o(this),s=a.next();!s.done;s=a.next()){var i=s.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(i,e)};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(i,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==a.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===a.default.TreeNodeColorType.red){n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===a.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,f(t)):(n.color=a.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===a.default.TreeNodeColorType.red?(n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===a.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,f(t)):(n.color=a.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=a.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}f(t),t&&t.remove(),--s,i.color=a.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=s)throw new Error("pos must more than 0 and less than set's size");var t=0;m(i,(function(n){return e===t?(g(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&g(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new a.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new a.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==a.default.TreeNodeColorType.black&&t.color===a.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===a.default.TreeNodeColorType.red)n.color=t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,v(r);else if(!n||n.color===a.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red;var o=r.rotateRight();r===i&&(i=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===i&&(i=o),v(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===i&&(i=o),v(t)):e===t.rightChild&&(t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,o=r.rotateLeft(),r===i&&(i=o)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++s,i.key=e,i.value=n,void(i.color=a.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++s,r.key=e,r.value=n,v(r),i.color=a.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(i,e)},this.getElementByKey=function(e){var t=b(i,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var n=e.key,r=e.value;return t.setElement(n,r)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(s),n.default=s},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,o=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var o=n[e];n[e]=n[t],n[t]=o},a=function(e){if(e<0||e>=r)throw new Error("unknown error");var a=2*e+1,s=2*e+2;a<r&&t(n[e],n[a])>0&&o(e,a),s<r&&t(n[e],n[s])>0&&o(e,s)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var a=e,s=2*a+1;s<r;){var i=s+1,c=s;if(i<r&&t(n[s],n[i])>0&&(c=i),t(n[a],n[c])<=0)break;o(a,c),s=2*(a=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var o=r-1;o>0;){var s=Math.floor((o-1)/2);if(t(n[s],e)<=0)break;a(s),o=s}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var o=0;o<this.size();){var a=2*o+1,s=2*o+2;if(a>=this.size())break;var i=a;if(s<this.size()&&t(n[a],n[s])>0&&(i=s),t(n[i],e)>=0)break;n[o]=n[i],o=i}n[o]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function o(e){void 0===e&&(e=[]);var t=new r.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(o),n.default=o},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Base/TreeNode");function s(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var s=0,i=new a.default;i.color=a.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=a.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,r=0;try{for(var a=o(this),s=a.next();!s.done;s=a.next())e(s.value,r++)}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var a=o(this),s=a.next();!s.done;s=a.next()){var i=s.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==a.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===a.default.TreeNodeColorType.red){n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===a.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,d(t)):(n.color=a.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===a.default.TreeNodeColorType.red?(n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===a.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,d(t)):(n.color=a.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=a.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--s,i.color=a.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=s)throw new Error("pos must more than 0 and less than set's size");var t=0;h(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=g(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&u(n)}};var p=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new a.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new a.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==a.default.TreeNodeColorType.black&&t.color===a.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===a.default.TreeNodeColorType.red)n.color=t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,f(r);else if(!n||n.color===a.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red;var o=r.rotateRight();r===i&&(i=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===i&&(i=o),f(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===i&&(i=o),f(t)):e===t.rightChild&&(t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,o=r.rotateLeft(),r===i&&(i=o)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++s,i.key=e,void(i.color=a.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++s,n.key=e,f(n),i.color=a.default.TreeNodeColorType.black)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?g(e.leftChild,n):r>0?g(e.rightChild,n):e}};this.find=function(e){var n=g(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return m(e.rightChild,n);var o=m(e.leftChild,n);return void 0!==o?o:e.key}};this.lowerBound=function(e){return m(i,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var o=v(e.rightChild,n);return void 0!==o?o:e.key}};this.reverseLowerBound=function(e){return v(i,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(i,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(s),n.default=s},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},o=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,a=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(o)throw o.error}}return s},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,a=t.length;o<a;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.front=function(){if(!this.empty())return i[0]},this.back=function(){if(!this.empty())return i[n-1]},this.forEach=function(e){i.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return i[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)i[t]=i[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){i.push(e),++n},this.popBack=function(){i.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");i[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,a([e,0],o(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,s(i)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(i),n.default=i},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var o=e("./Stack/Stack");n.Stack=o.default;var a=e("./Queue/Queue");n.Queue=a.default;var s=e("./LinkList/LinkList");n.LinkList=s.default;var i=e("./Deque/Deque");n.Deque=i.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var d=e("./Map/Map");n.Map=d.default;var u=e("./HashSet/HashSet");n.HashSet=u.default;var h=e("./HashMap/HashMap");n.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,n){const r=e("yallist"),o=Symbol("max"),a=Symbol("length"),s=Symbol("lengthCalculator"),i=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),p=Symbol("updateAgeOnGet"),f=()=>1;class g{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[o]=e.max||1/0;const t=e.length||f;if(this[s]="function"!=typeof t?f:t,this[i]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[p]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[o]=e||1/0,v(this)}get max(){return this[o]}set allowStale(e){this[i]=!!e}get allowStale(){return this[i]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[s]&&(this[s]=e,this[a]=0,this[u].forEach((e=>{e.length=this[s](e.value,e.key),this[a]+=e.length}))),v(this)}get lengthCalculator(){return this[s]}get length(){return this[a]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[l]&&this[u]&&this[u].length&&this[u].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[u]=new r,this[a]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,i=this[s](t,e);if(this[h].has(e)){if(i>this[o])return b(this,this[h].get(e)),!1;const s=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,s.value)),s.now=r,s.maxAge=n,s.value=t,this[a]+=i-s.length,s.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[o]?(this[l]&&this[l](e,t),!1):(this[a]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],o=r.e||0;if(0===o)this.set(r.k,r.v);else{const e=o-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[i])return}else n&&(e[p]&&(r.value.now=Date.now()),e[u].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[a]>e[o])for(let t=e[u].tail;e[a]>e[o]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[a]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,o){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=o||0}}const C=(e,t,n,r)=>{let o=n.value;y(e,o)&&(b(e,n),e[i]||(o=void 0)),o&&t.call(r,o.value,o.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((o=>[0,1].map((a=>{const s=e.alloc(1);return s.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(o?n.DUP_MASK:0)|r<<n.QOS_SHIFT|a,0,!0),s}))))))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),o=e("events");function a(e,t){const n=new s;return r(e,n,t),n.concat()}class s extends o{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let o,a=0;for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?t[o]=r[o].length:t[o]=n.byteLength(r[o]),e+=t[o];const s=n.allocUnsafe(e);for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?(r[o].copy(s,a),a+=t[o]):(s.write(r[o],a),a+=t[o]);return s}}t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},o=e.isBuffer(e.from([1,2]).subarray(0,1));function a(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function s(){for(let e=0;e<n;e++)r[e]=a(e)}function i(t){const n=4;let r=0,a=0;const s=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),s.writeUInt8(r,a++)}while(t>0&&a<n);return t>0&&(a=0),o?s.subarray(0,a):s.slice(0,a)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:s,generateNumber:a,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),o=e("events"),a=e("./packet"),s=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends o{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new a,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),i("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=s.types[e>>s.CMD_SHIFT],this.packet.retain=0!=(e&s.RETAIN_MASK),this.packet.qos=e>>s.QOS_SHIFT&s.QOS_MASK,this.packet.dup=0!=(e&s.DUP_MASK),i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),i("_parseLength %d",e.value),!!e}_parsePayload(){i("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return i("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;i("_parseConnect");const o={},a=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(a.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(a.protocolVersion=this._list.readUInt8(this._pos),a.protocolVersion>=128&&(a.bridgeMode=!0,a.protocolVersion=a.protocolVersion-128),3!==a.protocolVersion&&4!==a.protocolVersion&&5!==a.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.username=this._list.readUInt8(this._pos)&s.USERNAME_MASK,o.password=this._list.readUInt8(this._pos)&s.PASSWORD_MASK,o.will=this._list.readUInt8(this._pos)&s.WILL_FLAG_MASK,o.will&&(a.will={},a.will.retain=0!=(this._list.readUInt8(this._pos)&s.WILL_RETAIN_MASK),a.will.qos=(this._list.readUInt8(this._pos)&s.WILL_QOS_MASK)>>s.WILL_QOS_SHIFT),a.clean=0!=(this._list.readUInt8(this._pos)&s.CLEAN_SESSION_MASK),this._pos++,a.keepalive=this._parseNum(),-1===a.keepalive)return this._emitError(new Error("Packet too short"));if(5===a.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(a.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(a.clientId=l,i("_parseConnect: packet.clientId: %s",a.clientId),o.will){if(5===a.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(a.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(a.will.topic=e,i("_parseConnect: packet.will.topic: %s",a.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));a.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",a.will.payload)}if(o.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));a.username=r,i("_parseConnect: packet.username: %s",a.username)}if(o.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));a.password=n}return this.settings=a,i("_parseConnect: complete"),a}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&s.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),i("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){i("_parseSubscribe");const e=this.packet;let t,n,r,o,a,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),r=n&s.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>s.SUBSCRIBE_OPTIONS_NL_SHIFT&s.SUBSCRIBE_OPTIONS_NL_MASK),a=0!=(n>>s.SUBSCRIBE_OPTIONS_RAP_SHIFT&s.SUBSCRIBE_OPTIONS_RAP_MASK),o=n>>s.SUBSCRIBE_OPTIONS_RH_SHIFT&s.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=a,l.rh=o):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){i("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){i("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){i("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),i("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(i("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),i("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",r),r}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const n=this._list.slice(this._pos,t);return this._pos+=e,i("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){i("_parseVarByteNum");const t=4;let n,r=0,o=1,a=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),a+=o*(n&s.VARBYTEINT_MASK),o*=128,0==(n&s.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:a}:a),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=s.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(s.propertiesTypes[t]))):n[t]=this._parseByType(s.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(s.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new a,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),o=n.allocUnsafe(0),a=n.from([0]),s=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=s.cache,d=s.generateNumber,u=s.generateCache,h=s.genBufVariableByteInt,p=s.generate4ByteBuffer;let f=U,g=!0;function m(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),g&&(g=!1,u()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return I(e,t,n);case"suback":return _(e,t,n);case"unsubscribe":return S(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return E(e,t);case"disconnect":return A(e,t,n);case"auth":return T(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,o){const a=e||{},s=a.protocolId||"MQTT";let i=a.protocolVersion||4;const c=a.will;let l=a.clean;const d=a.keepalive||0,u=a.clientId||"",h=a.username,p=a.password,g=a.properties;void 0===l&&(l=!0);let m=0;if(!s||"string"!=typeof s&&!n.isBuffer(s))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=s.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))m+=n.byteLength(u)+2;else{if(i<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===i){var y=N(t,g);if(!y)return!1;m+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=n.byteLength(c.topic)+2,m+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?m+=n.byteLength(c.payload):m+=c.payload.length}var v={};if(5===i){if(!(v=N(t,c.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!$(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!$(p))return t.emit("error",new Error("Invalid password")),!1;m+=L(p)+2}t.write(r.CONNECT_HEADER),O(t,m),D(t,s),a.bridgeMode&&(i+=128),t.write(131===i?r.VERSION131:132===i?r.VERSION132:4===i?r.VERSION4:5===i?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=p?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),D(t,u),c&&(5===i&&v.write(),P(t,c.topic),D(t,c.payload)),null!=h&&D(t,h),null!=p&&D(t,p),!0}function b(e,t,o){const s=o?o.protocolVersion:4,i=e||{},c=5===s?i.reasonCode:i.returnCode,l=i.properties;let d=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===s){if(u=N(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),O(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:a),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,a){c("publish: packet: %o",e);const s=a?a.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||o,p=i.messageId,g=i.properties;let m=0;if("string"==typeof u)m+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;m+=u.length+2}if(n.isBuffer(h)?m+=h.length:m+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(m+=2);let y=null;if(5===s){if(y=N(t,g),!y)return!1;m+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),O(t,m),f(t,L(u)),t.write(u),l>0&&f(t,p),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.cmd||"puback",c=s.messageId,l=s.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=s.reasonCode,h=s.properties;let p=5===a?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===a&&"object"==typeof h){if(g=B(t,h,o,p),!g)return!1;p+=g.length}return t.write(r.ACKS[i][d][l][0]),O(t,p),f(t,c),5===a&&t.write(n.from([u])),null!==g&&g.write(),!0}function I(e,t,o){c("subscribe: packet: ");const a=o?o.protocolVersion:4,s=e||{},i=s.dup?r.DUP_MASK:0,l=s.messageId,d=s.subscriptions,u=s.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===a){if(p=N(t,u),!p)return!1;h+=p.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const r=d[e].topic,o=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof o)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===a){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][i?1:0][0]),O(t,h),f(t,l),null!==p&&p.write();let g=!0;for(const e of d){const o=e.topic,s=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,o),d=r.SUBSCRIBE_OPTIONS_QOS[s],5===a&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),g=t.write(n.from([d]))}return g}function _(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.messageId,c=s.granted,l=s.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===a){if(u=B(t,l,o,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),O(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function S(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.messageId,c=s.dup?r.DUP_MASK:0,l=s.unsubscriptions,d=s.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===a){if(h=N(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),O(t,u),f(t,i),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=P(t,l[e]);return p}function k(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.messageId,c=s.dup?r.DUP_MASK:0,l=s.granted,d=s.properties,u=s.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===a){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;p+=1}}let g=null;if(5===a){if(g=B(t,d,o,p),!g)return!1;p+=g.length}return t.write(r.ACKS[u][h][c][0]),O(t,p),f(t,i),null!==g&&g.write(),5===a&&t.write(n.from(l)),!0}function E(e,t,n){return t.write(r.EMPTY[e.cmd])}function A(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.reasonCode,c=s.properties;let l=5===a?1:0,d=null;if(5===a){if(d=B(t,c,o,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),O(t,l),5===a&&t.write(n.from([i])),null!==d&&d.write(),!0}function T(e,t,o){const a=o?o.protocolVersion:4,s=e||{},i=s.reasonCode,c=s.properties;let l=5===a?1:0;5!==a&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=B(t,c,o,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),O(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>f===U,set(e){e?(l&&0!==Object.keys(l).length||(g=!0),f=U):(g=!1,f=x)}});const M={};function O(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=M[t];return n||(n=h(t),t<16384&&(M[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function P(e,t){const r=n.byteLength(t);return f(e,r),c("writeString: %s",t),e.write(t,"utf8")}function R(e,t,n){P(e,t),P(e,n)}function U(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function x(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function j(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function D(e,t){"string"==typeof t?P(e,t):t?(f(e,t.length),e.write(t)):f(e,0)}function N(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){q(e,{},0)}};let o=0;function a(t,o){let a=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=2;break;case"int8":if("number"!=typeof o||o<0||o>255)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=2;break;case"binary":if(o&&null===o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=1+n.byteLength(o)+2;break;case"int16":if("number"!=typeof o||o<0||o>65535)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=3;break;case"int32":if("number"!=typeof o||o<0||o>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=5;break;case"var":if("number"!=typeof o||o<0||o>268435455)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=1+n.byteLength(h(o));break;case"string":if("string"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=3+n.byteLength(o.toString());break;case"pair":if("object"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;a+=Object.getOwnPropertyNames(o).reduce(((e,t)=>{const r=o[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(o[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${o}`)),!1}return a}if(t)for(const e in t){let n=0,r=0;const s=t[e];if(Array.isArray(s))for(let t=0;t<s.length;t++){if(r=a(e,s[t]),!r)return!1;n+=r}else{if(r=a(e,s),!r)return!1;n=r}if(!n)return!1;o+=n}return{length:n.byteLength(h(o))+o,write(){q(e,t,o)}}}function B(e,t,n,r){const o=["reasonString","userProperties"],a=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let s=N(e,t);if(a)for(;r+s.length>a;){const n=o.shift();if(!n||!t[n])return!1;delete t[n],s=N(e,t)}return s}function F(e,t,o){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+o]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([o]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,o);break;case"int16":e.write(n.from([r.properties[t]])),f(e,o);break;case"int32":e.write(n.from([r.properties[t]])),j(e,o);break;case"var":e.write(n.from([r.properties[t]])),O(e,o);break;case"string":e.write(n.from([r.properties[t]])),P(e,o);break;case"pair":Object.getOwnPropertyNames(o).forEach((a=>{const s=o[a];Array.isArray(s)?s.forEach((o=>{e.write(n.from([r.properties[t]])),R(e,a.toString(),o.toString())})):(e.write(n.from([r.properties[t]])),R(e,a.toString(),s.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${o}`)),!1}}function q(e,t,n){O(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)F(e,n,r[t]);else F(e,n,r)}}function L(e){return e?e instanceof n?e.length:n.byteLength(e):0}function $(e){return"string"==typeof e||e instanceof n}t.exports=m}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,n){var r=1e3,o=60*r,a=60*o,s=24*a,i=7*s,c=365.25*s;function l(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*i;case"days":case"day":case"d":return n*s;case"hours":case"hour":case"hrs":case"hr":case"h":return n*a;case"minutes":case"minute":case"mins":case"min":case"m":return n*o;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=a?Math.round(e/a)+"h":t>=o?Math.round(e/o)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=s?h(e,t,s,"day"):t>=a?h(e,t,a,"hour"):t>=o?h(e,t,o,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var o=t>=1.5*n;return Math.round(e/n)+" "+r+(o?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,o=e("debug")("number-allocator:trace"),a=e("debug")("number-allocator:error");function s(e,t){this.low=e,this.high=t}function i(e,t){if(!(this instanceof i))return new i(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),o("Create"),this.clear()}s.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},s.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return o("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),o("alloc():"+t),t},i.prototype.use=function(e){const t=new s(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),o("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,o("use():"+e),!0;if(n.high===e)return--n.high,o("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new s(r,e-1)),o("use():"+e),!0}return o("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void a("free():"+e+" is out of range");const t=new s(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void a("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}o("free():"+e)},i.prototype.clear=function(){o("clear()"),this.ss.clear(),this.ss.insert(new s(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=i},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function o(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function a(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(o),t.exports.strict=r(a),o.proto=o((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return o(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return a(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,o){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var a,s,i=arguments.length;switch(i){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,o)}));default:for(a=new Array(i-1),s=0;s<a.length;)a[s++]=arguments[s];return e.nextTick((function(){t.apply(null,a)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,o,a=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(o===clearTimeout)return clearTimeout(e);if((o===i||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(e);try{return o(e)}catch(t){try{return o.call(null,e)}catch(t){return o.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{o="function"==typeof clearTimeout?clearTimeout:i}catch(e){o=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&g())}function g(){if(!h){var e=c(f);h=!0;for(var t=u.length;t;){for(d=u,u=[];++p<t;)d&&d[p].run();p=-1,t=u.length}d=null,h=!1,l(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new m(e,t)),1!==u.length||h||c(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=y,a.addListener=y,a.once=y,a.off=y,a.removeListener=y,a.removeAllListeners=y,a.emit=y,a.prependListener=y,a.prependOnceListener=y,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var o="object"==typeof n&&n&&!n.nodeType&&n,a="object"==typeof t&&t&&!t.nodeType&&t,s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self!==s||(r=s);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-u,_=Math.floor,S=String.fromCharCode;function k(e){throw new RangeError(C[e])}function E(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function A(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+E((e=e.replace(w,".")).split("."),t).join(".")}function T(e){for(var t,n,r=[],o=0,a=e.length;o<a;)(t=e.charCodeAt(o++))>=55296&&t<=56319&&o<a?56320==(64512&(n=e.charCodeAt(o++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),o--):r.push(t);return r}function M(e){return E(e,(function(e){var t="";return e>65535&&(t+=S((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=S(e)})).join("")}function O(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function P(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function R(e,t,n){var r=0;for(e=n?_(e/f):e>>1,e+=_(e/t);e>I*h>>1;r+=d)e=_(e/I);return _(r+(I+1)*e/(e+p))}function U(e){var t,n,r,o,a,s,i,c,p,f,v=[],b=e.length,w=0,C=m,I=g;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(o=n>0?n+1:0;o<b;){for(a=w,s=1,i=d;o>=b&&k("invalid-input"),((c=O(e.charCodeAt(o++)))>=d||c>_((l-w)/s))&&k("overflow"),w+=c*s,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)s>_(l/(f=d-p))&&k("overflow"),s*=f;I=R(w-a,t=v.length+1,0==a),_(w/t)>l-C&&k("overflow"),C+=_(w/t),w%=t,v.splice(w++,0,C)}return M(v)}function x(e){var t,n,r,o,a,s,i,c,p,f,v,b,w,C,I,E=[];for(b=(e=T(e)).length,t=m,n=0,a=g,s=0;s<b;++s)(v=e[s])<128&&E.push(S(v));for(r=o=E.length,o&&E.push(y);r<b;){for(i=l,s=0;s<b;++s)(v=e[s])>=t&&v<i&&(i=v);for(i-t>_((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,s=0;s<b;++s)if((v=e[s])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=a?u:p>=a+h?h:p-a));p+=d)I=c-f,C=d-f,E.push(S(P(f+I%C,0))),c=_(I/C);E.push(S(P(c,0))),a=R(n,w,r==o),n=0,++r}++n,++t}return E.join("")}function j(e){return A(e,(function(e){return v.test(e)?U(e.slice(4).toLowerCase()):e}))}function D(e){return A(e,(function(e){return b.test(e)?"xn--"+x(e):e}))}if(i={version:"1.4.1",ucs2:{decode:T,encode:M},decode:U,encode:x,toASCII:D,toUnicode:j},o&&a)if(t.exports==o)a.exports=i;else for(c in i)i.hasOwnProperty(c)&&(o[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==St?St:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,a){t=t||"&",n=n||"=";var s={};if("string"!=typeof e||0===e.length)return s;var i=/\+/g;e=e.split(t);var c=1e3;a&&"number"==typeof a.maxKeys&&(c=a.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,g=e[d].replace(i,"%20"),m=g.indexOf(n);m>=0?(u=g.substr(0,m),h=g.substr(m+1)):(u=g,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(s,p)?o(s[p])?s[p].push(f):s[p]=[s[p],f]:s[p]=f}return s};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?a(s(e),(function(s){var i=encodeURIComponent(r(s))+n;return o(e[s])?a(e[s],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[s]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function a(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var s=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var o={};function a(e,t,n){function a(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,r){return e.call(this,a(t,n,r))||this}return r(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,o[e]=s}function s(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}a("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),a("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,o;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))o="The ".concat(e," ").concat(r," ").concat(s(t,"type"));else{var a=l(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(a," ").concat(r," ").concat(s(t,"type"))}return o+=". Received type ".concat(typeof n)}),TypeError),a("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),a("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),a("ERR_STREAM_PREMATURE_CLOSE","Premature close"),a("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),a("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),a("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),a("ERR_STREAM_WRITE_AFTER_END","write after end"),a("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),a("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),a("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=o},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var o=e("./_stream_readable"),a=e("./_stream_writable");e("inherits")(l,o);for(var s=r(a.prototype),i=0;i<s.length;i++){var c=s[i];l.prototype[c]||(l.prototype[c]=a.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);o.call(this,e),a.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=o;var r=e("./_stream_transform");function o(e){if(!(this instanceof o))return new o(e);r.call(this,e)}e("inherits")(o,r),o.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var o;t.exports=T,T.ReadableState=A,e("events").EventEmitter;var a=function(e,t){return e.listeners(t).length},s=e("./internal/streams/stream"),i=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return i.from(e)}function d(e){return i.isBuffer(e)||e instanceof c}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var p,f,g,m=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,C=b.ERR_STREAM_PUSH_AFTER_EOF,I=b.ERR_METHOD_NOT_IMPLEMENTED,_=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(T,s);var S=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function E(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function A(t,n,r){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof o),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new m,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(p||(p=e("string_decoder/").StringDecoder),this.decoder=new p(t.encoding),this.encoding=t.encoding)}function T(t){if(o=o||e("./_stream_duplex"),!(this instanceof T))return new T(t);var n=this instanceof o;this._readableState=new A(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),s.call(this)}function M(e,t,n,r,o){u("readableAddChunk",t);var a,s=e._readableState;if(null===t)s.reading=!1,j(e,s);else if(o||(a=P(s,t)),a)S(e,a);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)s.endEmitted?S(e,new _):O(e,s,t,!0);else if(s.ended)S(e,new C);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?O(e,s,t,!1):B(e,s)):O(e,s,t,!1)}else r||(s.reading=!1,B(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function O(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&D(e)),B(e,t)}function P(e,t){var n;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),T.prototype.destroy=y.destroy,T.prototype._undestroy=y.undestroy,T.prototype._destroy=function(e,t){t(e)},T.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=i.from(e,t),t=""),n=!0),M(this,e,t,!1,n)},T.prototype.unshift=function(e){return M(this,e,null,!0,!1)},T.prototype.isPaused=function(){return!1===this._readableState.flowing},T.prototype.setEncoding=function(t){p||(p=e("string_decoder/").StringDecoder);var n=new p(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,o="";null!==r;)o+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==o&&this._readableState.buffer.push(o),this._readableState.length=o.length,this};var R=1073741824;function U(e){return e>=R?e=R:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function x(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=U(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function j(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?D(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function D(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(N,e))}function N(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,V(e)}function B(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(F,e,t))}function F(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function q(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,V(e))}}function L(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function $(e){u("readable nexttick read 0"),e.read(0)}function K(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(z,e,t))}function z(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),V(e),t.flowing&&!t.reading&&e.read(0)}function V(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function Q(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(W,t,e))}function W(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function G(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}T.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):D(this),null;if(0===(e=x(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,o=t.needReadable;return u("need readable",o),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",o=!0),t.ended||t.reading?u("reading or ended",o=!1):o&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=x(n,t))),null===(r=e>0?Q(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},T.prototype._read=function(e){S(this,new I("_read()"))},T.prototype.pipe=function(e,t){var r=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,u("pipe count=%d opts=%j",o.pipesCount,t);var s=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}o.endEmitted?n.nextTick(s):r.once("end",s),e.on("unpipe",i);var l=q(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",p),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==G(o.pipes,e))&&!d&&(u("false write response, pause",o.awaitDrain),o.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===a(e,"error")&&S(e,t)}function g(){e.removeListener("finish",m),y()}function m(){u("onfinish"),e.removeListener("close",g),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),E(e,"error",f),e.once("close",g),e.once("finish",m),e.emit("pipe",r),o.flowing||(u("pipe resume"),r.resume()),e},T.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<o;a++)r[a].emit("unpipe",this,{hasUnpiped:!1});return this}var s=G(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},T.prototype.on=function(e,t){var r=s.prototype.on.call(this,e,t),o=this._readableState;return"data"===e?(o.readableListening=this.listenerCount("readable")>0,!1!==o.flowing&&this.resume()):"readable"===e&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,u("on readable",o.length,o.reading),o.length?D(this):o.reading||n.nextTick($,this))),r},T.prototype.addListener=T.prototype.on,T.prototype.removeListener=function(e,t){var r=s.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(L,this),r},T.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(L,this),t},T.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,K(this,e)),e.paused=!1,this},T.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},T.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var o in e.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){u("wrapped data"),n.decoder&&(o=n.decoder.write(o)),n.objectMode&&null==o||(n.objectMode||o&&o.length)&&(t.push(o)||(r=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var a=0;a<k.length;a++)e.on(k[a],this.emit.bind(this,k[a]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(T.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(T.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(T.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(T.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),T._fromList=Q,Object.defineProperty(T.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(T.from=function(t,n){return void 0===g&&(g=e("./internal/streams/from")),g(T,t,n)})}).call(this)}).call(this,e("_process"),void 0!==St?St:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,n){t.exports=d;var r=e("../errors").codes,o=r.ERR_METHOD_NOT_IMPLEMENTED,a=r.ERR_MULTIPLE_CALLBACK,s=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new a);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new s;return e.push(null)}e("inherits")(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new o("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var o=this._readableState;(r.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){z(t,e)}}var a;t.exports=A,A.WritableState=E;var s={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function d(e){return c.from(e)}function u(e){return c.isBuffer(e)||e instanceof l}var h,p=e("./internal/streams/destroy"),f=e("./internal/streams/state").getHighWaterMark,g=e("../errors").codes,m=g.ERR_INVALID_ARG_TYPE,y=g.ERR_METHOD_NOT_IMPLEMENTED,v=g.ERR_MULTIPLE_CALLBACK,b=g.ERR_STREAM_CANNOT_PIPE,w=g.ERR_STREAM_DESTROYED,C=g.ERR_STREAM_NULL_VALUES,I=g.ERR_STREAM_WRITE_AFTER_END,_=g.ERR_UNKNOWN_ENCODING,S=p.errorOrDestroy;function k(){}function E(t,n,r){a=a||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof a),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){j(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function A(t){var n=this instanceof(a=a||e("./_stream_duplex"));if(!n&&!h.call(A,this))return new A(t);this._writableState=new E(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),i.call(this)}function T(e,t){var r=new I;S(e,r),n.nextTick(t,r)}function M(e,t,r,o){var a;return null===r?a=new C:"string"==typeof r||t.objectMode||(a=new m("chunk",["string","Buffer"],r)),!a||(S(e,a),n.nextTick(o,a),!1)}function O(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function P(e,t,n,r,o,a){if(!n){var s=O(t,r,o);r!==s&&(n=!0,o="buffer",r=s)}var i=t.objectMode?1:r.length;t.length+=i;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:o,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,i,r,o,a);return c}function R(e,t,n,r,o,a,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(o,t.onwrite):e._write(o,a,t.onwrite),t.sync=!1}function U(e,t,r,o,a){--t.pendingcb,r?(n.nextTick(a,o),n.nextTick($,e,t),e._writableState.errorEmitted=!0,S(e,o)):(a(o),e._writableState.errorEmitted=!0,S(e,o),$(e,t))}function x(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function j(e,t){var r=e._writableState,o=r.sync,a=r.writecb;if("function"!=typeof a)throw new v;if(x(r),t)U(e,r,o,t,a);else{var s=F(r)||e.destroyed;s||r.corked||r.bufferProcessing||!r.bufferedRequest||B(e,r),o?n.nextTick(D,e,r,s,a):D(e,r,s,a)}}function D(e,t,n,r){n||N(e,t),t.pendingcb--,r(),$(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function B(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,a=new Array(r),s=t.corkedRequestsFree;s.entry=n;for(var i=0,c=!0;n;)a[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;a.allBuffers=c,R(e,t,!0,t.length,a,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(R(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function F(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function q(e,t){e._final((function(n){t.pendingcb--,n&&S(e,n),t.prefinished=!0,e.emit("prefinish"),$(e,t)}))}function L(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(q,e,t)))}function $(e,t){var n=F(t);if(n&&(L(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function K(e,t,r){t.ending=!0,$(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function z(e,t,n){var r=e.entry;for(e.entry=null;r;){var o=r.callback;t.pendingcb--,o(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(A,i),E.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(E.prototype,"buffer",{get:s.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(A,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===A&&e&&e._writableState instanceof E}})):h=function(e){return e instanceof this},A.prototype.pipe=function(){S(this,new b)},A.prototype.write=function(e,t,n){var r=this._writableState,o=!1,a=!r.objectMode&&u(e);return a&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?T(this,n):(a||M(this,r,e,n))&&(r.pendingcb++,o=P(this,r,a,e,t,n)),o},A.prototype.cork=function(){this._writableState.corked++},A.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||B(this,e))},A.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,n){n(new y("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||K(this,r,n),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=p.destroy,A.prototype._undestroy=p.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==St?St:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,n){(function(n){(function(){var r;function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var a=e("./end-of-stream"),s=Symbol("lastResolve"),i=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function f(e){var t=e[s];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[s]=null,e[i]=null,t(p(n,!1)))}}function g(e){n.nextTick(f,e)}function m(e,t){return function(n,r){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((o(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(p(void 0,!0))}))}));var r,o=this[d];if(o)r=new Promise(m(o,this));else{var a=this[h].read();if(null!==a)return Promise.resolve(p(a,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),o(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(p(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(o(t={},h,{value:e,writable:!0}),o(t,s,{value:null,writable:!0}),o(t,i,{value:null,writable:!0}),o(t,c,{value:null,writable:!0}),o(t,l,{value:e._readableState.endEmitted,writable:!0}),o(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[s]=null,n[i]=null,e(p(r,!1))):(n[s]=e,n[i]=t)},writable:!0}),t));return n[d]=null,a(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[s]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[s];null!==r&&(n[d]=null,n[s]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",g.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(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 o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var l=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){s(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var o=t.data,a=e>o.length?o.length:e;if(a===o.length?r+=o:r+=o.slice(0,e),0==(e-=a)){a===o.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=o.slice(a));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,a),0==(e-=a)){a===o.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(a));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,o({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var a=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(s,this,t)):e.nextTick(s,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?a._writableState?a._writableState.errorEmitted?e.nextTick(o,a):(a._writableState.errorEmitted=!0,e.nextTick(r,a,t)):e.nextTick(r,a,t):n?(e.nextTick(o,a),n(t)):e.nextTick(o,a)})),this)}function r(e,t){s(e,t),o(e)}function o(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function s(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function o(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];e.apply(this,r)}}}function a(){}function s(e){return e.setHeader&&"function"==typeof e.abort}function i(e,t,n){if("function"==typeof t)return i(e,null,t);t||(t={}),n=o(n||a);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},g=function(t){n.call(e,t)},m=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return s(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",f),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",f),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=i},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function o(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var a=e("../../../errors").codes,s=a.ERR_MISSING_ARGS,i=a.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,a,s){s=o(s);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:a},(function(e){if(e)return s(e);c=!0,s()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void s(e||new i("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function p(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,o=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new s("streams");var a=t.map((function(e,n){var s=n<t.length-1;return d(e,s,n>0,(function(e){r||(r=e),e&&a.forEach(u),s||(a.forEach(u),o(r))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function o(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function a(e,t,n,a){var s=o(t,a,n);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new r(a?n:"highWaterMark",s);return Math.floor(s)}return e.objectMode?16:16384}t.exports={getHighWaterMark:a}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function o(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new r(arguments[0],arguments[1],e)}t.exports=o},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?o(e):e.proto?a:r;function t(e,t){for(var r=Object.keys(e),o=new Array(r.length),a=0;a<r.length;a++){var s=r[a],i=e[s];"object"!=typeof i||null===i?o[s]=i:i instanceof Date?o[s]=new Date(i):ArrayBuffer.isView(i)?o[s]=n(i):o[s]=t(i)}return o}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var o={};for(var a in e)if(!1!==Object.hasOwnProperty.call(e,a)){var s=e[a];"object"!=typeof s||null===s?o[a]=s:s instanceof Date?o[a]=new Date(s):s instanceof Map?o[a]=new Map(t(Array.from(s),r)):s instanceof Set?o[a]=new Set(t(Array.from(s),r)):ArrayBuffer.isView(s)?o[a]=n(s):o[a]=r(s)}return o}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,a);if(e instanceof Map)return new Map(t(Array.from(e),a));if(e instanceof Set)return new Set(t(Array.from(e),a));var r={};for(var o in e){var s=e[o];"object"!=typeof s||null===s?r[o]=s:s instanceof Date?r[o]=new Date(s):s instanceof Map?r[o]=new Map(t(Array.from(s),a)):s instanceof Set?r[o]=new Set(t(Array.from(s),a)):ArrayBuffer.isView(s)?r[o]=n(s):r[o]=a(s)}return r}}function o(e){var t=[],r=[];return e.proto?s:a;function o(e,o){for(var a=Object.keys(e),s=new Array(a.length),i=0;i<a.length;i++){var c=a[i],l=e[c];if("object"!=typeof l||null===l)s[c]=l;else if(l instanceof Date)s[c]=new Date(l);else if(ArrayBuffer.isView(l))s[c]=n(l);else{var d=t.indexOf(l);s[c]=-1!==d?r[d]:o(l)}}return s}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,a);if(e instanceof Map)return new Map(o(Array.from(e),a));if(e instanceof Set)return new Set(o(Array.from(e),a));var s={};for(var i in t.push(e),r.push(s),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)s[i]=c;else if(c instanceof Date)s[i]=new Date(c);else if(c instanceof Map)s[i]=new Map(o(Array.from(c),a));else if(c instanceof Set)s[i]=new Set(o(Array.from(c),a));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?r[l]:a(c)}}return t.pop(),r.pop(),s}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,s);if(e instanceof Map)return new Map(o(Array.from(e),s));if(e instanceof Set)return new Set(o(Array.from(e),s));var a={};for(var i in t.push(e),r.push(a),e){var c=e[i];if("object"!=typeof c||null===c)a[i]=c;else if(c instanceof Date)a[i]=new Date(c);else if(c instanceof Map)a[i]=new Map(o(Array.from(c),s));else if(c instanceof Set)a[i]=new Set(o(Array.from(c),s));else if(ArrayBuffer.isView(c))a[i]=n(c);else{var l=t.indexOf(c);a[i]=-1!==l?r[l]:s(c)}}return t.pop(),r.pop(),a}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
5
4
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
6
- var r=e("buffer"),s=r.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return s(e,t,n)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=r:(i(r,n),n.Buffer=o),o.prototype=Object.create(s.prototype),i(s,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=s(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(s(t)):null}function s(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,s=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function o(e){var t=i(e);if("string"!=typeof t&&(r.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=d,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function l(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function c(e,t,n){var r=t.length-1;if(r<n)return 0;var s=l(t[r]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--r<n||-2===s?0:(s=l(t[r]))>=0?(s>0&&(e.lastNeed=s-2),s):--r<n||-2===s?0:(s=l(t[r]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):0}function u(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function d(e){var t=this.lastTotal-this.lastNeed,n=u(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=c(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=a,a.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},a.prototype.end=f,a.prototype.text=h,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),s=e("./util");function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=S,n.resolveObject=C,n.format=E,n.Url=i;var o=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(c),d=["%","/","?",";","#"].concat(u),h=["/","?","#"],f=255,p=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&s.isObject(e)&&e instanceof i)return e;var r=new i;return r.parse(e,t,n),r}function E(e){return s.isString(e)&&(e=w(e)),e instanceof i?e.format():i.prototype.format.call(e)}function S(e,t){return w(e,!1,!0).resolve(t)}function C(e,t){return e?w(e,!1,!0).resolveObject(t):t}i.prototype.parse=function(e,t,n){if(!s.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),a=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(a),w=/\\/g;c[0]=c[0].replace(w,"/");var E=e=c.join(a);if(E=E.trim(),!n&&1===e.split("#").length){var S=l.exec(E);if(S)return this.path=E,this.href=E,this.pathname=S[1],S[2]?(this.search=S[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var C=o.exec(E);if(C){var T=(C=C[0]).toLowerCase();this.protocol=T,E=E.substr(C.length)}if(n||C||E.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===E.substr(0,2);!k||C&&y[C]||(E=E.substr(2),this.slashes=!0)}if(!y[C]&&(k||C&&!v[C])){for(var _,I,A=-1,R=0;R<h.length;R++)-1!==(L=E.indexOf(h[R]))&&(-1===A||L<A)&&(A=L);for(-1!==(I=-1===A?E.lastIndexOf("@"):E.lastIndexOf("@",A))&&(_=E.slice(0,I),E=E.slice(I+1),this.auth=decodeURIComponent(_)),A=-1,R=0;R<d.length;R++){var L;-1!==(L=E.indexOf(d[R]))&&(-1===A||L<A)&&(A=L)}-1===A&&(A=E.length),this.host=E.slice(0,A),E=E.slice(A),this.parseHost(),this.hostname=this.hostname||"";var D="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!D)for(var O=this.hostname.split(/\./),x=(R=0,O.length);R<x;R++){var P=O[R];if(P&&!P.match(p)){for(var M="",F=0,U=P.length;F<U;F++)P.charCodeAt(F)>127?M+="x":M+=P[F];if(!M.match(p)){var N=O.slice(0,R),B=O.slice(R+1),j=P.match(g);j&&(N.push(j[1]),B.unshift(j[2])),B.length&&(E="/"+B.join(".")+E),this.hostname=N.join(".");break}}}this.hostname.length>f?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=r.toASCII(this.hostname));var $=this.port?":"+this.port:"",q=this.hostname||"";this.host=q+$,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==E[0]&&(E="/"+E))}if(!m[T])for(R=0,x=u.length;R<x;R++){var K=u[R];if(-1!==E.indexOf(K)){var G=encodeURIComponent(K);G===K&&(G=escape(K)),E=E.split(K).join(G)}}var H=E.indexOf("#");-1!==H&&(this.hash=E.substr(H),E=E.slice(0,H));var V=E.indexOf("?");if(-1!==V?(this.search=E.substr(V),this.query=E.substr(V+1),t&&(this.query=b.parse(this.query)),E=E.slice(0,V)):t&&(this.search="",this.query={}),E&&(this.pathname=E),v[T]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){$=this.pathname||"";var z=this.search||"";this.path=$+z}return this.href=this.format(),this},i.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",i=!1,o="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var a=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==i?(i="//"+(i||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):i||(i=""),r&&"#"!==r.charAt(0)&&(r="#"+r),a&&"?"!==a.charAt(0)&&(a="?"+a),t+i+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.replace("#","%23"))+r},i.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},i.prototype.resolveObject=function(e){if(s.isString(e)){var t=new i;t.parse(e,!1,!0),e=t}for(var n=new i,r=Object.keys(this),o=0;o<r.length;o++){var a=r[o];n[a]=this[a]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var l=Object.keys(e),c=0;c<l.length;c++){var u=l[c];"protocol"!==u&&(n[u]=e[u])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var d=Object.keys(e),h=0;h<d.length;h++){var f=d[h];n[f]=e[f]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),n.pathname=p.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),E=w||b||n.host&&e.pathname,S=E,C=n.pathname&&n.pathname.split("/")||[],T=(p=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(T&&(n.hostname="",n.port=null,n.host&&(""===C[0]?C[0]=n.host:C.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),E=E&&(""===p[0]||""===C[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,C=p;else if(p.length)C||(C=[]),C.pop(),C=C.concat(p),n.search=e.search,n.query=e.query;else if(!s.isNullOrUndefined(e.search))return T&&(n.hostname=n.host=C.shift(),(R=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=R.shift(),n.host=n.hostname=R.shift())),n.search=e.search,n.query=e.query,s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!C.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=C.slice(-1)[0],_=(n.host||e.host||C.length>1)&&("."===k||".."===k)||""===k,I=0,A=C.length;A>=0;A--)"."===(k=C[A])?C.splice(A,1):".."===k?(C.splice(A,1),I++):I&&(C.splice(A,1),I--);if(!E&&!S)for(;I--;I)C.unshift("..");!E||""===C[0]||C[0]&&"/"===C[0].charAt(0)||C.unshift(""),_&&"/"!==C.join("/").substr(-1)&&C.push("");var R,L=""===C[0]||C[0]&&"/"===C[0].charAt(0);return T&&(n.hostname=n.host=L?"":C.length?C.shift():"",(R=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=R.shift(),n.host=n.hostname=R.shift())),(E=E||n.host&&C.length)&&!L&&C.unshift(""),C.length?n.pathname=C.join("/"):(n.pathname=null,n.path=null),s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},i.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function s(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return s}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==gt?gt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),s=t[t.length-1];return"function"==typeof r&&r!==s&&Object.keys(s).forEach((function(e){r[e]=s[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=s;var r=Object.prototype.hasOwnProperty;function s(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var s in n)r.call(n,s)&&(e[s]=n[s])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,s=arguments.length;n<s;n++)t.push(arguments[n]);return t}function s(e,t,n){var r=t===e.head?new a(n,null,t,e):new a(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function i(e,t){e.tail=new a(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new a(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function a(e,t,n,r){if(!(this instanceof a))return new a(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=a,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,s=this.head;null!==s;)n.push(e.call(t,s.value,this)),s=s.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,s=this.tail;null!==s;)n.push(e.call(t,s.value,this)),s=s.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var s=0;null!==r;s++)n=e(n,r.value,s),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var s=this.length-1;null!==r;s--)n=e(n,r.value,s),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,i=this.head;null!==i&&s<e;s++)i=i.next;for(;null!==i&&s<t;s++,i=i.next)n.push(i.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,i=this.tail;null!==i&&s>t;s--)i=i.prev;for(;null!==i&&s>e;s--,i=i.prev)n.push(i.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,i=this.head;null!==i&&r<e;r++)i=i.next;var o=[];for(r=0;i&&r<t;r++)o.push(i.value),i=this.removeNode(i);for(null===i&&(i=this.tail),i!==this.head&&i!==this.tail&&(i=i.prev),r=0;r<n.length;r++)i=s(this,i,n[r]);return o},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12)}(Do);var Oo=mt(Do.exports);const xo=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype},{hasOwnProperty:Po}=Object.prototype,{propertyIsEnumerable:Mo}=Object,Fo=(e,t,n)=>Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}),Uo=gt,No={concatArrays:!1,ignoreUndefined:!1},Bo=e=>{const t=[];for(const n in e)Po.call(e,n)&&t.push(n);if(Object.getOwnPropertySymbols){const n=Object.getOwnPropertySymbols(e);for(const r of n)Mo.call(e,r)&&t.push(r)}return t};function jo(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return Bo(e).forEach((n=>{Fo(t,n,jo(e[n]))})),t}(e):xo(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return Bo(e).forEach((n=>{Fo(t,n,jo(e[n]))})),t}(e):e}const $o=(e,t,n,r)=>(n.forEach((n=>{void 0===t[n]&&r.ignoreUndefined||(n in e&&e[n]!==Object.getPrototypeOf(e)?Fo(e,n,qo(e[n],t[n],r)):Fo(e,n,jo(t[n])))})),e);function qo(e,t,n){return n.concatArrays&&Array.isArray(e)&&Array.isArray(t)?((e,t,n)=>{let r=e.slice(0,0),s=0;return[e,t].forEach((t=>{const i=[];for(let n=0;n<t.length;n++)Po.call(t,n)&&(i.push(String(n)),Fo(r,s++,t===e?t[n]:jo(t[n])));r=$o(r,t,Bo(t).filter((e=>!i.includes(e))),n)})),r})(e,t,n):xo(t)&&xo(e)?$o(e,t,Bo(t),n):jo(t)}const Ko=function(...e){const t=qo(jo(No),this!==Uo&&this||{},No);let n={_:{}};for(const r of e)if(void 0!==r){if(!xo(r))throw new TypeError("`"+r+"` is not an Option Object");n=qo(n,{_:r},t)}return n._}.bind({concatArrays:!0,ignoreUndefined:!0});function Go(e,t){return new Promise(((n,r)=>{try{const r=e();null==t||t(null,r),n(r)}catch(e){null==t||t(e),r(e)}}))}function Ho(e,t,n){return Promise.all(e).then((e=>{var r;const s=null!==(r=null==n?void 0:n(e))&&void 0!==r?r:null;return null==t||t(null,s),Promise.resolve(s)}),(e=>(null==t||t(e),Promise.reject(e))))}const Vo={getItem:(e,t)=>Go((()=>window.localStorage.getItem(e)),t),setItem:(e,t,n)=>Go((()=>window.localStorage.setItem(e,t)),n),removeItem:(e,t)=>Go((()=>window.localStorage.removeItem(e)),t),mergeItem:(e,t,n)=>Go((()=>function(e,t){const n=window.localStorage.getItem(e);if(n){const r=JSON.parse(n),s=JSON.parse(t),i=JSON.stringify(Ko(r,s));window.localStorage.setItem(e,i)}else window.localStorage.setItem(e,t)}(e,t)),n),clear:e=>Go((()=>window.localStorage.clear()),e),getAllKeys:e=>Go((()=>{const e=window.localStorage.length,t=[];for(let n=0;n<e;n+=1){const e=window.localStorage.key(n)||"";t.push(e)}return t}),e),flushGetRequests:()=>{},multiGet:(e,t)=>Ho(e.map((e=>Vo.getItem(e))),t,(t=>t.map(((t,n)=>[e[n],t])))),multiSet:(e,t)=>Ho(e.map((e=>Vo.setItem(e[0],e[1]))),t),multiRemove:(e,t)=>Ho(e.map((e=>Vo.removeItem(e))),t),multiMerge:(e,t)=>Ho(e.map((e=>Vo.mergeItem(e[0],e[1]))),t)};class zo{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 Wo=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new zo};var Yo={},Qo={},Xo={};Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.bytesToString=Xo.stringToBytes=Xo.NIL=Xo.X500=Xo.OID=Xo.URL=Xo.DNS=Xo.hexToByte=Xo.byteToHex=void 0;let Jo=[],Zo={};for(var ea=0;ea<256;ea++)Jo[ea]=(ea+256).toString(16).substr(1),Zo[Jo[ea]]=ea;Xo.byteToHex=Jo,Xo.hexToByte=Zo,Xo.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Xo.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Xo.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",Xo.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",Xo.NIL="00000000-0000-0000-0000-000000000000";Xo.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};Xo.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.parse=void 0;const ta=Xo;Qo.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++]=ta.hexToByte[e]),"")));s<16;)t[r+s++]=0;return t};var na={};Object.defineProperty(na,"__esModule",{value:!0}),na.unparse=void 0;const ra=Xo;na.unparse=(e,t)=>{let n=t||0,r=ra.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 sa={},ia={};Object.defineProperty(ia,"__esModule",{value:!0});ia.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 oa=gt&&gt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(sa,"__esModule",{value:!0}),sa.validate=void 0;const aa=oa(ia);sa.validate=e=>"string"==typeof e&&aa.default.test(e);var la={};Object.defineProperty(la,"__esModule",{value:!0}),la.version=void 0;const ca=sa;la.version=e=>{if(!ca.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var ua={},da={};Object.defineProperty(da,"__esModule",{value:!0}),da.stringify=void 0;const ha=sa,fa=[];for(let e=0;e<256;++e)fa.push((e+256).toString(16).substr(1));da.stringify=(e,t=0)=>{const n=(fa[e[t+0]]+fa[e[t+1]]+fa[e[t+2]]+fa[e[t+3]]+"-"+fa[e[t+4]]+fa[e[t+5]]+"-"+fa[e[t+6]]+fa[e[t+7]]+"-"+fa[e[t+8]]+fa[e[t+9]]+"-"+fa[e[t+10]]+fa[e[t+11]]+fa[e[t+12]]+fa[e[t+13]]+fa[e[t+14]]+fa[e[t+15]]).toLowerCase();if(!ha.validate(n))throw TypeError("Stringified UUID is invalid");return n};var pa={};Object.defineProperty(pa,"__esModule",{value:!0}),pa.rng=void 0;pa.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(ua,"__esModule",{value:!0}),ua.v1=void 0;const ga=da,ma=pa;let ya,va,ba=0,wa=0;ua.v1=(e,t,n=0)=>{let r=t&&n||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:ya,o=e&&e.clockseq?e.clockseq:va;if(null==i||null==o){const t=e&&e.random?e.random:e&&e.rng?e.rng():ma.rng();null==i&&(i=ya=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==o&&(o=va=16383&(t[6]<<8|t[7]))}let a=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:wa+1;const c=a-ba+(l-wa)/1e4;if(c<0&&e&&!e.clockseq&&(o=o+1&16383),(c<0||a>ba)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");ba=a,wa=l,va=o,a+=122192928e5;const u=(1e4*(268435455&a)+l)%4294967296;s[r++]=u>>>24&255,s[r++]=u>>>16&255,s[r++]=u>>>8&255,s[r++]=255&u;const d=a/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=255&d,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=255&o;for(let e=0;e<6;++e)s[r+e]=i[e];return t||ga.stringify(s)};var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.v4=void 0;const Sa=na,Ca=pa;Ea.v4=(e,t,n)=>{let r=t&&n||0,s=Ca.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||Sa.unparse(s)};var Ta={},ka={};Object.defineProperty(ka,"__esModule",{value:!0}),ka.v35=void 0;const _a=da,Ia=Qo,Aa=Xo;ka.v35=(e,t,n)=>(e,r,s,i=0)=>{if("string"==typeof e&&(e=Aa.stringToBytes(e)),"string"==typeof r&&(r=Ia.parse(r)),r&&16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+e.length);if(o.set(r),o.set(e,r.length),o=Aa.stringToBytes(n(Aa.bytesToString(o))),o[6]=15&o[6]|t,o[8]=63&o[8]|128,s)for(let e=0;e<16;++e)s[i+e]=o[e];return s||_a.stringify(o)};var Ra={};!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=>o(r(l(e)));e.any_sha1=(e,t)=>a(r(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>o(s(l(e),l(t)));e.any_hmac_sha1=(e,t,n)=>a(s(l(e),l(t)),n);const r=e=>u(d(c(e),8*e.length)),s=(e,t)=>{let n=c(e);n.length>16&&(n=d(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 o=d(r.concat(c(t)),512+8*t.length);return u(d(s.concat(o),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},o=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),o=0;o<4;o++)8*s+6*o>8*e.length?t+=n:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-o)&63);return t},a=(e,t)=>{var n,r,s,i,o=t.length,a=[],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/o))*o,(i.length>0||r>0)&&(i[i.length]=r);a[a.length]=s,l=i}var c="";for(n=a.length-1;n>=0;n--)c+=t.charAt(a[n]);var u=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(n=c.length;n<u;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},u=e=>{for(var t="",n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>24-n%32&255);return t},d=(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,o=271733878,a=-1009589776,l=0;l<e.length;l+=16){for(var c=r,u=s,d=i,m=o,y=a,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,o)),p(p(a,n[v]),f(v)));a=o,o=i,i=g(s,30),s=r,r=t}r=p(r,c),s=p(s,u),i=p(i,d),o=p(o,m),a=p(a,y)}return[r,s,i,o,a]},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}(Ra);var La=gt&&gt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.v5=void 0;const Da=ka,Oa=La(Ra);Ta.v5=Da.v35("v5",80,Oa.default),Object.defineProperty(Yo,"__esModule",{value:!0});const xa=Qo,Pa=na,Ma=sa,Fa=la,Ua=ua,Na=Ea,Ba=Ta,ja=Xo;var $a=Yo.default={parse:xa.parse,unparse:Pa.unparse,validate:Ma.validate,version:Fa.version,v1:Ua.v1,v4:Na.v4,v5:Ba.v5,NIL:ja.NIL,DNS:ja.DNS,URL:ja.URL,OID:ja.OID,X500:ja.X500};const qa=()=>$a.v4().toString();let Ka=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=qa(),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:Ka}),"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&&(Ka=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Ga=async()=>{const e=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await Vo.getItem(e);return new Promise((t=>{t(Wo().localStorage.getItem(e))}))})("deviceId");if(e)return e;const t=`ascWebSdk#${qa()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await Vo.setItem(e,t),!0):new Promise((n=>{Wo().localStorage.setItem(e,t),n(!0)})))("deviceId",t),t},Ha=()=>{const e=(()=>{var e,t;return(null===(e=_t.versions)||void 0===e?void 0:e.node)?_t.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:h}},Va=1e3;var za;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(za||(za={}));const Wa=e=>{let t;return{connect:async function(n){const r=await(async e=>`mqttjs_${await Ga()}_${e}_${Ka}`)(n.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Oo.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Va,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=Va,(()=>{const e=[pt(ut()),pt(dt()),pt(ht()),pt(ft()),pt(at(He())),pt(ct())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Va),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return 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,n){const r=(t,r)=>{var s;if(t||128===(null===(s=r[0])||void 0===s?void 0:s.qos)){const r=t?new ge(t.message,8e5,"error"):new ye(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Ya=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const s=fe[e];if(!s)return;const i=he(s);i&&r.forEach((e=>{(n?Te:_e)([s,"get",i(e)],e,t)}))}))},Qa=(e,t)=>{const{log:n,cache:r}=we(),s=[e,w,t],i={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:s,data:i}),Ie([e,"get",t],!0),Te(s,i))};function Xa(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 Ja=(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(!we().cache)return;return(null===(n=Ce(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},Za=(e,t,n="userId",r="user")=>{const s=e,i=t,o=s[i],a=Xa(s,["symbol"==typeof i?i:i+""]),l=Ja(o,n,r);return Object.assign(Object.assign({},a),{[t]:l})};function el(e){return e.map((e=>{var{isMentioned:t}=e,n=Xa(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function tl(e){return el(e)}function nl(e){return el(e)}const rl=e=>{var t,n;return null!==(n=null===(t=Ce(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},sl=["analytic","normal-priority"],il=["analytic","high-priority"],ol=async e=>{const t=we(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class al{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=Ce(sl);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ol(t),Ie(sl)}catch(e){this.stop(),Ie(sl)}}async syncHighPriorityCapturedEvent(){try{const e=Ce(il);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ol(t),Ie(il)}catch(e){this.stop(),Ie(il)}}}class ll{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({itemId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,s=(()=>n?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*v);return!(r.getTime()-s.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,n={event:[]},r=Ce(sl);(null==r?void 0:r.data)&&(n.event=r.data.event),n.event.length>=this._poolLimit&&n.event.shift(),n.event.push({contentId:e,contentType:"post",activityType:"view",timestamp:t.toISOString()}),_e(sl,n),this._recentViewed[e]=t}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({itemId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const s={event:[]},i=Ce(il);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()}),_e(il,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Te(["story-seen","get",e.storyId],(new Date).toISOString());const o=Ce(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Te(["story-last-seen",e.targetId],e.expiresAt):Te(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),et("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Ie(sl),Ie(il)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class cl{constructor(){this._client=we(),this._eventCapturer=new ll,this._eventSyncer=new al}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let ul;var dl=()=>(ul||(ul=new cl),ul);const hl=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let n={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const r=Ce(["file","get",`${e.avatarFileId}`]);return(null==r?void 0:r.data)&&(n=null==r?void 0:r.data),n}});class fl{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Ce(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ce(["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=Ce(["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 Ce(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Se(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r}}=t;return n===this._targetId&&(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 pl=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:s,targetUpdatedAt:i,localFilter:o}=e,a=new fl(n,r,s);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:i,hasUnseen:a.getHasUnseenFlag(),syncingStoriesCount:a.syncingStoriesCount,failedStoriesCount:a.failedStoriesCount,localFilter:o,localLastExpires:a.localLastStoryExpires,localLastSeen:a.localLastStorySeenExpiresAt,localSortingDate:a.getLocalLastSortingDate()}},gl=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=Ce(["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=Ce(["user","get",e.userId]);if(null==t?void 0:t.data)return hl(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ce(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>gl(e)))}}),ml=(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=Ce(["messageMarker","get",he("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},yl=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Ce(n))||void 0===t?void 0:t.data,s=Se(["subChannelUnreadInfo","get"]);let i=0,o=!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),o=t.some((({data:e})=>e.isMentioned))}const a=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:i,isMentioned:o});return Te(n,a),a};class vl{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=we(),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=Se(["readReceipt"]))||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=Ce(["readReceipt",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=we();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=Ce(["readReceipt",r]))||void 0===t?void 0:t.data;Te(["readReceipt",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=Ce(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=yl(s.channelId);et("local.channelUnread.updated",e),Te(r,s),et("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Ce(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Te(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Te(["readReceipt",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 bl=null;var wl=()=>(bl||(bl=new vl),bl);const El=e=>{const{subChannelId:t,channelSegment:n}=e;wl().markRead(t,n)},Sl=async e=>{const t=we();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,o=Xa(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=t.cache&&Date.now(),l=tl(s),c=nl(i);return t.cache&&Ya(Object.assign({userMarkers:r,userEntityMarkers:l,userFeedMarkers:c},o),{cachedAt:a}),et("local.channelMarker.updated",{userEntityMarkers:l}),et("local.subChannelMarker.updated",{userFeedMarkers:c}),!0},Cl={comment:gl,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{dl().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Ce(["comment","get",e]))||void 0===t?void 0:t.data;return n?gl(n):null})).filter(Boolean)||[]},get creator(){const t=Ce(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return hl(t.data)}}),user:hl,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let n={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const r=Ce(["file","get",`${e.avatarFileId}`]);return(null==r?void 0:r.data)&&(n=null==r?void 0:r.data),n}}),story:e=>{const t=dl(),n=Ce(["storyTarget","get",e.targetId]),r=Ce(["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=Ce(["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=Ce(["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&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Ce(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ce(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return hl(t.data)},get storyTarget(){if(null==n?void 0:n.data)return pl(n.data)},get isSeen(){const t=Ce(["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:pl,message:e=>{const t=Xa(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return ml(e).readCount},get deliveredCount(){return ml(e).deliveredCount},markRead:()=>El(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ce(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return hl(n)}}),channel:e=>Object.assign(Object.assign({},e),{markAsRead:()=>Sl(e.channelInternalId)})},Tl=e=>{var t;const n=e.messagePreviewId?rl(e.channelId):null,r=null===(t=Ce(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:r?Cl.user(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},kl=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(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:o,dataType:a,isDeleted:l,segment:c,creatorPublicId:u,createdAt:d,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:o,dataType:a,isDeleted:l,segment:c,creatorId:u,createdAt:d,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Ya(r)},_l=e=>{var t,n;return null!==(n=null===(t=Ce(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Il=e=>{var t;const n=e.messagePreviewId?_l(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Ce(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},Al=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:o,creatorPublicId:a,data:l,dataType:c,isDeleted:u,segment:d,createdAt:h,updatedAt:f}=t;return{messagePreviewId:o,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:u,segment:d,creatorId:a,createdAt:h,updatedAt:f,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Ya(r)};function Rl(e){const t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,n),t}function Ll(e,t,n){Te(["subChannel","get",e],Object.assign(Rl(t),n))}const Dl=async e=>{var t,n,r,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ce(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(n=Ce(["subChannel","get",h]))||void 0===n?void 0:n.data;Te(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),Ll(e.subChannelId,t,{messagePreviewId:o})}const m=null===(r=Ce(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(s=Ce(["subChannel","get",h]))||void 0===s?void 0:s.data;Te(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},Ol=async e=>{var t,n,r,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ce(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(n=Ce(["subChannel","get",h]))||void 0===n?void 0:n.data;Ll(e.subChannelId,t,{messagePreviewId:o}),Te(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(r=Ce(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=Ce(["subChannel","get",h]))||void 0===s?void 0:s.data;Te(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},xl=async e=>{var t,n,r,s;const{channelId:i,subChannelId:o}=e,a=null===(t=Ce(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==a?void 0:a.subChannelId)===o){const e=null===(n=Ce(["subChannel","get",o]))||void 0===n?void 0:n.data;Te(["messagePreviewChannel","get",i],Object.assign(Object.assign({},a),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(r=Ce(["messagePreviewSubChannel","get",o]))||void 0===r?void 0:r.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=Ce(["subChannel","get",o]))||void 0===s?void 0:s.data;Te(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Pl=(e,t)=>{var n,r,s,i,o;const a=we();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ce(["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!==(o=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(i=(e=>{var t;const n={entityId:e,userId:He()._id};return null===(t=Ce(["channelMarker","get",he("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===i?void 0:i.unreadCount)&&void 0!==o?o:0},Ml=(e,t)=>{var n,r,s,i;const o=we();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ce(["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:He()._id};return null===(t=Ce(["channelMarker","get",he("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==i&&i},Fl=["broadcast","conversation","community"],Ul=({type:e})=>Fl.includes(e);function Nl(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const s=null===(n=Ce(["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({get unreadCount(){return Pl(e)},get hasMentioned(){return Ml(e)},get isMentioned(){return Ml(e)},get subChannelsUnreadCount(){return Pl(e)}},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ul(e),messagePreviewId:r})}const Bl=(e,t={isMessagePreviewUpdated:!0})=>{Ya({channels:e.channels.map((e=>Nl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},jl=async(e,t={isMessagePreviewUpdated:!0})=>{const n=we(),r=await n.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&kl(e);const s=e.channels.filter(Ul).map((({channelInternalId:e})=>e));if(s.length>0){Bl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=we();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=tl(r),o=t.cache&&Date.now();return t.cache&&Ya({userEntityMarkers:i,userMarkers:s},{cachedAt:o}),et("local.channelMarker.fetched",{userEntityMarkers:i}),et("local.userMarker.fetched",{userMarkers:s}),{data:i,cachedAt:o}})(s)}catch(e){}}const i=e.channels.map((e=>Nl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=Ja(e.channelUsers),a=Xa(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},a),{channels:i,channelUsers:o})},$l=async e=>{const t=we();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return et("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ql=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};Ya({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{yl(e)}))}},Kl=async e=>{const t=we(),n=await $l(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:s}=n;ql({feedMarkers:r,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Gl=async e=>{const t=we();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=>{_(null==t?void 0:t.code)&&Qa("channel",e)})),t}const s=await jl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Kl(r);const i=t.cache&&Date.now();return t.cache&&Ya(s,{cachedAt:i}),et("local.channel.fetched",s.channels),{data:s.channels.map((e=>Cl.channel(e))),cachedAt:i}};Gl.locally=e=>{var t,n;const r=we();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=Se(["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)),o=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:i.map((e=>Cl.channel(e))),cachedAt:o.cachedAt}};const Hl=async()=>{const e=we();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&&Ya({userMarkers:n},{cachedAt:r}),et("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}},Vl=e=>!0===e&&void 0;function zl(e,t,n){var r,s;if(n)return n.hasMentioned;const i=we();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=Ce(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:He()._id},a=null===(s=Ce(["subChannelMarker","get",he("subChannelMarker")(o)]))||void 0===s?void 0:s.data;return!!a&&a.hasMentioned}const Wl=["broadcast","conversation","community"],Yl=({channelType:e})=>Wl.includes(e);function Ql(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:s,creatorId:i,creatorPublicId:o,lastMessageId:a,lastMessageTimestamp:l,messageFeedId:c,name:u}=e,d=Xa(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=we();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(r=Ce(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const o={entityId:e,feedId:t,userId:He()._id},a=null===(s=Ce(["subChannelMarker","get",he("subChannelMarker")(o)]))||void 0===s?void 0:s.data;return a?a.unreadCount:0}(t,c)},get hasMentioned(){return zl(t,c)},get isMentioned(){return zl(t,c)}},d),{channelId:n,creatorId:o,displayName:u,lastActivity:l,latestMessageId:a,messageCount:s,subChannelId:c,isUnreadCountSupport:Yl({channelType:r})})}function Xl(e,t,n){var r;const{channelPublicId:s,childCount:i,creatorPublicId:o,mentionedUsers:a,messageFeedId:l,myReactions:c,reactionCount:u,reactions:d,referenceId:h,segment:f,messageId:p,creatorId:g}=e,m=Xa(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let y;h&&(y=Ce(["message","get",h])),y||(y=Ce(["message","get",p]));const v=Object.assign(Object.assign({},m),{messageId:p,channelId:s,channelSegment:f,childrenNumber:i,creatorId:o,creatorPrivateId:e.creatorId,reactions:null!=d?d:{},myReactions:c||(null!==(r=null==y?void 0:y.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:y?y.data.uniqueId:p,referenceId:h});return a&&(v.mentionees=a.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=we(),s=Ce(["message","get",e.messageId]),i=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:i});const o=t[0];o&&o.userId===r.userId&&("message.reactionAdded"!==n||i.includes(o.reactionName)||Object.assign(e,{myReactions:[...i,o.reactionName]}),"message.reactionRemoved"===n&&i.includes(o.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==o.reactionName))}))})(v,t,n),v}const Jl={},Zl=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Ya({messages:(r=e).messages.map((e=>Xl(e,r.reactions)))});const t=n.join("");Jl[t]&&clearTimeout(Jl[t]),Jl[t]=setTimeout((()=>{try{(async e=>{const t=we();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,o=t.cache&&Date.now();t.cache&&Ya({contentMarkers:r,feedMarkers:s,userMarkers:i},{cachedAt:o}),et("local.feedMarker.fetched",{feedMarkers:s}),et("local.messageMarker.fetched",{contentMarkers:r}),et("local.userMarker.fetched",{userMarkers:i})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:s}=e,i=Xa(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const r=null!==(n=null===(t=Ce(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Xa(Ql(e),["unreadCount","hasMentioned","isMentioned"]);Ll(e.messageFeedId,r,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((n=>Xl(n,e.reactions,t)))})};function ec(e){var{subChannelId:t,mentionees:n,dataType:r,data:s}=e,i=Xa(e,["subChannelId","mentionees","dataType","data"]);return r===u.IMAGE||r===u.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 tc(e){var{sortBy:t,subChannelId:n,tags:r,includingTags:s,excludingTags:i,includeDeleted:o,aroundMessageId:a,limit:l,type:c}=e,u=Xa(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},u),{messageFeedId:n,isDeleted:Vl(o),options:{sortBy:t,limit:l||f,around:a}});return r&&(d.includeTags=r),s&&(d.includeTags=s),c&&(d.dataType=c),i&&(d.excludeTags=i),d}const nc=["broadcast","conversation","community"],rc=({channelType:e})=>nc.includes(e),sc=async e=>{const t=e.messageFeeds.filter(rc).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Ya({messageFeeds:e.messageFeeds.map((e=>Ql(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=we();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Z(t,"skiplimit")}}}),{paging:s}=r,i=Xa(r,["paging"]),{userEntityMarkers:o,userFeedMarkers:a,userMarkers:l,feedMarkers:c}=i;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&ql({feedMarkers:c,userFeedMarkers:a});const u=tl(o),d=nl(a),h=n.cache&&Date.now();n.cache&&Ya({userEntityMarkers:u,userFeedMarkers:d,userMarkers:l},{cachedAt:h}),et("local.channelMarker.fetched",{userEntityMarkers:u}),et("local.subChannelMarker.fetched",{userFeedMarkers:d}),et("local.userMarker.fetched",{userMarkers:l});const f=ee(s.next);return{data:d,cachedAt:h,prevPage:ee(s.previous),nextPage:f}})(t)}catch(e){}}Al(e);const n=e.messageFeeds.map(Ql),r=e.messages.map((e=>Xl(e)));return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r})};class ic{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let oc;var ac=()=>(oc||(oc=new ic),oc);const lc=e=>ac().onSessionStateChange(e),cc=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},uc=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return Promise.resolve().then((function(){return ZE})).then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},dc=(e,t)=>{const{log:n,cache:r}=we(),s=[e,w,t];if(!r)return;n("cache/api/isInTombstone",s);const i=Ce(s),{lifeSpan:o}=le("cache_then_server",18e4);if(i&&oe(i.data,o))throw new me("Item not found!",400400,"error")},hc=async e=>{const t=we();t.log("channel/getSubChannel",e),dc("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await sc(n.data),s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),et("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:s}}catch(t){throw _(null==t?void 0:t.code)&&Qa("subChannel",e),t}};hc.locally=e=>{const t=we();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Ce(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};let fc=!1,pc=[];const gc={},mc=async()=>{const e=Object.entries(gc).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=we();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:o}=n,a=tl(r),l=nl(s),c=t.cache&&Date.now();return t.cache&&Ya({userEntityMarkers:a,userFeedMarkers:l,feedMarkers:i,userMarkers:o},{cachedAt:c}),et("local.feedMarker.fetched",{feedMarkers:i}),et("local.channelMarker.fetched",{userEntityMarkers:a}),et("local.subChannelMarker.fetched",{userFeedMarkers:l}),et("local.userMarker.fetched",{userMarkers:o}),!0})(e)},yc=()=>{fc=!1},vc=()=>(fc=!0,lc((e=>{"notLoggedIn"===e&&yc()})),()=>{yc()}),bc=async e=>{const t=await(async e=>{const t=hc.locally(e);if(t)return t.data.channelId;const{data:n}=await hc(e);return n.channelId})(e),n=lt({channelId:t,subChannelId:e});pc.push(pt(n))};cc((async()=>{fc&&await mc()}),3e4);const wc=async e=>{const t=we();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await sc(n.data),s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),et("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:s}};wc.locally=e=>{var t;const n=we();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Ce(["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 Ec=async(e=!0)=>{var t;const n=null===(t=Ce(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var s;return(s=r).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Sc=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Cc=(e,t)=>{var n;const r=null===(n=Ce(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Tc=e=>{const{userId:t}=we();return{currentUser:()=>Cc(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Ce(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Cc(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Ce(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Cc(e,t))})(t,e,n)}},kc=async e=>{const t=we();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},_c=async e=>{const t=we();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},Ic=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Ac={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Rc=e=>{const t=we();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Ac[e].includes(t))(n,e))throw new ge(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,ac().setSessionState(e),!0},Lc=async e=>{const t=we();Rc("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:i}=await(async e=>{const t=we();t.log("client/api/getToken",e);const n=Ha(),{data:r}=await t.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:n}),{headers:{"X-API-Key":t.apiKey}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:i,expiresAt:s},Rc("established"),{accessToken:n,users:r}},Dc=e=>{const t=Se(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Te(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Oc=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Ce(n))||void 0===t?void 0:t.data)&&Ie(n)},xc=e=>{const t=we();return Ze(t,"onChannelDeleted","channel.deleted",(async n=>{const r=await jl(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.channels.forEach((e=>{Dc(e.channelId),Oc(e.channelId)})),Ya(r),e(r.channels[0])}))},Pc=e=>{const t=we();return Ze(t,"onChannelMemberBanned","channel.banned",(async n=>{const r=await jl(n),{channels:s,channelUsers:i}=r,o=i.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&r.channels.forEach((e=>{Dc(e.channelId),Oc(e.channelId)})),Ya(r),e(s[0],i.find((e=>"banned"===e.membership)))}))},Mc=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{n.cache&&Ya(e),t(e.users[0])}))},Fc=e=>Mc("user.deleted",e);class Uc{constructor(){this.TIMER_INTERVAL_MS=y,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(uc((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return Promise.resolve().then((function(){return ZE})).then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{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=>{const{data:t}=await Gl(e);et("local.channel.resolved",t)})(e),t.length>0&&(async e=>{const t=await $l(e),{feedMarkers:n,userFeedMarkers:r}=t;ql({feedMarkers:n,userFeedMarkers:r}),et("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 Nc=null;var Bc=()=>(Nc||(Nc=new Uc),Nc);const jc=async()=>{const e=we();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&Rc("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},$c=e=>{const t=we();Rc("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,jc()},qc=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Kc=e=>{const t=we(),n=qc.map((n=>Ze(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new ge(t.message,t.code,"fatal"):new ve(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Gc=e=>{const t=we();return Ze(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Hc=e=>{const t=he("channelMarker")({userId:He()._id,entityId:e.channelId});Ie(["channelMarker","get",t],!0)},Vc=e=>{const t=we();return Ze(t,"onChannelCreated","channel.created",(async t=>{const n=await jl(t);Ya(n),e(n.channels[0])}))},zc=e=>{const t=we(),n=[Ze(t,"onChannelUpdated","channel.updated",(async t=>{const n=await jl(t);Ya(n),e(n.channels[0])})),Ze(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{n.forEach((e=>e()))}},Wc=e=>{const t=we();return Ze(t,"onChannelJoined","channel.joined",(async t=>{const n=await jl(t),{channels:r,channelUsers:s}=n;Ya(n),e(r[0],s[0])}))},Yc=e=>{const t=we();return Ze(t,"onChannelLeft","channel.left",(async n=>{const{userId:r}=we(),{channelUsers:s}=n,i=s.some((e=>e.userId===r)),o=await jl(n,{isMessagePreviewUpdated:i});t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&i&&o.channels.forEach((e=>{Dc(e.channelId),Oc(e.channelId)}));const{channels:a,channelUsers:l}=o;Ya(o),e(a[0],l[0])}))},Qc=e=>{const t=we();return Ze(t,"onChannelMuted","channel.setMuted",(async t=>{const n=await jl(t);Ya(n),e(n.channels[0])}))},Xc=e=>{const t=we();return Ze(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const n=await jl(t),{channels:r,channelUsers:s}=n;Ya(n),e(r[0],s.find((e=>"member"===e.membership)))}))},Jc=e=>{const t=we();return Ze(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const n=await jl(t),{channels:r,channelUsers:s}=n;Ya(n),e(r[0],s[0])}))},Zc=e=>{const t=we();return Ze(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const n=await jl(t),{channels:r,channelUsers:s}=n;Ya(n),e(r[0],s.find((e=>"none"===e.membership)))}))},eu=e=>{const t=we();return Ze(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))},tu=e=>{const t=we();return Ze(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))},nu=e=>{const t=we();return Ze(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Ya(t),e(t.feedMarkers[0])}))},ru=e=>{const t=we(),n=He(),r=[Ze(t,"message/onMessageCreated","message.created",(async r=>{const s=await Zl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=we(),r=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=Ce(r))||void 0===t?void 0:t.data;if(!s)return;const i=s.lastSegment<e.segment?e.segment:s.lastSegment,o=i-s.readToSegment;let{lastMentionSegment:a}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(a=e.segment)}));const l=Object.assign(Object.assign({},s),{lastMentionSegment:a,lastSegment:i,isMentioned:!(s.readToSegment>=a),unreadCount:Math.max(o,0)});Te(r,l)})(e),yl(e.channelId)})),Ya(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&El(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},su=e=>{const t=we(),n=[Ze(t,"message/onMessageCreated","local.message.created",(t=>t.messages.forEach((t=>{e(t)}))))];return()=>{n.forEach((e=>e()))}},iu=e=>{const t=we();return Ze(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await sc(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};Te(["subChannelUnreadInfo","get",i.subChannelId],i)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Ya(r),e(r.messageFeeds[0])}))},ou=e=>{const t=we(),n=[Ze(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await sc(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Ce(n))||void 0===t?void 0:t.data;r&&Te(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),yl(e.channelId)})),Ya(r),e(r.messageFeeds[0])})),Ze(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},au=async e=>{const t=we();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:o}=n,a=tl(r),l=nl(s),c=t.cache&&Date.now();return t.cache&&Ya({userEntityMarkers:a,userFeedMarkers:l,feedMarkers:i,userMarkers:o},{cachedAt:c}),et("local.feedMarker.fetched",{feedMarkers:i}),et("local.channelMarker.fetched",{userEntityMarkers:a}),et("local.subChannelMarker.fetched",{userFeedMarkers:l}),et("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}},lu=()=>{const e=we();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new ge("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)};let cu=!1,uu=[],du=!1,hu=!0,fu=null;const pu=e=>{null!=e&&(!fu||e.getTime()>fu.getTime())&&(fu=e)},gu=async()=>{const{data:e}=await Hl();null!=e&&pu(new Date(e.lastSyncAt))};let mu=[];const yu=e=>{mu=e},vu=e=>mu.push(e),bu=async()=>{if(!du&&0!==mu.length)try{du=!0,mu=[];const e=await au((null==fu?new Date:fu).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);pu(t),e.hasMore&&mu.push("has_more")}catch(e){}finally{du&&(du=!1)}},wu=()=>{uu.length>0||uu.push(uc((()=>{mu.push("resume")})),ru((e=>{const t=we();rc(e)&&e.creatorId!==t.userId&&mu.push("new message")})),Vc((()=>mu.push("subchannel is created"))),xc((()=>mu.push("subchannel is deleted"))),Wc((()=>mu.push("subchannel is joined"))),Yc((()=>mu.push("subchannel is left"))),iu((()=>mu.push("subchannel is created"))),ou((()=>setTimeout((()=>mu.push("subchannel is deleted")),2e3))),nu((()=>mu.push("feed marker updated"))),(e=>{const t=we();return Ze(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:n,userEntityMarkers:r,userFeedMarkers:s}=t,i=Xa(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=tl(r),a=nl(s);Ya(Object.assign({userMarkers:n,userEntityMarkers:o,userFeedMarker:a},i)),e(n[0])}))})((()=>mu.push("feed marker updated"))),(e=>{const t=we();return Ze(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{t.feedMarkers.forEach((t=>{e(t)}))}))})((()=>mu.push("feed marker updated"))))},Eu=()=>{uu.forEach((e=>e())),uu=[]},Su=async()=>(await gu(),vu("start syncing"),hu=!0,cu=!0,wu(),Eu),Cu=()=>{cu=!1,yu([]),Eu()};cc((async()=>{cu&&await bu()}),2e3);const Tu=()=>hu;let ku=[];const _u=async(e,t,n)=>{const r=we();let s;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await jc(),ku.forEach((e=>e())),ku=[]);const i=await Ga();try{const{users:n}=await Lc(Object.assign(Object.assign({},e),{displayName:(null==e?void 0:e.displayName)||e.userId,deviceId:(null==e?void 0:e.deviceId)||i})),l=n.find((t=>t.userId===e.userId));if(null==l)throw new ge(`${e.userId} has not been founded`,8e5,"error");if(l.isDeleted)return $c("userDeleted"),!1;if(l.isGlobalBanned)return $c("globalBan"),!1;o=r.ws,a=r.emitter,Qe.forEach((e=>{o.on(e,(t=>{a.emit(e,t)}))})),r.ws.open(),r.userId=l.userId,r.sessionHandler=t,s=r.accessTokenExpiryWatcher(t),Ve(l)}catch(e){throw Rc("notLoggedIn"),e}var o,a;if(!0!==(null==n?void 0:n.disableRTE)&&async function(){await rt()}(),await(async()=>{var e;const t=await Ec();if(t===(null===(e=Ce(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Te(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Se(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Ie(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=Se(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Ie(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Gl(n),0!==r.length&&await wc(r)}})(),0===ku.length){ku.push(Gc((e=>{$c("globalBan"),ku.forEach((e=>e())),s()})),(e=>{const t=we();return Ze(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{$c(),ku.forEach((e=>e())),s()})),Fc((e=>{e.userId===r.userId&&($c("userDeleted"),ku.forEach((e=>e())),s())})),(e=>{const t=we();return Ze(t,"client/onTokenExpired","tokenExpired",e)})((e=>{Rc(e),jc(),ku.forEach((e=>e()))})),xc(Hc),Pc(Hc),vc(),(()=>{const e=dl();return e.established(),lc((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=wl();return e.startSyncReadReceipt(),lc((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bc();return e.startResolver(),lc((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await Su();ku.push(e)}return!0},Iu=()=>{let e,t=!1;const n=we();n.log("initiating access token renewal");const r=async r=>{const{userId:s,displayName:i}=He(),o={userId:s,displayName:i,authToken:r,deviceId:await Ga()};"tokenExpired"===n.sessionState&&n.sessionHandler?await _u(o,n.sessionHandler):await Lc(o),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(Iu())}),b)}}},Au=3e5,Ru=e=>{const t=setInterval((()=>{const t=we();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-Au)(r))return et("tokenExpired","tokenExpired"),void Ye((()=>e.sessionWillRenewAccessToken(Iu())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),s=Date.parse(n),i=Date.now();return i>s+.8*(r-s-Au)&&i<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(Iu())}),b);return()=>clearInterval(t)},Lu=e=>{const t=we();return Ze(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Du=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Ou=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},xu=e=>{const t=we();return Ze(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Pu=e=>{const t=we();return Ze(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},Mu=e=>{const t=we();return Ze(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Fu=e=>{const t=we();return Ze(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,s;Ya(t);const i=Se(["message","collection"]),{contentMarkers:o,feedMarkers:a}=t;if(i&&(null==i?void 0:i.length)>0&&(null==a?void 0:a.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)===a[0].feedId}));if(e.length>0&&(null==o?void 0:o.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=>Ce(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const r=["messageMarker","get",he("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=Ce(r))||void 0===t?void 0:t.data;if(!s)return;const i=o[0].feedId===s.feedId,a=o[0].readCount>s.readCount,l=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(i){const e=Object.assign(Object.assign({},s),{readCount:a?o[0].readCount:s.readCount,deliveredCount:l?o[0].deliveredCount:s.deliveredCount});Te(r,e)}}))}}e(t.contentMarkers[0])}))};function Uu(e){return"object"==typeof e&&null!==e}const Nu=e=>{if(!Uu(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)},Bu=e=>{if(!Uu(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};function ju(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(!ju(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=>ju(e[n],t[n])))}const $u=(e,t,n,r,s,i)=>{const{forceDispatch:o,callbackDataSelector:a,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=we();let u;c||console.log("For using Live Object feature you need to enable Cache!");let d=!1;const h=[],f=e=>{const{data:n}=e,r=Xa(e,["data"]);l&&!l(n,u)||t(Object.assign({data:a(n)},r)),u=Nu(n)};return h.push(...s.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(u&&!r&&ju(u,t)||f({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=ae(r,e,!0);ce(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{-5===s?(f({data:t,origin:r,loading:!1,error:new me(m,800800,"error")}),d=!0,h.forEach((e=>e()))):d||f({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var qu=Object.freeze({__proto__:null,getActiveClient:we,getActiveUser:He,setActiveUser:Ve,createClient:(e,t=At.SG,{debugSession:n="amity",apiEndpoint:r}={})=>{var s,i;const o=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!It,n=Tt(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);o("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const a=null!==(s=null==r?void 0:r.http)&&void 0!==s?s:Lt("http",t),l=null!==(i=null==r?void 0:r.mqtt)&&void 0!==i?i:Lt("mqtt",t),c=pr(a),u=(e=>{const t=Ro(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(a),d=Wa(l),f=Je(),p={version:`${h}`,apiKey:e,log:o,cache:{data:{}},http:c,ws:u,mqtt:d,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Ru,sessionHandler:undefined,hasPermission:Tc,validateUrls:kc,validateTexts:_c,getFeedSettings:Ic,getSocialSettings:Sc,getMessagePreviewSetting:Ec,use:()=>Ee(p),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:Tu};try{const t=we();if(t.apiKey===e)return t;Ee(p)}catch(e){Ee(p)}return p},login:_u,logout:jc,secureLogout:async()=>{const e=we(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await jc()},isConnected:()=>{var e,t;const n=we();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)&&n.ws.connected)},getFeedSettings:Ic,renewal:Iu,markerSync:au,enableUnreadCount:lu,onConnectionError:Kc,onClientDisconnected:e=>Kc((({code:t})=>{800211===t&&e()})),onClientBanned:Gc,onSessionStateChange:lc,getTotalUnreadCount:e=>{const{_id:t}=He();if(!t)throw new ge("The _id has not been defined in ActiveUser",8e5,"error");return $u(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await Hl();return{data:e,cachedAt:t}}),[Pu],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=He();if(!t)throw new ge("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=we();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,o=!1;const a=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;i=r?Nu(r):r,e({data:r?Object.assign(Object.assign({},r),{hasMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(xu((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),o={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};ju(i,o)||a({loading:!1,data:o})})(e)))),(()=>{const e=ae(Hl);ce(e,(({error:e,data:t,loading:n,origin:r,cachedAt:i})=>{!function(e){return null!=e&&null!=e}(t)?a({loading:n,data:void 0,origin:r,error:e}):(-5===i?(a({data:t,origin:r,loading:!1,error:new me(m,800800,"error")}),o=!0,s.forEach((e=>e()))):o||a({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>mu,setMarkerSyncEvents:yu,pushMarkerSyncEvent:vu,markerSyncTrigger:bu,startMarkerSync:Su,startUnreadSync:async()=>{await gu(),vu("start syncing"),lu(),hu=!1,cu=!0,wu()},stopUnreadSync:Cu,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Cu()),getMarkerSyncConsistentMode:Tu});const Ku=async e=>{const t=we();let n={};if(e){const{token:t,limit:r}=e;n={limit:r,token:t}}t.log("user/queryBlockedUsers");const{data:r}=await t.http.get("/api/v4/me/user-blocks",{params:n}),{paging:s}=r,i=Xa(r,["paging"]),{users:o}=i,a=t.cache&&Date.now();if(t.cache){Ya(i,{cachedAt:a});Te(["blockedUsers","query",n],{users:o.map(he("user")),paging:s})}const{next:l,previous:c,total:u}=s,d=te(l);return{data:o,prevPage:te(c),nextPage:d,total:u,cachedAt:a}};Ku.locally=(e={})=>{var t,n,r;const s=we();if(s.log("user/queryBlockedUsers.locally"),!s.cache)return;let i={};if(e){const{token:t,limit:n}=e;i={token:t,limit:n}}const o=["blockedUsers","query",i],{data:a,cachedAt:l}=null!==(t=Ce(o))&&void 0!==t?t:{},c=null!==(n=null==a?void 0:a.users.map((e=>Ce(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],u=te(null==a?void 0:a.paging.next),d=te(null==a?void 0:a.paging.previous);return c.length>0&&c.length===(null===(r=null==a?void 0:a.users)||void 0===r?void 0:r.length)?{data:c,nextPage:u,prevPage:d,total:null==a?void 0:a.paging.total,cachedAt:l}:void 0};const Gu=(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getBlockedUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=null!=o?o:f,{policy:l=p}=null!=n?n:{},c=[],u=["blockedUsers","collection",{}],d=(e=!1)=>{var n,r;const s=null===(n=Ce(u))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!e&&i.length>0&&!(null==s?void 0:s.params.page))return;const o=ae(Ku,{limit:a,token:Z(e||null==s?void 0:s.params.page,"afterbeforeraw")});ce(o,(({data:e,loading:n,error:r,nextPage:s,total:o})=>{const a={loading:n,error:r,params:{page:s,total:o},data:i};e&&(a.data=[...new Set([...i,...e.map(he("user"))])]),Te(u,a),(e=>{var n,r;const s=null!==(n=e.data.map((e=>Ce(["user","get",e]))).filter(Boolean).map((({data:e})=>Cl.user(e))))&&void 0!==n?n:[];t({onNextPage:d,data:s,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})})(a)}),le(l,E))};return c.push((()=>{})),d(!0),()=>{r(`getCategories(tmpid: ${i}) > dispose`),c.forEach((e=>e())),Ie(u)}},Hu=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{var r,s;if(n.cache){Ya(e);[...null!==(r=Se(["followers","query"]))&&void 0!==r?r:[],...null!==(s=Se(["followings","query"]))&&void 0!==s?s:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>_e(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},Vu=e=>Hu("follow.created",e),zu=e=>Hu("follow.unfollowed",e),Wu=e=>Hu("follow.followerDeleted",e),Yu=e=>Hu("follow.requested",e),Qu=e=>Hu("follow.requestCanceled",e),Xu=e=>Hu("follow.accepted",e),Ju=e=>Hu("follow.requestDeclined",e),Zu=async e=>{var t,n;const r=we();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(),o="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&&Te(["followInfo","get",e],o,{cachedAt:i}),{data:o,cachedAt:i}};Zu.locally=e=>{const t=we();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Ce(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ed=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([Zu(t.from),Zu(t.to)]);e(n),e(r)},n=[Hu("follow.created",t),Hu("follow.requested",t),Hu("follow.accepted",t),Hu("follow.unfollowed",t),Hu("follow.requestCanceled",t),Hu("follow.requestDeclined",t),Hu("follow.followerDeleted",t)];return()=>{n.forEach((e=>e()))}},td=async(e,t)=>{const n=we();n.log(`follow/queryF${e.substring(1)}`,t);const{userId:r,page:s}=t,i=Xa(t,["userId","page"]),{data:o}=await n.http.get(n.userId===r?`/api/v4/me/${e}`:`/api/v4/users/${r}/${e}`,{params:Object.assign(Object.assign({},i),{token:Z(s,"afterbeforeraw")})}),{paging:a}=o,l=Xa(o,["paging"]),{follows:c}=l,u=n.cache&&Date.now();if(n.cache){Ya(l,{cachedAt:u});const t=["follow","query",Object.assign(Object.assign({},i),{userId:r,options:Object.assign({},s),type:e})];Te(t,{follows:c.map(he("follow")),paging:a})}const d=te(a.next);return{data:c,cachedAt:u,prevPage:te(a.previous),nextPage:d}};td.locally=(e,t)=>{var n,r;const s=we();if(s.log(`follow/queryF${e.substring(1)}.locally`,t),!s.cache)return;const{page:i}=t,o=Xa(t,["page"]),a=["follow","query",Object.assign(Object.assign({},o),{options:Object.assign({},i),type:e})],{data:l,cachedAt:c}=null!==(n=Ce(a))&&void 0!==n?n:{};if(!(null==l?void 0:l.follows.length))return;const u=l.follows.map((e=>Ce(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),d=te(null==l?void 0:l.paging.previous),h=te(null==l?void 0:l.paging.next);return u.length===(null===(r=null==l?void 0:l.follows)||void 0===r?void 0:r.length)?{data:u,cachedAt:c,prevPage:d,nextPage:h}:void 0};const nd=async e=>td("followers",e);nd.locally=e=>td.locally("followers",e);const rd=async e=>td("following",e);rd.locally=e=>td.locally("following",e);var sd=Object.freeze({__proto__:null,blockUser:async e=>{const t=we();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,o={follows:s};return t.cache&&(Ya(o,{cachedAt:r}),_e(["followInfo","get",e],i[0],{cachedAt:r})),et("follow.unfollowed",o),n},unBlockUser:async e=>{const t=we();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,o={follows:s};return t.cache&&(Ya(o,{cachedAt:r}),_e(["followInfo","get",e],i[0],{cachedAt:r})),et("follow.created",o),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),Gu(e,t,n)),follow:async e=>{const t=we();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();return t.cache&&Ya(n,{cachedAt:r}),et("accepted"===n.follows[0].status?"follow.created":"follow.requested",n),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=we();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Ya(n),et("follow.unfollowed",n),!0},acceptFollower:async e=>{const t=we();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Ya(n),et("follow.accepted",n),!0},acceptMyFollower:async e=>{const t=we();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Ya(n),et("follow.accepted",n),!0},declineFollower:async e=>{const t=we();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Ya(n),et("follow.requestDeclined",n),!0},declineMyFollower:async e=>{const t=we();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Ya(n),et("follow.requestDeclined",n),!0},onUserFollowed:Vu,onUserUnfollowed:zu,onFollowerDeleted:Wu,onFollowerRequested:Yu,onFollowRequestCanceled:Qu,onFollowRequestAccepted:Xu,onFollowRequestDeclined:Ju,onFollowInfoUpdated:ed,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeFollowInfo(tmpid: ${s}) > listen`);const i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},o=[];return o.push(ed((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&i(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),ce(ae(Zu,e),(e=>(e.data||e.error)&&i(e,"onFetch")),le(n)),()=>{r(`observeFollowInfo(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const s=[],i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(s=t[n])||void 0===s||s.call(t,e)};return s.push(Yu((e=>i(e,"onRequested"))),Xu((e=>i(e,"onAccepted"))),Ju((e=>i(e,"onDeclined"))),Qu((e=>i(e,"onCanceled"))),Vu((e=>i(e,"onFollowed"))),zu((e=>i(e,"onUnfollowed"))),Wu((e=>i(e,"onDeleted")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const s=[],i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(s=t[n])||void 0===s||s.call(t,e)};return s.push(Yu((e=>i(e,"onRequested"))),Xu((e=>i(e,"onAccepted"))),Ju((e=>i(e,"onDeclined"))),Qu((e=>i(e,"onCanceled"))),Vu((e=>i(e,"onFollowed"))),zu((e=>i(e,"onUnfollowed"))),Wu((e=>i(e,"onDeleted")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getFollowers(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"follower"}],h=n=>{var r,s;let i=null!==(r=n.data.map((e=>Ce(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const s=null===(r=Ce(d))||void 0===r?void 0:r.data;e.userId===n.to&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==he("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([he("follow")(n),...s.data])]),Te(d,s),h(s))},m=(e=!1)=>{var t,n,r,s;const i=null===(t=Ce(d))||void 0===t?void 0:t.data,o=null!==(n=null==i?void 0:i.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null===(r=null==i?void 0:i.params)||void 0===r?void 0:r.page))return;const u=ae(nd,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));ce(u,(({data:e,error:t,loading:n,nextPage:r})=>{const s={loading:n,error:t,params:{page:r},data:o};e&&(s.data=[...new Set([...o,...e.map(he("follow"))])]),Te(d,s),h(s)}),le(c))};return u.push(Yu(g("onRequested")),Xu(g("onAccepted")),Ju(g("onDeclined")),Qu(g("onCanceled")),Vu(g("onFollowed")),zu(g("onUnfollowed")),Wu(g("onDeleted"))),m(!0),()=>{r(`getFollowers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getFollowings(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"following"}],h=n=>{var r,s;let i=null!==(r=n.data.map((e=>Ce(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const s=null===(r=Ce(d))||void 0===r?void 0:r.data;e.userId===n.from&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==he("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([he("follow")(n),...s.data])]),Te(d,s),h(s))},m=(e=!1)=>{var t,n,r,s;const i=null===(t=Ce(d))||void 0===t?void 0:t.data,o=null!==(n=null==i?void 0:i.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null===(r=null==i?void 0:i.params)||void 0===r?void 0:r.page))return;const u=ae(rd,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));ce(u,(({data:e,error:t,loading:n,nextPage:r})=>{const s={loading:n,error:t,params:{page:r},data:o};e&&(s.data=[...new Set([...o,...e.map(he("follow"))])]),Te(d,s),h(s)}),le(c))};return u.push(Yu(g("onRequested")),Xu(g("onAccepted")),Ju(g("onDeclined")),Qu(g("onCanceled")),Vu(g("onFollowed")),zu(g("onUnfollowed")),Wu(g("onDeleted"))),m(!0),()=>{r(`getFollowings(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowInfo:(e,t)=>$u(e,t,"userId",Zu,[ed],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=He();return $u(t,e,"userId",Zu,[ed],{forceDispatch:!0})}});const id=async e=>{const t=we();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=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),et("user.fetched",r),{data:r.users.map((e=>Cl.user(e))),cachedAt:s}};id.locally=e=>{var t;const n=we();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Ce(["user","get",e]))).filter(Boolean),s=r.map((({data:e})=>Cl.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 od=e=>Mc("user.updated",e),ad=e=>Mc("user.flagged",e),ld=e=>Mc("user.unflagged",e),cd=e=>Mc("user.flagCleared",e),ud=e=>Mc("user.fetched",e),dd=async e=>{const t=we();let n;t.log("user/getUser",e),dc("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&Qa("user",e),t}const r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{users:s}=n;return et("user.fetched",n),{data:s.find((t=>t.userId===e)),cachedAt:r}};dd.locally=e=>{const t=we();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ce(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const hd=async(e={})=>{const t=we();t.log("user/queryUsers",e);const{page:n,limit:r=10,displayName:s,filter:i="all",sortBy:o="displayName"}=e,a=Xa(e,["page","limit","displayName","filter","sortBy"]),{data:l}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:s,filter:i,sortBy:o,options:n?{token:n}:{limit:r}})}),{paging:c}=l,u=Xa(l,["paging"]),{users:d}=u,h=t.cache&&Date.now();if(t.cache){Ya(u,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:r,token:n}})];Te(t,{users:d.map(he("user")),paging:c})}return et("user.fetched",l),{data:d,cachedAt:h,paging:c}};hd.locally=(e={})=>{var t,n,r;const s=we();if(s.log("user/queryUsers.locally",e),!s.cache)return;const{limit:i=10,page:o}=null!=e?e:{},a=["user","query",Object.assign(Object.assign({},e),{options:{limit:i,token:o}})],{data:l,cachedAt:c}=null!==(t=Ce(a))&&void 0!==t?t:{},u=null!==(n=null==l?void 0:l.users.map((e=>Ce(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];return u.length>0&&u.length===(null===(r=null==l?void 0:l.users)||void 0===r?void 0:r.length)?{data:u,cachedAt:c,paging:null==l?void 0:l.paging}:void 0};const fd=(e,t)=>{let n=Re(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":n=n.sort(Ne);break;case"lastCreated":n=n.sort(je);break;default:n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Fe)}return n},pd=(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`liveUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["user","collection",qa()],h=(n,r=!1)=>{var s,i;const o=null!==(s=n.data.map((e=>Ce(["user","get",e]))).filter(Boolean).map((({data:e})=>Cl.user(e))))&&void 0!==s?s:[];t({onNextPage:y,data:r?fd(o,e):o,hasNextPage:!!(null===(i=n.params)||void 0===i?void 0:i.page),loading:n.loading,error:n.error})},m=e=>e=>{var t;const n=null===(t=Ce(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Te(d,n),h(n,!0))},y=(e=!1)=>{var t,n;const r=null===(t=Ce(d))||void 0===t?void 0:t.data,s=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==r?void 0:r.params.page))return;const i=e?{limit:l}:{page:null==r?void 0:r.params.page},o=ae(hd,Object.assign(Object.assign({},a),i));ce(o,(({data:t,error:n,loading:r,paging:i})=>{const o={loading:r,error:n,params:{page:null==i?void 0:i.next},data:s};t&&(o.data=e?t.map(he("user")):[...new Set([...s,...t.map(he("user"))])]),Te(d,o),h(o)}),le(c))};return u.push(od(m()),Fc(m()),ad(m()),ld(m()),cd(m())),y(!0),()=>{r(`liveUsers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},gd=async e=>{const t=we();let n;t.log("user/getUser",e),dc("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&Qa("user",e),t}const r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{users:s}=n;return et("user.fetched",n),{data:Cl.user(s.find((t=>t.userId===e))),cachedAt:r}};gd.locally=e=>{const t=we();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ce(["user","get",e]);return n?{data:Cl.user(n.data),cachedAt:n.cachedAt}:void 0};const md=async({viewId:e,viewedType:t,limit:n,token:r})=>{const s=we(),i={};r?i.token=r:i.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,a=await s.http.get(o,{params:i});return Ya(a.data),a.data};var yd=Object.freeze({__proto__:null,Relationship:sd,getUserByIds:id,updateUser:async(e,t)=>{const n=we();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=n.cache&&Date.now();n.cache&&Ya(r,{cachedAt:s});const{users:i}=r;return et("user.updated",r),{data:i.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=we();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Ya(n),et("user.flagged",n),!!n},unflagUser:async e=>{const t=we();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Ya(n),et("user.unflagged",n),!!n},isUserFlaggedByMe:async e=>{const t=we();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:od,onUserDeleted:Fc,onUserFlagged:ad,onUserUnflagged:ld,onUserFlagCleared:cd,getUser:(e,t)=>$u(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?Cl.user(e.data):e.data}))),"userId",dd,[ud,od,Fc,ad,ld,cd]),getUsers:pd,observeUser:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const s=(n,r)=>{var s,i,o;if((null===(s=n.data)||void 0===s?void 0:s.userId)!==e)return;const a=Object.assign(Object.assign({},n),{data:Cl.user(n.data)});if(t instanceof Function)return t(a);"onFetch"!==r&&(null===(i=t.onEvent)||void 0===i||i.call(t,r,a)),null===(o=t[r])||void 0===o||o.call(t,a)},i=[];return i.push(od((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Fc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),ad((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),ld((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),cd((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),ce(ae(gd,e),(e=>e.data&&s(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:Gu,searchUserByDisplayName:(e,t,n)=>pd(Object.assign(Object.assign({},e),{filter:"all"}),t,n),getViewedUsers:(e,t)=>{const{log:n,cache:r}=we(),s=["postViewedUsers","collection",{postId:e.postId}];r||console.log(g);const i=Date.now();n(`getViewedUsers(tmpid: ${i}) > listen`);const{limit:o,postId:a}=e,l=(e=!1)=>{var n,r,i;const c=null===(n=Ce(s))||void 0===n?void 0:n.data,u=null!==(r=null==c?void 0:c.data)&&void 0!==r?r:[];if(!e&&u.length>0&&!(null==c?void 0:c.params.page))return;const d=ae(md,{viewId:a,viewedType:"post",limit:o||10,token:e||null===(i=null==c?void 0:c.params.page)||void 0===i?void 0:i.next});ce(d,(e=>{var n,r,i,o,a;let c=null!==(i=null===(r=null===(n=Ce(s))||void 0===n?void 0:n.data)||void 0===r?void 0:r.data)&&void 0!==i?i:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(a=e.data)||void 0===a?void 0:a.paging},data:c||[]};Te(s,u),(e=>{var n,r;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Ce(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:l,data:s,hasNextPage:!!(null===(r=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(u)}),le(p,E))};return l(!0),()=>{n(`getViewedUsers(tmpid: ${i}) > dispose`),Ie(s)}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:s}=we(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(g);const o=Date.now();r(`getReachUsers(tmpid: ${o}) > listen`);const{limit:a,viewId:l,viewedType:c}=e;return n=(e=!1)=>{var r,s,o;const u=null===(r=Ce(i))||void 0===r?void 0:r.data,d=null!==(s=null==u?void 0:u.data)&&void 0!==s?s:[];if(!e&&d.length>0&&!(null==u?void 0:u.params.page))return;const h=ae(md,{viewId:l,viewedType:c,limit:a||10,token:e||null===(o=null==u?void 0:u.params.page)||void 0===o?void 0:o.next});ce(h,(e=>{var r,s,o,a,l;let c=null!==(o=null===(s=null===(r=Ce(i))||void 0===r?void 0:r.data)||void 0===s?void 0:s.data)&&void 0!==o?o:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};Te(i,u),(e=>{var r,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>Ce(["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})})(u)}),le(p,E))},n(!0),()=>{r(`getReachUsers(tmpid: ${o}) > dispose`),Ie(i)}}});const vd=async e=>{const t=we();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Ya({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};vd.locally=e=>{const t=we();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Ce(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const bd=async(e,t,n)=>{const r=we();r.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.http.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),a=r.cache&&Date.now();return r.cache&&Ya({files:o},{cachedAt:a}),{data:o,cachedAt:a}},wd=async(e,t)=>{const n=we();n.log("file/uploadImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ya({files:i},{cachedAt:o}),{data:i,cachedAt:o}};var Ed=Object.freeze({__proto__:null,getFile:vd,uploadFile:async(e,t)=>{const n=we();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ya({files:i},{cachedAt:o}),{data:i,cachedAt:o}},deleteFile:async e=>{const t=we();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Ie(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:bd,uploadImage:wd,createImage:async(e,t)=>{const n=we();n.log("file/createImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ya({files:i},{cachedAt:o}),{data:i,cachedAt:o}},createFile:async(e,t)=>{const n=we();n.log("file/createFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),o=n.cache&&Date.now();return n.cache&&Ya({files:i},{cachedAt:o}),{data:i,cachedAt:o}},createVideo:async(e,t,n)=>{const r=we();r.log("file/createVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await r.http.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),a=r.cache&&Date.now();return r.cache&&Ya({files:o},{cachedAt:a}),{data:o,cachedAt:a}},observeFile:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return ce(ae(vd,e),(n=>n.data&&((n,r)=>{var s,i,o;if((null===(s=n.data)||void 0===s?void 0:s.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(i=t.onEvent)||void 0===i||i.call(t,r,n)),null===(o=t[r])||void 0===o||o.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const Sd=async e=>{const t=we();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r,limit:s=10,queryToken:i,displayName:o,sortBy:a}=n,l=Xa(n,["page","limit","queryToken","displayName","sortBy"]),c=i?{token:i}:s?{limit:s}:r?{token:Z(r,"skiplimit")}:void 0,{data:u}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},l),{keyword:o,sortBy:a,options:c})}),{paging:d}=u,h=Xa(u,["paging"]),{roles:f}=h,p=t.cache&&Date.now();t.cache&&Ya(h,{cachedAt:p});const g=ee(d.next);return{data:f,cachedAt:p,prevPage:ee(d.previous),nextPage:g,paging:d}};Sd.locally=e=>{we().log("role/queryRoles.locally",e)};const Cd=async e=>{const t=we();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Ya({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Cd.locally=e=>{const t=we();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Ce(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Td=(e,t)=>{"message"===e?et("local.message.updated",{messages:[t]}):"post"===e?et("post.updated",{posts:[t]}):"comment"===e?et("comment.updated",{comments:[t]}):"story"===e&&et("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},kd=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),dc("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Zl(t)}catch(t){throw _(null==t?void 0:t.code)&&Qa("message",e),t}const s=n.cache&&Date.now();n.cache&&Ya(r,{cachedAt:s});const{messages:i}=r;return et("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};kd.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ce(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _d=async e=>{const t=we();let n;t.log("post/getPost",e),dc("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&Qa("post",e),t}const r=Za(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{posts:i}=r,o=i.find((t=>t.postId===e));return{data:Cl.post(o),cachedAt:s}};_d.locally=e=>{const t=we();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ce(["post","get",e]);return n?{data:Cl.post(n.data),cachedAt:n.cachedAt}:void 0};const Id=async e=>{const t=we();let n;t.log("comment/getComment",e),dc("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&Qa("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{comments:s}=n;return{data:Cl.comment(s.find((t=>t.commentId===e))),cachedAt:r}};function Ad(e,t){return e.map((e=>{const n=t.some((t=>function(e,t){const{userId:n}=He();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}))}Id.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ce(["comment","get",e]);return n?{data:Cl.comment(n.data),cachedAt:n.cachedAt}:void 0};const Rd=(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=Ce([i,"get",s]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Ld=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Dd=(e,t,n,r=[])=>{const s=e.split(".")[1];let i=r;if(we().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},Od=(e,t)=>{const n=e.split(".")[0],r=Rd(t,n),s=Dd(e,t.reactor.userId,t.reactor.reactionName,r);return Ld(t,`${n}s`,s)},xd=(e,t)=>{var n,r;const s=e.split(".")[0];let i=Rd(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(i=Dd(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 o=Ld(t,"stories",i);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const a=Ad(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:a})},Pd=async(e,t,n)=>{const r=we();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),r.cache){const n=Ce([e,"get",t]);(null==n?void 0:n.data)&&Te([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};Pd.optimistically=(e,t,n)=>{var r,s,i,o,a;const l=we();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=Ce([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 u=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 _e([e,"get",t],u,{cachedAt:-5}),Td(e,u),null!==(a=null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==a&&a};const Md=async(e,t,n)=>{const r=we();if(r.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),r.cache){const n=Ce([e,"get",t]);(null==n?void 0:n.data)&&Te([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};Md.optimistically=(e,t,n)=>{var r,s,i,o,a;const l=we();if(l.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!l.cache)return;const c=Ce([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 u=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(i=c.data.reactions[n])&&void 0!==i?i:0)-1)})});return _e([e,"get",t],u,{cachedAt:-5}),Td(e,u),null!==(a=!(null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(n)))&&void 0!==a&&a};const Fd=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{var s;if(n.cache){const{communities:i}=r,o=Xa(r,["communities"]),a=Za(o,"communityUsers");if(Ya(a),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&et("community.updated",{communities:i,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=r.posts[0];try{dc("post",e)}catch(e){return}return s!==n.userId&&Qa("post",e),t(r.posts[0])}const l=Ce(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=Se(["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)===l.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})=>_e(e,t,{cachedAt:-1})))}t(l.data)}else t(r.posts[0])}))},Ud=e=>Fd("post.created",e),Nd=e=>Fd("post.updated",e),Bd=e=>Fd("post.deleted",e),jd=e=>Fd("post.approved",e),$d=e=>Fd("post.declined",e),qd=e=>Fd("post.flagged",e),Kd=e=>Fd("post.unflagged",e),Gd=e=>{const t=we();return Ze(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Xa(Od("post.addReaction",n),["reactor"]);Ya(t);const r=Ce(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Hd=e=>{const t=we();return Ze(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Xa(Od("post.removeReaction",n),["reactor"]);Ya(t);const r=Ce(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Vd=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Rd(e,"comment");return Ld(e,"comments",t)})(r):r;Ya(n);const{comments:i}=n;if(i.length>0){const n=Ce(["comment","get",i[0].commentId]);if(["comment.created"].includes(e)){if(i[0].parentId){const e=Ce(["comment","get",i[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(i[0].commentId)||Te(["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])]})))}const e=null===(s=Se(["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})=>_e(e,t,{cachedAt:-1})))}t(Cl.comment(n.data))}}else t(Cl.comment(r.comments[0]))}))},zd=e=>Vd("comment.created",e),Wd=e=>Vd("comment.updated",e),Yd=e=>Vd("comment.deleted",e),Qd=e=>Vd("comment.flagged",e),Xd=e=>Vd("comment.unflagged",e),Jd=e=>{const t=we();return Ze(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Xa(Od("comment.addReaction",n),["reactor"]);Ya(t);const r=Ce(["comment","get",n.comments[0].commentId]);e(Cl.comment(r.data))}else e(Cl.comment(n.comments[0]))}))},Zd=e=>{const t=we();return Ze(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Xa(Od("comment.removeReaction",n),["reactor"]);Ya(t);const r=Ce(["comment","get",n.comments[0].commentId]);e(Cl.comment(r.data))}else e(Cl.comment(n.comments[0]))}))},eh=(e,t,n)=>{const r=we(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Ze(r,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Zl(e);t.reactions[0]&&(Ya(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ze(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Xa(e,["reactor"]);Ya(n),Ya({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Ze(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Xa(e,["reactions"]);Ya(n),Ya({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Ze(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Xa(e,["reactor"]);Ya(n),Ya({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},th=(e,t,n)=>{const r=we(),s=(r,s,i)=>{r===e&&s===t&&n(i)};if("message"===e){return Ze(r,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Zl(e);t.reactions[0]&&(Ya(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ze(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Xa(e,["reactor"]);Ya(n),Ya({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Ze(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Xa(e,["reactions"]);Ya(n),Ya({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Ze(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Xa(e,["reactor"]);Ya(n),Ya({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},nh=async e=>{we().log("reaction/queryReactor",e);const t=await(async e=>{const t=we();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,s=Xa(n,["page"]),{data:i}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:Z(r,"afterbeforeraw")}})}),{paging:o}=i,a=Xa(i,["paging"]),{reactions:l}=a;Ya(Object.assign(Object.assign({},a),{reactions:l})),Ya(Object.assign(Object.assign({},a),{reactors:l[0].reactors}));const c=te(o.next);return{data:l,prevPage:te(o.previous),nextPage:c}})(e),{data:n}=t,r=Xa(t,["data"]);return Object.assign(Object.assign({},r),{data:n[0].reactors})};var rh=Object.freeze({__proto__:null,addReaction:Pd,removeReaction:Md,onReactionAdded:(e,t,n)=>{const r=r=>{he(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Zl(e),s=Ce(["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;Ya(n),i&&r(n.messages[0])};return Ze(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Gd(r):Jd(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{he(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Zl(e),s=Ce(["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;Ya(n),i&&r(n.messages[0])};return Ze(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Hd(r):Zd(r)},onReactorAdded:eh,onReactorRemoved:th,getReactions:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`liveReactions(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],h=e=>{var n,r;const s=null!==(n=e.data.map((e=>Ce(["reactor","get",e]))).filter(Boolean).map((({data:e})=>Cl.reactor(e))))&&void 0!==n?n:[];t({onNextPage:m,data:s,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},g=e=>t=>{var n;const r=null===(n=Ce(d))||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))),Te(d,r),h(r))},m=(e=!1)=>{var t,n,r,s;const i=null===(t=Ce(d))||void 0===t?void 0:t.data,o=null!==(n=null==i?void 0:i.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null===(r=null==i?void 0:i.params)||void 0===r?void 0:r.page))return;const u=ae(nh,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));ce(u,(({data:e,error:t,loading:n,nextPage:r})=>{const s={loading:n,error:t,params:{page:r},data:o};e&&(s.data=[...new Set([...o,...e.map(he("reactor"))])]),Te(d,s),h(s)}),le(c))};return u.push(eh(a.referenceType,a.referenceId,g("onAdded")),th(a.referenceType,a.referenceId,g("onRemoved"))),m(!0),()=>{r(`liveReactions(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}}),sh={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const ih=async e=>{const t=we();let n;t.log("channel/getChannel",e),dc("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await jl(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Kl(r)}catch(t){throw _(null==t?void 0:t.code)&&Qa("channel",e),t}const r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:r}};ih.locally=e=>{var t;const n=we();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Se(["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 oh=(e,t,n)=>r=>e((e=>{var s;if(!e)return e;const i=[n,"get",`${e[t]}`],o=null===(s=Ce(i))||void 0===s?void 0:s.data;return o?r(o):void 0})),ah=e=>{const t=we(),n=[Ze(t,"onMessageUpdated","message.updated",(async t=>{const n=await Zl(t);Ya(n),e(n.messages[0])})),Ze(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},lh=e=>{const t=we(),n=[Ze(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Zl(t);Ya(n),e(n.messages[0])})),Ze(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},ch=e=>{const t=we(),n=[Ze(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await sc(t);Ya(n),e(n.messageFeeds[0])})),Ze(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function uh(e,t){Te(["channel","get",e.channelId],Object.assign(Rl(e),t))}const dh=e=>{const t=we();return Ze(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},hh=async(e,t=!1)=>{const n=we(),r=await hc(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:pe(r.data.updatedAt)});return t?setTimeout((()=>{Qa("subChannel",e)}),0):_e(["subChannel","get",e],s),et("local.message-feed.deleted",{messageFeeds:[s]}),s},fh=e=>Ze(we(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),ph=async e=>{const t=we();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await Zl(n),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{messages:i}=r;return et("local.message.fetched",{messages:i}),{data:i.map((e=>Cl.message(e))),cachedAt:s}};ph.locally=e=>{var t;const n=we();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>Ce(["message","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,cachedAt:i.cachedAt}};const gh=()=>`LOCAL_${qa()}`;let mh;const yh=async e=>{const t=we();t.log("message/createMessage",e);const n=e.referenceId||mh||gh();mh=void 0;const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ec(e)),{referenceId:n})),s=await Zl(r),{messages:i}=s,o=t.cache&&Date.now();return t.cache&&(Ie(["message","get",n]),Ya(s,{cachedAt:o})),et("local.message.created",{messages:i}),{data:Cl.message(i[0]),cachedAt:o}};yh.optimistically=e=>{var t,n,{referenceId:r}=e,s=Xa(e,["referenceId"]);const i=we();if(!i.cache)return;mh=r||gh();const o=Object.assign({messageId:mh,uniqueId:mh},s);i.log("message/createMessage.optimistically",o);const a=Ce(["subChannel","get",s.subChannelId]);if(a&&(_e(["subChannel","get",s.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=Ce(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&_e(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const l=(new Date).toISOString(),c=Object.assign({creatorId:i.userId,creatorPrivateId:He()._id,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:l,updatedAt:l},o);return Te(["message","get",c.messageId],c,{cachedAt:-5}),et("local.message.created",{messages:[c]}),{cachedAt:-5,data:Cl.message(c)}};const vh=async(e,t)=>{const n=we();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)}`,ec(t)),s=await Zl(r),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{messages:o}=s;return et("local.message.updated",{messages:o}),{data:Cl.message(o.find((t=>t.messageId===e))),cachedAt:i}};vh.optimistically=(e,t)=>{const n=we();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Ce(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return _e(["message","get",e],s,{cachedAt:-1}),et("local.message.updated",{messages:[s]}),{data:Cl.message(s),cachedAt:-1}};const bh=async(e,t)=>{const n=we();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ec(t)),s=await Zl(r),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{messages:o}=s;return et("local.message.updated",{messages:o}),{data:Cl.message(o.find((t=>t.messageId===e))),cachedAt:i}};bh.optimistically=(e,t)=>{const n=we();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Ce(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return _e(["message","get",e],s,{cachedAt:-1}),et("local.message.updated",{messages:[s]}),{data:Cl.message(s),cachedAt:-1}};const wh=async e=>{const t=we();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await kd(e);return et("local.message.deleted",{messages:[n.data]}),Cl.message(n.data)};wh.optimistically=e=>{we().log("message/deleteMessage.optimistically",e);const t=Ce(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return _e(["message","get",e],n,{cachedAt:-1}),et("local.message.deleted",{messages:[n]}),{data:Cl.message(n),cachedAt:-1}};const Eh=async e=>{const t=we();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await kd(e);return et("local.message.deleted",{messages:[n.data]}),Cl.message(n.data)};Eh.optimistically=e=>{we().log("message/softDeleteMessage.optimistically",e);const t=Ce(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return _e(["message","get",e],n,{cachedAt:-1}),et("local.message.deleted",{messages:[n]}),{data:Cl.message(n),cachedAt:-1}};const Sh=async e=>{const t=we();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,s=Xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Z(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=Xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){Ya(Object.assign(Object.assign({},c),{userFeedMarkers:nl(l)}),{cachedAt:u});const e=["read-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];Te(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await id(a));return{data:d,cachedAt:u,prevPage:ee(o.previous),nextPage:ee(o.next)}};Sh.locally=e=>{var t;const n=we();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,s=Xa(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:o,cachedAt:a}=null!==(t=Ce(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ce(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:ee(null==o?void 0:o.paging.previous),nextPage:ee(null==o?void 0:o.paging.next)}};const Ch=async e=>{const t=we();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,s=Xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Z(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=Xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){Ya(Object.assign(Object.assign({},c),{userFeedMarkers:nl(l)}),{cachedAt:u});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];Te(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await id(a));return{data:d,cachedAt:u,prevPage:ee(o.previous),nextPage:ee(o.next)}};Ch.locally=e=>{var t;const n=we();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,s=Xa(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:o,cachedAt:a}=null!==(t=Ce(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ce(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:ee(null==o?void 0:o.paging.previous),nextPage:ee(null==o?void 0:o.paging.next)}};const Th=e=>{const t=we();return Ze(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Zl(t);Ya(n),e(n.messages[0])}))},kh=e=>{const t=we();return Ze(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Zl(t);Ya(n),e(n.messages[0])}))},_h=e=>{const t=we();return Ze(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Zl(t);Ya(n),e(n.messages[0])}))},Ih=e=>{const t=we();return Ze(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Zl(t,"message.reactionAdded");Ya(n),e(n.messages[0])}))},Ah=e=>{const t=we();return Ze(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Zl(t,"message.reactionRemoved");Ya(n),e(n.messages[0])}))},Rh=e=>{const t=we();return Ze(t,"message/onMessageFetched","local.message.fetched",(t=>{Ya(t),e(t.messages[0])}))};var Lh={exports:{}};!function(e,t){e.exports=function e(t,n,r){function s(o,a){if(!n[o]){if(!t[o]){if(!a&&Lo)return Lo(o);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}a=n[o]={exports:{}},t[o][0].call(a.exports,(function(e){return s(t[o][1][e]||e)}),a,a.exports,e,t,n,r)}return n[o].exports}for(var i=Lo,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(e,t,n){(function(r,s,i,o,a,l,c,u,d){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,o=Object.prototype.toString.call(t),a=/\[object (.*)\]/i.exec(o);if(a=(a=a?a[1]:"unknown:["+o+"]").toLowerCase(),0<=(o=n.indexOf(t)))return this.dispatch("[CIRCULAR:"+o+"]");if(n.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return r("buffer:"),r(t);if("object"===a||"function"===a||"asyncfunction"===a)return o=Object.keys(t),e.unorderedObjects&&(o=o.sort()),!1===e.respectType||y(t)||o.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(o=o.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+o.length+":"),s=this,o.forEach((function(n){s.dispatch(n),r(":"),e.excludeValues||s.dispatch(t[n]),r(",")}));if(!this["_"+a]){if(e.ignoreUnknown)return r("["+a+"]");throw new Error('Unknown object type "'+a+'"')}this["_"+a](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 o=[];return s=t.map((function(t){var r=new b,s=n.slice();return v(e,r,s).dispatch(t),o=o.concat(s.slice(n.length)),r.read().toString()})),n=n.concat(o),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,o,a,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),o="A".charCodeAt(0),a="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===n||e===a?62:e===r||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<o+26?e-o: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)),o=0<s?e.length-4:e.length,a=0;function l(e){i[a++]=e}for(n=0;n<o;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,o="";function a(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)o+=a((s=n=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+a(s>>12&63)+a(s>>6&63)+a(63&s);switch(i){case 1:o=(o+=a((n=e[e.length-1])>>2))+a(n<<4&63)+"==";break;case 2:o=(o=(o+=a((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+a(n>>4&63))+a(n<<2&63)+"="}return o}}(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,o,a,l,c,u){var d=e("base64-js"),h=e("ieee754");function s(e,t,n){if(!(this instanceof s))return new s(e,t,n);var r,i,o,a,l=typeof e;if("base64"===t&&"string"==l)for(e=(a=e).trim?a.trim():a.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==l)r=L(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=L(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(D(a=e)||s.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length)for(o=0;o<r;o++)s.isBuffer(e)?i[o]=e.readUInt8(o):i[o]=e[o];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!n)for(o=0;o<r;o++)i[o]=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 E(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 S(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"),U(t,65535)),!((s=e.length)<=n))for(var i=0,o=Math.min(s-n,2);i<o;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function C(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"),U(t,4294967295)),!((s=e.length)<=n))for(var i=0,o=Math.min(s-n,4);i<o;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||S(e,0<=t?t:65535+t+1,n,r,s)}function k(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||C(e,0<=t?t:4294967295+t+1,n,r,s)}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+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 I(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=x(e).length;break;case"ascii":case"binary":case"raw":n=e.length;break;case"base64":n=P(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(D(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 o=e[i];o.copy(n,r),r+=o.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,o,a,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 o=0;o<r;o++){var a=parseInt(t.substr(2*o,2),16);j(!isNaN(a),"Invalid hex string"),e[n+o]=a}return s._charsWritten=2*o,o}(this,e,t,n);break;case"utf8":case"utf-8":o=this,a=t,l=n,i=s._charsWritten=M(x(e),o,a,l);break;case"ascii":case"binary":i=f(this,e,t,n);break;case"base64":o=this,a=t,l=n,i=s._charsWritten=M(P(e),o,a,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,o,a=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):a.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+=O(e[i]);return s}(a,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+=F(s)+String.fromCharCode(e[i]),s=""):s+="%"+e[i].toString(16);return r+F(s)}(a,t,n);break;case"ascii":case"binary":r=g(a,t,n);break;case"base64":s=a,o=n,r=0===(i=t)&&o===s.length?d.fromByteArray(s):d.fromByteArray(s.slice(i,o));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}(a,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 o=0;o<i;o++)e[o+t]=this[o+n];else e._set(this.subarray(n,n+i),t)}},s.prototype.slice=function(e,t){var n=this.length;if(e=R(e,n,0),t=R(t,n,n),s._useTypedArrays)return s._augment(this.subarray(e,t));for(var r=t-e,i=new s(r,void 0,!0),o=0;o<r;o++)i[o]=this[o+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 E(this,e,!0,t)},s.prototype.readDoubleBE=function(e,t){return E(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"),U(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,n){S(this,e,t,!0,n)},s.prototype.writeUInt16BE=function(e,t,n){S(this,e,t,!1,n)},s.prototype.writeUInt32LE=function(e,t,n){C(this,e,t,!0,n)},s.prototype.writeUInt32BE=function(e,t,n){C(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){k(this,e,t,!0,n)},s.prototype.writeInt32BE=function(e,t,n){k(this,e,t,!1,n)},s.prototype.writeFloatLE=function(e,t,n){_(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){_(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){I(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){I(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]=O(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 A=s.prototype;function R(e,t,n){return"number"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function L(e){return(e=~~Math.ceil(+e))<0?0:e}function D(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function O(e){return e<16?"0"+e.toString(16):e.toString(16)}function x(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("%")),o=0;o<i.length;o++)t.push(parseInt(i[o],16))}return t}function P(e){return d.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 F(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function U(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=A.get,e.set=A.set,e.write=A.write,e.toString=A.toString,e.toLocaleString=A.toString,e.toJSON=A.toJSON,e.copy=A.copy,e.slice=A.slice,e.readUInt8=A.readUInt8,e.readUInt16LE=A.readUInt16LE,e.readUInt16BE=A.readUInt16BE,e.readUInt32LE=A.readUInt32LE,e.readUInt32BE=A.readUInt32BE,e.readInt8=A.readInt8,e.readInt16LE=A.readInt16LE,e.readInt16BE=A.readInt16BE,e.readInt32LE=A.readInt32LE,e.readInt32BE=A.readInt32BE,e.readFloatLE=A.readFloatLE,e.readFloatBE=A.readFloatBE,e.readDoubleLE=A.readDoubleLE,e.readDoubleBE=A.readDoubleBE,e.writeUInt8=A.writeUInt8,e.writeUInt16LE=A.writeUInt16LE,e.writeUInt16BE=A.writeUInt16BE,e.writeUInt32LE=A.writeUInt32LE,e.writeUInt32BE=A.writeUInt32BE,e.writeInt8=A.writeInt8,e.writeInt16LE=A.writeInt16LE,e.writeInt16BE=A.writeInt16BE,e.writeInt32LE=A.writeInt32LE,e.writeInt32BE=A.writeInt32BE,e.writeFloatLE=A.writeFloatLE,e.writeFloatBE=A.writeFloatBE,e.writeDoubleLE=A.writeDoubleLE,e.writeDoubleBE=A.writeDoubleBE,e.fill=A.fill,e.inspect=A.inspect,e.toArrayBuffer=A.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,o,a,l,c,u){s=e("buffer").Buffer;var d=4,h=new s(d);h.fill(0),t.exports={hash:function(e,t,n,r){for(var i=t(function(e,t){e.length%d!=0&&(n=e.length+(d-e.length%d),e=s.concat([e,h],n));for(var n,r=[],i=t?e.readInt32BE:e.readInt32LE,o=0;o<e.length;o+=d)r.push(i.call(e,o));return r}(e=s.isBuffer(e)?e:new s(e),r),8*e.length),o=(t=r,new s(n)),a=t?o.writeInt32BE:o.writeInt32LE,l=0;l<i.length;l++)a.call(o,i[l],4*l,!0);return o}}}).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,o,a,l,c,u){s=e("buffer").Buffer;var d=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:d,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),o=0;o<g;o++)r[o]=54^t[o],i[o]=92^t[o];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"],E=function(e){n[e]=function(){v("sorry,",e,"is not implemented yet")}};for(b in w)E(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,o,a,l,c,u){var d=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,o=0;o<e.length;o+=16){var a=n,l=r,c=s,u=i;n=p(n,r,s,i,e[o+0],7,-680876936),i=p(i,n,r,s,e[o+1],12,-389564586),s=p(s,i,n,r,e[o+2],17,606105819),r=p(r,s,i,n,e[o+3],22,-1044525330),n=p(n,r,s,i,e[o+4],7,-176418897),i=p(i,n,r,s,e[o+5],12,1200080426),s=p(s,i,n,r,e[o+6],17,-1473231341),r=p(r,s,i,n,e[o+7],22,-45705983),n=p(n,r,s,i,e[o+8],7,1770035416),i=p(i,n,r,s,e[o+9],12,-1958414417),s=p(s,i,n,r,e[o+10],17,-42063),r=p(r,s,i,n,e[o+11],22,-1990404162),n=p(n,r,s,i,e[o+12],7,1804603682),i=p(i,n,r,s,e[o+13],12,-40341101),s=p(s,i,n,r,e[o+14],17,-1502002290),n=g(n,r=p(r,s,i,n,e[o+15],22,1236535329),s,i,e[o+1],5,-165796510),i=g(i,n,r,s,e[o+6],9,-1069501632),s=g(s,i,n,r,e[o+11],14,643717713),r=g(r,s,i,n,e[o+0],20,-373897302),n=g(n,r,s,i,e[o+5],5,-701558691),i=g(i,n,r,s,e[o+10],9,38016083),s=g(s,i,n,r,e[o+15],14,-660478335),r=g(r,s,i,n,e[o+4],20,-405537848),n=g(n,r,s,i,e[o+9],5,568446438),i=g(i,n,r,s,e[o+14],9,-1019803690),s=g(s,i,n,r,e[o+3],14,-187363961),r=g(r,s,i,n,e[o+8],20,1163531501),n=g(n,r,s,i,e[o+13],5,-1444681467),i=g(i,n,r,s,e[o+2],9,-51403784),s=g(s,i,n,r,e[o+7],14,1735328473),n=m(n,r=g(r,s,i,n,e[o+12],20,-1926607734),s,i,e[o+5],4,-378558),i=m(i,n,r,s,e[o+8],11,-2022574463),s=m(s,i,n,r,e[o+11],16,1839030562),r=m(r,s,i,n,e[o+14],23,-35309556),n=m(n,r,s,i,e[o+1],4,-1530992060),i=m(i,n,r,s,e[o+4],11,1272893353),s=m(s,i,n,r,e[o+7],16,-155497632),r=m(r,s,i,n,e[o+10],23,-1094730640),n=m(n,r,s,i,e[o+13],4,681279174),i=m(i,n,r,s,e[o+0],11,-358537222),s=m(s,i,n,r,e[o+3],16,-722521979),r=m(r,s,i,n,e[o+6],23,76029189),n=m(n,r,s,i,e[o+9],4,-640364487),i=m(i,n,r,s,e[o+12],11,-421815835),s=m(s,i,n,r,e[o+15],16,530742520),n=y(n,r=m(r,s,i,n,e[o+2],23,-995338651),s,i,e[o+0],6,-198630844),i=y(i,n,r,s,e[o+7],10,1126891415),s=y(s,i,n,r,e[o+14],15,-1416354905),r=y(r,s,i,n,e[o+5],21,-57434055),n=y(n,r,s,i,e[o+12],6,1700485571),i=y(i,n,r,s,e[o+3],10,-1894986606),s=y(s,i,n,r,e[o+10],15,-1051523),r=y(r,s,i,n,e[o+1],21,-2054922799),n=y(n,r,s,i,e[o+8],6,1873313359),i=y(i,n,r,s,e[o+15],10,-30611744),s=y(s,i,n,r,e[o+6],15,-1560198380),r=y(r,s,i,n,e[o+13],21,1309151649),n=y(n,r,s,i,e[o+4],6,-145523070),i=y(i,n,r,s,e[o+11],10,-1120210379),s=y(s,i,n,r,e[o+2],15,718787259),r=y(r,s,i,n,e[o+9],21,-343485551),n=v(n,a),r=v(r,l),s=v(s,c),i=v(i,u)}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,o){return f(t&n|~t&r,e,t,s,i,o)}function g(e,t,n,r,s,i,o){return f(t&r|n&~r,e,t,s,i,o)}function m(e,t,n,r,s,i,o){return f(t^n^r,e,t,s,i,o)}function y(e,t,n,r,s,i,o){return f(n^(t|~r),e,t,s,i,o)}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 d.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,o,a,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,o,a,l,c,u){var d=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),o=1732584193,a=-271733879,l=-1732584194,c=271733878,u=-1009589776,d=0;d<e.length;d+=16){for(var h=o,g=a,m=l,y=c,v=u,b=0;b<80;b++){i[b]=b<16?e[d+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(o,5),(w=a,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(u,i[b]),(n=b)<20?1518500249:n<40?1859775393:n<60?-1894007588:-899497514));u=c,c=l,l=p(a,30),a=o,o=w}o=f(o,h),a=f(a,g),l=f(l,m),c=f(c,y),u=f(u,v)}return Array(o,a,l,c,u)}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 d.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,o,a,l,c,u){function d(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 o,a,l=0;l<e.length;l+=16){for(var c=s[0],u=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]:d(d(d((a=i[w-2],p(a,17)^p(a,19)^g(a,10)),i[w-7]),(a=i[w-15],p(a,7)^p(a,18)^g(a,3))),i[w-16]),n=d(d(d(d(b,p(a=m,6)^p(a,11)^p(a,25)),m&y^~m&v),r[w]),i[w]),o=d(p(o=c,2)^p(o,13)^p(o,22),c&u^c&h^u&h),b=v,v=y,y=m,m=d(f,n),f=h,h=u,u=c,c=d(n,o);s[0]=d(c,s[0]),s[1]=d(u,s[1]),s[2]=d(h,s[2]),s[3]=d(f,s[3]),s[4]=d(m,s[4]),s[5]=d(y,s[5]),s[6]=d(v,s[6]),s[7]=d(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,o,a,l,c){n.read=function(e,t,n,r,s){var i,o,a=8*s-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?s-1:0,h=n?-1:1;for(s=e[t+d],d+=h,i=s&(1<<-u)-1,s>>=-u,u+=a;0<u;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=r;0<u;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return o?NaN:1/0*(s?-1:1);o+=Math.pow(2,r),i-=c}return(s?-1:1)*o*Math.pow(2,i-r)},n.write=function(e,t,n,r,s,i){var o,a,l=8*i-s-1,c=(1<<l)-1,u=c>>1,d=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?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(r=Math.pow(2,-o))<1&&(o--,r*=2),2<=(t+=1<=o+u?d/r:d*Math.pow(2,1-u))*r&&(o++,r/=2),c<=o+u?(a=0,o=c):1<=o+u?(a=(t*r-1)*Math.pow(2,s),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));8<=s;e[n+h]=255&a,h+=f,a/=256,s-=8);for(o=o<<s|a,l+=s;0<l;e[n+h]=255&o,h+=f,o/=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,o,a,l,c){var u,d,h;function f(){}(e=t.exports={}).nextTick=(d="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,d?function(e){return window.setImmediate(e)}:h?(u=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<u.length&&u.shift()())}),!0),function(e){u.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)}(Lh);var Dh=Lh.exports;class Oh{constructor(e){const{http:t}=we();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 o=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=o.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(s=o.paging)||void 0===s?void 0:s.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class xh extends Oh{async getRequest(e,t){const n=tc(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 Ph{constructor(e,t){this.query=e,this.cacheKey=t}}class Mh extends Ph{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=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.messages.map(he("message")),query:this.query});else{const n=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,i=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...i,...e.messages.map(he("message"))])]:[...new Set([...e.messages.map(he("message")),...i])]}))}}reactor(e){return t=>{var n,r,s,i,o;if("onCreate"===e){const e=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;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.dataType&&this.query.dataType!==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.excludeTags&&(null===(s=this.query.excludeTags)||void 0===s?void 0:s.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===(i=this.query.includingTags)||void 0===i?void 0:i.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.tags&&!(null===(o=this.query.tags)||void 0===o?void 0:o.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([t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,t.messageId])]),Te(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Fh{constructor(e){const{http:t}=we();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Uh{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 Fh?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 Fh)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 Fh)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(Nu).map(Bu);return!ju(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}class Nh extends Uh{constructor(e,t){const n=Dh(e),r=["message","collection",n];super(new xh(e),n,r,t),this.query=e,this.queryStreamController=new Mh(this.query,this.cacheKey,this.notifyChange.bind(this),Zl,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ru,action:"onCreate"},{fn:lh,action:"onDelete"},{fn:ah,action:"onUpdate"},{fn:Th,action:"onFlagged"},{fn:kh,action:"onUnflagged"},{fn:_h,action:"onFlagCleared"},{fn:Ih,action:"onReactionAdded"},{fn:Ah,action:"onReactionRemoved"},{fn:oh(Mu,"contentId","message"),action:"onUpdate"},{fn:oh(Fu,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["message","get",e]))).filter(Boolean).map((({data:e})=>e)).map((e=>Cl.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>!this.query.tags||this.query.tags.find((t=>!!e.tags&&e.tags.includes(t))))),t=t.filter((e=>!this.query.excludeTags||(this.query.excludeTags||[]).find((t=>!e.tags||!e.tags.includes(t))))),this.query.includeDeleted||(t=Ae(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}}const Bh=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),dc("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Zl(t)}catch(t){throw _(null==t?void 0:t.code)&&Qa("message",e),t}const s=n.cache&&Date.now();n.cache&&Ya(r,{cachedAt:s});const{messages:i}=r;return et("local.message.fetched",{messages:i}),{data:Cl.message(i.find((t=>t.messageId===e))),cachedAt:s}};Bh.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ce(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var jh=Object.freeze({__proto__:null,getMessageByIds:ph,createMessage:yh,updateMessage:vh,editMessage:bh,deleteMessage:wh,softDeleteMessage:Eh,markAsDelivered:async(e,t)=>{const n=we();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:o}=r,a=Xa(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=n.cache&&Date.now();return n.cache&&Ya(Object.assign({userMarkers:s,userEntityMarkers:tl(i),userFeedMarkers:nl(o)},a),{cachedAt:l}),!0},getReadUsers:Sh,getDeliveredUsers:Ch,flagMessage:async e=>{const t=we();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Zl(n);Ya(e)}return et("message.flagged",n),!!n},unflagMessage:async e=>{const t=we();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Zl(n);Ya(e)}return et("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=we();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:ru,onMessageCreatedLocal:su,onMessageUpdated:ah,onMessageDeleted:lh,onMessageFlagged:Th,onMessageUnflagged:kh,onMessageFlagCleared:_h,onMessageReactionAdded:Ih,onMessageReactionRemoved:Ah,onMessageFetched:Rh,getMessage:(e,t)=>$u(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?Cl.message(e.data):n}))}),"messageId",kd,[Rh,ah,lh,Th,kh,_h,Ih,Ah,oh(Mu,"contentId","message"),oh(Fu,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getMessages(tmpid: ${i}) > listen`);const o=new Nh(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ie(l)})),()=>{r(`getMessages(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeMessage(tmpid: ${s}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const i=(n,r)=>{var s,i,o;if((null===(s=n.data)||void 0===s?void 0:s.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(i=t.onEvent)||void 0===i||i.call(t,r,n)),null===(o=t[r])||void 0===o||o.call(t,n)}},o=[];return o.push(ah((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onUpdate"))),lh((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onDelete"))),oh(Mu,"contentId","message")((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onUpdate"))),oh(Fu,"contentId","message")((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==n&&ce(ae(Bh,e),(e=>e.data&&i(e,"onFetch")),le(n)),()=>{r(`observeMessages(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const s=[],i=(n,r)=>{var s,i,o;if((null===(s=n.data)||void 0===s?void 0:s.subChannelId)===e){if(t instanceof Function)return t(n);null===(i=t.onEvent)||void 0===i||i.call(t,r,n),null===(o=t[r])||void 0===o||o.call(t,n)}};return s.push(ru((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onCreate"))),su((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onCreate"))),ah((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onUpdate"))),lh((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onDelete"))),oh(Mu,"contentId","message")((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onCreate"))),oh(Fu,"contentId","message")((e=>i({data:Cl.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Xl,prepareMessagePayload:Zl,convertParams:ec,convertQueryParams:tc});const $h=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class qh extends Oh{async getRequest(e,t){var n;const{limit:r=f}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Xa(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Xa(e,["limit"])))&&void 0!==n?n:{},{channelId:i,includeDeleted:o}=s,a=Xa(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({},a),{isDeleted:Vl(o),options:l})});return c}}class Kh extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(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=Ce(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])]),Te(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Gh extends Uh{constructor(e,t){const n=Dh(e),r=["subChannel","collection",n];super(new qh(e),n,r,t),this.query=e,this.queryStreamController=new Kh(this.query,this.cacheKey,this.notifyChange.bind(this),sc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:fh,action:"onCreate"},{fn:iu,action:"onCreate"},{fn:ou,action:"onDelete"},{fn:e=>ch((async t=>{var n;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(!r||!r.data.includes(t.subChannelId))return;const s=we();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=_l(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Te(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>ru((async t=>{var n,r;const s=Ce(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(!i||!i.data.includes(t.subChannelId))return;await(async e=>{const t=we();"no-message-preview"!==await t.getMessagePreviewSetting(!1)&&Dl(e)})(t);const o=null===(r=Ce(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;o&&(Ll(t.subChannelId,o,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>su((async t=>{var n,r;const s=Ce(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(!i||!i.data.includes(t.subChannelId))return;const o=we();if("no-message-preview"===await o.getMessagePreviewSetting(!1))return;Dl(t);const a=null===(r=Ce(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;a&&(Ll(t.subChannelId,a,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>Ou((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Ce(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:oh(Du,"feedId","subChannel"),action:"onUpdate"},{fn:oh((e=>ah((async t=>{var n;const r=we();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const s=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(Ol(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:oh((e=>lh((async t=>{var n;const r=we(),s=await r.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const i=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;i&&i.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await hc(t.subChannelId):await Ol(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:oh($h,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Il))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ae(e,"isDeleted",!1)),t.sort(Ke),t}}const Hh={},Vh=async e=>{const t=await(async e=>{const t=hc.locally(e);if(t)return t.data.channelId;const{data:n}=await hc(e);return n.channelId})(e),n=lt({channelId:t,subChannelId:e});Hh[e]=pt(n)};var zh=Object.freeze({__proto__:null,getSubChannelByIds:wc,createSubChannel:async e=>{const t=we();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await sc(n.data),s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),et("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=we();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await sc(r.data),i=n.cache&&Date.now();return n.cache&&Ya(s,{cachedAt:i}),et("message-feed.updated",r.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:hh,hardDeleteSubChannel:async e=>{we().log("channel/hardDeleteSubChannel",e);return await hh(e,!0)},softDeleteSubChannel:async e=>{we().log("channel/softDeleteSubChannel",e);return await hh(e,!1)},onSubChannelCreated:iu,onSubChannelUpdated:ch,onSubChannelDeleted:ou,getSubChannel:(e,t)=>{const n=we();let r;return $u(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Il(e.data)}),s=Xa(n,["origin"]);return ju(r,s)?void 0:(r=s,t(n))}),"subChannelId",hc,[fh,t=>ch((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(xl(r),r.subChannelId===e&&t(r))})),ou,oh(Du,"feedId","subChannel"),t=>Ou((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(r=Ce(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&t(s)})),oh((t=>ru((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dl(t),t.subChannelId!==e)return;const s=null===(r=Ce(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&Ll(t.subChannelId,s,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),oh((t=>su((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dl(t),t.subChannelId!==e)return;const s=null===(r=Ce(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&Ll(t.subChannelId,s,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),oh((t=>ah((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(Ol(r),t(r))}))),"subChannelId","subChannel"),oh((t=>lh((async r=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&r.subChannelId===e&&("message-preview-include-deleted"===s&&await Ol(r),"message-preview-not-include-deleted"===s&&await hc(r.subChannelId),t(r))}))),"subChannelId","subChannel"),oh($h,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:s}=we(),i=Date.now();r(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(g);const o=new Gh(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ie(l)})),()=>{r(`getSubChannels(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},markReadEngineOnLoginHandler:vc,startReading:async e=>{gc[e]=!0,0===pc.length&&(pc.length>0||pc.push(uc((()=>{mc()}))),bc(e));try{return await(async e=>{const t=we();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:o}=n,a=tl(r),l=nl(s),c=t.cache&&Date.now();return t.cache&&Ya({userEntityMarkers:a,userFeedMarkers:l,feedMarkers:i,userMarkers:o},{cachedAt:c}),et("local.feedMarker.fetched",{feedMarkers:i}),et("local.channelMarker.fetched",{userEntityMarkers:a}),et("local.subChannelMarker.fetched",{userFeedMarkers:l}),et("local.userMarker.fetched",{userMarkers:o}),!0})(e)}catch(t){return gc[e]=!1,!1}},stopReading:e=>(gc[e]=!1,pc.forEach((e=>e())),pc=[],(async e=>{const t=we();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:i,userMarkers:o}=n,a=tl(r),l=nl(s),c=t.cache&&Date.now();return t.cache&&Ya({userEntityMarkers:a,userFeedMarkers:l,feedMarkers:i,userMarkers:o},{cachedAt:c}),et("local.feedMarker.fetched",{feedMarkers:i}),et("local.channelMarker.fetched",{userEntityMarkers:a}),et("local.subChannelMarker.fetched",{userFeedMarkers:l}),et("local.userMarker.fetched",{userMarkers:o}),!0})(e)),startMessageReceiptSync:async e=>(await Vh(e),!0),stopMessageReceiptSync:e=>(Hh[e]&&Hh[e](),!0)});const Wh=e=>{const t=we();return Ze(t,"channelMarker/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Yh extends Oh{async getRequest(e,t){const{limit:n=f,displayName:r,membership:s}=e,i=Xa(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:r,filter:s,options:o})});return a}}class Qh extends Fh{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Xh extends Ph{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=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.channels.map(he("channel"))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(he("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Qh)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolve"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(he("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Te(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Jh=(e,t)=>{const n=we();if(n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()){Bc().resolve(e.channelId,"userMessageFeedMarker")}else t(e)},Zh=e=>{const t=we();return Ze(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class ef extends Uh{constructor(e,t){const n=Dh(e),r=["channel","collection",n],s=ef.getPaginationController(e);super(s,n,r,t),this.query=e,this.queryStreamController=new Xh(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=we();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Kl(e)}catch(e){console.error("Error while preparing unread count info",e)}return jl(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;let o=null!==(s=i.data.map((e=>Ce(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Tl).map(Cl.channel))&&void 0!==s?s:[];this.paginationController instanceof Yh&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Yh?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof Yh&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;switch(n=Ae(n,"isDeleted",this.query.isDeleted),n=Ae(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=De(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ne);break;case"lastCreated":n=n.sort(je);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Fe);break;default:n=n.sort(Ke)}return n}shouldAbort(e){var t,n;const r=null===(t=Ce(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 we().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Qh(e):new Yh(e)}getSubscriptions(){const e=[{fn:oh((e=>ru((t=>{var n;const r=null===(n=Ce(["channel","get",t.channelId]))||void 0===n?void 0:n.data;if(r)uh(r,{lastActivity:t.createdAt}),e(t);else{Bc().resolve(t.channelId,"channel")}}))),"messageId","channel"),action:"onUpdate"},{fn:oh((e=>su((t=>{var n;const r=null===(n=Ce(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(uh(r,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:xc,action:"onDelete"},{fn:zc,action:"onUpdate"},{fn:Qc,action:"onMute"},{fn:e=>Wc((t=>{Jh(t,e)})),action:"onJoin"},{fn:e=>Yc(((t,n)=>{var r,s;const{userId:i}=we();if("member"===this.query.membership&&i===n.userId){const e=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;Te(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:Xc,action:"onMemberAdded"},{fn:Jc,action:"onMemberRemoved"},{fn:oh(Lu,"entityId","channel"),action:"onUpdate"},{fn:oh(dh,"entityId","channel"),action:"onUpdate"},{fn:oh((e=>ru((async t=>{var n;if("no-message-preview"===await ef.getMessagePreviewSetting())return;if(Dl(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ce(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(uh(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:oh((e=>su((async t=>{var n;if("no-message-preview"===await ef.getMessagePreviewSetting())return;if(Dl(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ce(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(uh(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:oh((e=>ah((async t=>{"no-message-preview"!==await ef.getMessagePreviewSetting()&&(Ol(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:oh((e=>lh((async t=>{const n=await ef.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ol(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await ih(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:oh((e=>ou((async t=>{var n;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=rl(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await ih(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:oh((e=>ch((async t=>{var n;if("no-message-preview"===await ef.getMessagePreviewSetting())return;(null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data)&&(await xl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:oh(iu,"channelId","channel"),action:"onUpdate"},{fn:Zh,action:"onResolve"},{fn:e=>(e=>{const t=we();return Ze(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=[...new Set(t.feedMarkers.map((e=>e.entityId)))].map((e=>{var t;return null===(t=Ce(["channel","get",e]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"onResolve"},{fn:oh(Wh,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Oh?[...e,{fn:e=>Vc((t=>{Jh(t,e)})),action:"onCreate"}]:e}}class tf extends Oh{async getRequest(e,t){const{limit:n=f}=e,r=Xa(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(r.channelId)}/users`,{params:Object.assign(Object.assign({},r),{options:s})});return i}}class nf extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>he("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>he("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=he("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==s)):r.data.includes(s)||(r.data=[s,...r.data]),Te(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rf extends Uh{constructor(e,t){const n=Dh(e),r=["channelUsers","collection",n];super(new tf(e),n,r,t),this.query=e,this.queryStreamController=new nf(this.query,this.cacheKey,this.notifyChange.bind(this),jl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:Wc,action:"onJoin"},{fn:Yc,action:"onLeft"},{fn:Xc,action:"onMemberAdded"},{fn:Jc,action:"onMemberRemoved"},{fn:Pc,action:"onChannelMemberBanned"},{fn:Zc,action:"onChannelMemberUnbanned"},{fn:eu,action:"onChannelMemberRoleAdded"},{fn:tu,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(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))}))),this.query.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),t=Me(t,this.query.search));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?je:Ne),t}}const sf=(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const o=new rf(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ie(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}};var of=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();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=>et("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await jl(r);n.cache&&Ya(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=we();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=>et("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await jl(r);n.cache&&Ya(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership)))),t.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),n=Me(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?je:Ne),n},getMembers:sf,searchMembers:(e,t,n)=>sf(e,t)});var af=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=we();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 jl(s);r.cache&&Ya(i),et("local.channel-moderator.role-added",i);const{channelUsers:o}=i;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=we();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 jl(s);r.cache&&Ya(i),et("local.channel-moderator.role-removed",i);const{channelUsers:o}=i;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=we();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 jl(r),{channelUsers:i}=s,o=n.cache&&Date.now();return n.cache&&Ya(s,{cachedAt:o}),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=we();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 jl(r),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{channelUsers:o}=s;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:i}},muteMembers:async(e,t,n=-1)=>{const r=we();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:s}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:i}=s;return i},unmuteMembers:async(e,t)=>{const n=we();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=r;return s}}),lf=Object.freeze({__proto__:null,Membership:of,Moderation:af,getChannelByIds:Gl,createChannel:async e=>{const t=we();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=Xa(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 jl(n.data),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{channels:i}=r;return{data:i[0],cachedAt:s}},updateChannel:async(e,t)=>{const n=we();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await jl(r),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{channels:o}=s;return{data:o.find((t=>t.channelId===e)),cachedAt:i}},deleteChannel:async e=>{const t=we();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await ih(e)).data},joinChannel:async e=>{const t=we();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await jl(n);t.cache&&Ya(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=we();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await jl(n);t.cache&&Ya(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=we();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new ge("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=we();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},markAsRead:Sl,onChannelCreated:Vc,onChannelUpdated:zc,onChannelDeleted:xc,onChannelJoined:Wc,onChannelLeft:Yc,onChannelMuted:Qc,onChannelMemberAdded:Xc,onChannelMemberRemoved:Jc,onChannelMemberBanned:Pc,onChannelMemberUnbanned:Zc,onChannelMemberRoleAdded:eu,onChannelMemberRoleRemoved:tu,observeChannel:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const s=(n,r)=>{var s,i,o;if((null===(s=n.data)||void 0===s?void 0:s.channelId)===e){if(t instanceof Function)return t(Object.assign(Object.assign({},n),{data:Cl.channel(n.data)}));"onFetch"!==r&&(null===(i=t.onEvent)||void 0===i||i.call(t,r,Object.assign(Object.assign({},n),{data:Cl.channel(n.data)}))),null===(o=t[r])||void 0===o||o.call(t,Object.assign(Object.assign({},n),{data:Cl.channel(n.data)}))}},i=[];return i.push(zc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),xc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Wc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Yc((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Qc((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),Xc((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),Jc((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),oh(Lu,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),ce(ae(ih,e),(e=>e.data&&s(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=we(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],s=(t,n)=>{var r,s;if(e instanceof Function)return e(Cl.channel(t));null===(r=e.onEvent)||void 0===r||r.call(e,n,Cl.channel(t)),null===(s=e[n])||void 0===s||s.call(e,Cl.channel(t))};return r.push(Vc((e=>s(e,"onCreate"))),zc((e=>s(e,"onUpdate"))),xc((e=>s(e,"onDelete"))),Wc((e=>s(e,"onJoin"))),Yc((e=>s(e,"onLeft"))),Qc((e=>s(e,"onMute"))),Xc((e=>s(e,"onMemberAdded"))),Jc((e=>s(e,"onMemberRemoved"))),oh(Lu,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>{const n=we();let r;return $u(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Cl.channel(Tl(e.data))}),s=Xa(n,["origin"]);return ju(r,s)?void 0:(r=s,t(n))}),"channelId",ih,[zc,xc,Wc,Yc,Xc,Jc,Pc,Zc,Qc,oh(Lu,"entityId","channel"),oh(dh,"entityId","channel"),oh((t=>ru((async r=>{await(async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dl(r),r.channelId!==e)return;const i=null===(s=Ce(["channel","get",e]))||void 0===s?void 0:s.data;i&&(uh(i,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),oh((t=>su((async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Dl(r),r.channelId!==e)return;const i=null===(s=Ce(["channel","get",e]))||void 0===s?void 0:s.data;i&&(uh(i,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),oh((t=>ah((async r=>{var s;const i=null===(s=Ce(["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 Ol(r),t(r))}))),"channelId","channel"),oh((t=>lh((async r=>{var s;const i=null===(s=Ce(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==r.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(Ie(["messagePreviewChannel","get",e]),await ih(r.channelId)):await Ol(r),t(r))}))),"channelId","channel"),oh((e=>ou((async t=>{var r,s;const{channelId:i,subChannelId:o}=t,a=null===(r=Ce(["messagePreviewChannel","get",i]))||void 0===r?void 0:r.data;if(!a||a.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await ih(i);(null===(s=Ce(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),oh((t=>ch((async r=>{var s,i;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;xl(r);const o=null===(s=Ce(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!o||o.subChannelId!==r.subChannelId)return;(null===(i=Ce(["channel","get",e]))||void 0===i?void 0:i.data)&&t(r)}))),"channelId","channel"),oh(iu,"channelId","channel"),oh(Wh,"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:s,userId:i}=we();s||console.log(g);const o=Date.now();r(`getChannels(tmpid: ${o}) > listen`);const a=new ef(e,t),l=a.startSubscription(),c=a.getCacheKey();return l.push((()=>{Ie(c)})),()=>{r(`getChannels(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Fl,isUnreadCountSupport:Ul,convertFromRaw:Nl,preUpdateChannelCache:Bl,prepareChannelPayload:jl});const cf=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Te(["communityUsers","collection",e],n)}))},uf=e=>{var t;return null!==(t=Object.keys(a).find((t=>e.needApprovalOnPostCreation===a[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===a[t].onlyAdminCanPost)))&&void 0!==t?t:l},df=e=>{if(!e)return e;const t={};return e.forEach((e=>{t[`${e.userId}#${e.communityId}`]=e})),t},hf=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Xa(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:uf({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)})),n=t.reduce(((e,{communityId:t})=>{var n;const r=null===(n=Ce(["communityUsers","collection",t]))||void 0===n?void 0:n.data;return r?Object.assign(Object.assign({},df(r)),e):e}),df(e.communityUsers)),r=Ja(Object.values(n)),s=Ad(t,r);return Object.assign(Object.assign({},e),{communities:s,communityUsers:r})},ff=e=>{const{postSetting:t,storySetting:n}=e,r=Xa(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?a[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},pf=async e=>{const t=we();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=hf(n),s=t.cache&&Date.now();return t.cache&&(Ya(r,{cachedAt:s}),cf(r.communities,r.communityUsers)),{data:r.communities,cachedAt:s}};pf.locally=e=>{var t;const n=we();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Ce(["community","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,cachedAt:i.cachedAt}};const gf=async e=>{const t=we();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=hf(n),s=t.cache&&Date.now();t.cache&&(Ya(r,{cachedAt:s}),cf(r.communities,r.communityUsers));const{communities:i}=r;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};gf.locally=e=>{const t=we();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Ce(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mf=async e=>{const t=we();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),s=hf(r),{communities:i}=s,o=t.cache&&Date.now();if(t.cache){Ya(s,{cachedAt:o});Te(["community","top-trending",{params:{options:{limit:n}}}],{communities:i.map(he("community"))})}return{data:i,cachedAt:o}};mf.locally=e=>{var t,n;const r=we();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:s=5}=null!=e?e:{},i=["community","top-trending",{params:{options:{limit:s}}}],{data:o,cachedAt:a}=null!==(t=Ce(i))&&void 0!==t?t:{};if(!(null==o?void 0:o.communities.length))return;const l=o.communities.map((e=>Ce(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return l.length===(null===(n=null==o?void 0:o.communities)||void 0===n?void 0:n.length)?{data:l,cachedAt:a}:void 0};const yf=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{const r=hf(e);if(n.cache){Ya(r);const e=Ce(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},vf=e=>yf("community.created",e),bf=e=>yf("community.updated",e),wf=e=>yf("community.deleted",e);function Ef(e){return null!=e}function Sf(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Cf(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"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=>!Sf(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!Sf(e,t,"ADD_COMMUNITY_USER")))}const Tf=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{const s=hf(r),{communities:i,communityUsers:o}=s,a=Ad(i,o);if(s.communities=a,n.cache){Ya(s);const n=Ce(["community","get",s.communities[0].communityId]),r=Cf(e,s).map((e=>{const t=Ce(["communityUsers","get",he("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Ef);t(n.data,r)}else t(s.communities[0],Cf(e,s))}))},kf=e=>Tf("community.userAdded",e),_f=e=>Tf("community.userRemoved",e),If=e=>Tf("community.userBanned",e),Af=e=>Tf("community.userChanged",e),Rf=e=>Tf("community.userUnbanned",e),Lf=e=>Tf("community.roleAdded",e),Df=e=>Tf("community.roleRemoved",e),Of=e=>Tf("community.joined",e),xf=e=>Tf("community.left",e);class Pf extends Oh{async getRequest(e,t){const{limit:n=f}=e,r=Xa(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:Vl(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:s})});return i}}class Mf extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.communities.map(he("community"))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(he("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ce(this.cacheKey))||void 0===t?void 0:t.data;n&&(Te(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ff,Uf;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Ff||(Ff={})),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"}(Uf||(Uf={}));class Nf extends Oh{async getRequest(e,t){const{limit:n=f}=e,r=Xa(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v3/communities/${r.communityId}/users`,{params:Object.assign(Object.assign({},r),{options:s})});return i}}class Bf extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>he("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>he("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(t,n)=>{var r;const s=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;s&&(e===Uf.OnCommunityUserRoleAdded&&"displayName"===this.query.sortBy||(n.forEach((e=>{const t=he("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?s.data=s.data.filter((e=>e!==t)):s.data.includes(t)||(s.data=[t,...s.data])})),Te(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class jf extends Uh{constructor(e,t){const n=Dh(e),r=["communityUsers","collection",n];super(new Nf(e),n,r,t),this.query=e,this.queryStreamController=new Bf(this.query,this.cacheKey,this.notifyChange.bind(this),hf),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:Of,action:Uf.OnCommunityJoined},{fn:xf,action:Uf.OnCommunityLeft},{fn:If,action:Uf.OnCommunityUserBanned},{fn:Af,action:Uf.OnCommunityUserChanged},{fn:Lf,action:Uf.OnCommunityUserRoleAdded},{fn:Df,action:Uf.OnCommunityUserRoleRemoved},{fn:Rf,action:Uf.OnCommunityUserUnbanned}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["communityUsers","get",e]))).filter(Ef).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);switch(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=Me(t,this.query.search)),this.query.sortBy){case"firstCreated":t=t.sort(Ne);break;case"displayName":t=t.sort(((e,t)=>{var n,r,s,i;return(null===(n=null==e?void 0:e.user)||void 0===n?void 0:n.displayName)&&(null===(r=null==t?void 0:t.user)||void 0===r?void 0:r.displayName)?null===(s=null==e?void 0:e.user)||void 0===s?void 0:s.displayName.localeCompare(null===(i=null==t?void 0:t.user)||void 0===i?void 0:i.displayName):0}));break;default:t=t.sort(je)}return t}}class $f extends Oh{async getRequest(e,t){const{limit:n=f}=e,r=Xa(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v3/communities/${r.communityId}/users`,{params:Object.assign(Object.assign({},r),{options:s})});return i}}class qf extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Ya(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>he("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>he("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=he("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Te(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Kf;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Kf||(Kf={}));class Gf extends Uh{constructor(e,t){const n=Dh(e),r=["communityUsers","collection",n];super(new $f(e),n,r,t),this.query=e,this.queryStreamController=new qf(this.query,this.cacheKey,this.notifyChange.bind(this),hf),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:Of,action:Kf.OnCommunityJoined},{fn:xf,action:Kf.OnCommunityLeft},{fn:If,action:Kf.OnCommunityUserBanned},{fn:Af,action:Kf.OnCommunityUserChanged},{fn:Df,action:Kf.OnCommunityUserRoleRemoved},{fn:Rf,action:Kf.OnCommunityUserUnbanned}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["communityUsers","get",e]))).filter(Ef).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=Me(t,this.query.search)),t}}var Hf=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});et("community.userAdded",r);const s=Za(r,"communityUsers");n.cache&&Ya(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=we();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});et("community.userRemoved",r);const s=Za(r,"communityUsers");n.cache&&Ya(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(n=Me(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?je:Ne),n},getMembers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const o=new jf(e,(e=>{console.log("resp",e),t(e)})),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ie(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getMembers(tmpid: ${i}) > listen`);const o=new Gf(e,(e=>{t(e)})),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ie(l)})),()=>{r(`getMembers(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},onCommunityUserAdded:kf,onCommunityUserRemoved:_f,onCommunityUserBanned:If,onCommunityUserChanged:Af,onCommunityUserUnbanned:Rf,onCommunityUserRoleAdded:Lf,onCommunityUserRoleRemoved:Df,onCommunityJoined:Of,onCommunityLeft:xf});class Vf extends Uh{constructor(e,t){const n=Dh(e),r=["community","collection",n];super(new Pf(e),n,r,t),this.query=e,this.queryStreamController=new Mf(this.query,this.cacheKey,this.notifyChange.bind(this),hf),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:wf,action:Ff.OnCommunityDeleted},{fn:bf,action:Ff.OnCommunityUpdated},{fn:Of,action:Uf.OnCommunityJoined},{fn:xf,action:Uf.OnCommunityLeft},{fn:Af,action:Uf.OnMemberCountChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;return this.query.includeDeleted&&(n=Ae(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=xe(n,this.query.membership,t)),n}}class zf extends Oh{async getRequest(e,t){const{limit:n=f}=e,r=Xa(e,["limit"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:Vl(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:s})});return i}}var Wf;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Wf||(Wf={}));class Yf extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Ya(t,{cachedAt:r}),cf(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)Te(this.cacheKey,{data:e.communities.map(he("community"))});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(he("community"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ce(this.cacheKey))||void 0===n?void 0:n.data;r&&(this.query.displayName&&e===Wf.OnCommunityCreated||(r.data=[...new Set([t.communityId,...r.data])],Te(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Qf extends Uh{constructor(e,t){const n=Dh(e),r=["community","collection",n];super(new zf(e),n,r,t),this.query=e,this.queryStreamController=new Yf(this.query,this.cacheKey,this.notifyChange.bind(this),hf),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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:vf,action:Wf.OnCommunityCreated},{fn:wf,action:Wf.OnCommunityDeleted},{fn:bf,action:Wf.OnCommunityUpdated},{fn:Of,action:Uf.OnCommunityJoined},{fn:xf,action:Uf.OnCommunityLeft},{fn:Af,action:Uf.OnMemberCountChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const i=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>Ce(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;if(this.query.includeDeleted&&(n=Ae(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=xe(n,this.query.membership,t)),!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Ne;case"lastCreated":default:return je;case"displayName":return Fe}})();n=n.sort(e)}return n}}const Xf=async e=>{const t=we();t.log("community/getTrendingCommunities",e);const{limit:n=f}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),s=hf(r),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&Ya(s,{cachedAt:o}),{data:i,cachedAt:o}},Jf=(e,t,n)=>{let r=e;r=Ae(r,"displayName",t.displayName),t.includeDeleted||(r=Ae(r,"isDeleted",!1)),t.categoryId&&(r=r.filter((e=>{var n;return null===(n=e.categoryIds)||void 0===n?void 0:n.includes(t.categoryId)}))),t.tags&&(r=r.filter((e=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))}))),t.membership&&n&&(r=xe(r,t.membership,n));const s=t.sortBy||"lastCreated";return"lastCreated"!==s&&"firstCreated"!==s||(r=r.sort("lastCreated"===s?je:Ne)),"displayName"===s&&(r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Fe)),r},Zf=async e=>{const t=we();t.log("community/getRecommendedCommunities",e);const{limit:n=f}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:n}}}),s=hf(r),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&Ya(s,{cachedAt:o}),{data:i,cachedAt:o}};var ep=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=we();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=Za(s,"communityUsers");r.cache&&Ya(i);const{communityUsers:o}=i;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=we();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=Za(s,"communityUsers");r.cache&&Ya(i);const{communityUsers:o}=i;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=we();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Za(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const n=we();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Za(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}}}),tp=Object.freeze({__proto__:null,Moderation:ep,Membership:Hf,getCommunityByIds:pf,createCommunity:async e=>{const t=we();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",ff(e));et("community.created",n);const r=hf(n),s=t.cache&&Date.now();t.cache&&(Ya(r,{cachedAt:s}),cf(r.communities,r.communityUsers));const{communities:i}=r;return{data:i[0],cachedAt:s}},updateCommunity:async(e,t)=>{const n=we();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,ff(t));et("community.updated",r);const s=hf(r),i=n.cache&&Date.now();n.cache&&(Ya(s,{cachedAt:i}),cf(s.communities,s.communityUsers));const{communities:o}=s;return{data:o.find((t=>t.communityId===e)),cachedAt:i}},deleteCommunity:async e=>{const t=we();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await gf(e);return et("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=we();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);et("community.joined",n);const r=hf(n),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=we();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);et("community.left",n);const r=hf(n),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{communityUsers:i}=r;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:mf,onCommunityCreated:vf,onCommunityUpdated:bf,onCommunityDeleted:wf,observeCommunity:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const s=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&s(t,n)},o=[];return o.push(bf((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),wf((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Of((e=>i({data:e,loading:!1,origin:"event"},"onJoin"))),xf((e=>i({data:e,loading:!1,origin:"event"},"onLeft"))),kf((e=>i({data:e,loading:!1,origin:"event"},"onUserAdded"))),_f((e=>i({data:e,loading:!1,origin:"event"},"onUserRemoved"))),If((e=>i({data:e,loading:!1,origin:"event"},"onUserBanned"))),Rf((e=>i({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),ce(ae(gf,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},searchCommunities:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`searchCommunities(tmpid: ${i}) > listen`);const o=new Vf(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>Ie(l))),()=>{r(`searchCommunities(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getCommunities(tmpid: ${i}) > listen`);const o=new Qf(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>Ie(l))),()=>{r(`getCommunities(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},getCommunity:(e,t)=>$u(e,t,"communityId",gf,[bf,wf,Of,xf,If,Rf,Af]),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=we();s||console.log(g);const o=Date.now();r(`getTrendingCommunities(tmpid: ${o}) > listen`);const{limit:a}=e,l=null!=a?a:f,{policy:c=p}=null!=n?n:{},u=[],d=["community","top-trending",{params:{options:{limit:l}}}],h=(n,r=!1)=>{var s,o;const a=null!==(s=n.data.map((e=>Ce(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:r?Jf(a,e,i):a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},m=(t=!1)=>{var n,r;const s=null===(n=Ce(d))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const o=ae(Xf,e);ce(o,(({data:t,error:n,loading:r})=>{const s={loading:r,error:n,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(he("community"))])]),Te(d,s),h(s)}),le(c,E))};return u.push(Af((e=>{var t;const n=null===(t=Ce(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Te(d,n),h(n))}))),m(!0),u.push((()=>Ie(d))),()=>{r(`getTrendingCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:s,userId:i}=we();s||console.log(g);const o=Date.now();r(`getRecommendedCommunities(tmpid: ${o}) > listen`);const{limit:a}=e;Xa(e,["limit"]);const l=null!=a?a:f,{policy:c=p}=null!=n?n:{},u=[],d=["community","recommended",{params:{options:{limit:l}}}],h=(n,r=!1)=>{var s,o;const a=null!==(s=n.data.map((e=>Ce(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:r?Jf(a,e,i):a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},m=(t=!1)=>{var n,r;const s=null===(n=Ce(d))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const o=ae(Zf,e);ce(o,(({data:t,error:n,loading:r})=>{const s={loading:r,error:n,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(he("community"))])]),Te(d,s),h(s)}),le(c,E))};return u.push(Af((e=>{var t;const n=null===(t=Ce(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Te(d,n),h(n))}))),m(!0),u.push((()=>Ie(d))),()=>{r(`getRecommendedCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}}});const np=async e=>{const t=we();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&&Ya(n,{cachedAt:r});const{categories:s}=n;return{data:Cl.category(s.find((t=>t.categoryId===e))),cachedAt:r}};np.locally=e=>{const t=we();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Ce(["category","get",e]);return n?{data:Cl.category(n.data),cachedAt:n.cachedAt}:void 0};const rp=async e=>{const t=we();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:s,includeDeleted:i}=n,o=Xa(n,["page","limit","includeDeleted"]),a=r?{token:r}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:Vl(i),options:a})}),{paging:c}=l,u=Xa(l,["paging"]),{categories:d}=u,h=t.cache&&Date.now();if(t.cache){Ya(u,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:i,options:a})];Te(e,{categories:d.map(he("category")),paging:c})}return{data:d,cachedAt:h,paging:c}};rp.locally=e=>{var t,n;const r=we();if(r.log("category/queryCategories.locally",e),!r.cache)return;const s=null!=e?e:{},{page:i,limit:o=10}=s,a=Xa(s,["page","limit"]),l=i?{token:i}:o?{limit:o}:void 0,c=["category","query",Object.assign(Object.assign({},a),{options:l})],{data:u,cachedAt:d}=null!==(t=Ce(c))&&void 0!==t?t:{};if(!(null==u?void 0:u.categories.length))return;const h=u.categories.map((e=>Ce(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=u;return h.length===(null===(n=null==u?void 0:u.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:d,paging:f}:void 0};var sp=Object.freeze({__proto__:null,getCategory:np,getCategories:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getCategories(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["category","collection",{}],h=(n=!1)=>{var r,s;const i=null===(r=Ce(d))||void 0===r?void 0:r.data,o=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!n&&o.length>0&&!(null==i?void 0:i.params.page))return;const u=ae(rp,Object.assign(Object.assign({},a),{limit:n?l:void 0,page:n||null==i?void 0:i.params.page}));ce(u,(({data:n,error:r,loading:s,paging:i})=>{const a={loading:s,error:r,params:{page:null==i?void 0:i.next},data:o};n&&(a.data=[...new Set([...o,...n.map(he("category"))])]),Te(d,a),(n=>{var r,s;let i=null!==(r=n.data.map((e=>Ce(["category","get",e]))).filter(Boolean).map((({data:e})=>Cl.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(i=Ae(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(Ne);break;case"lastCreated":i=i.sort(je);break;default:i=i.sort(Ue)}t({onNextPage:h,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(a)}),le(c))};return u.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const ip=async e=>{const t=we();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:s,queryToken:i}=n,o=Xa(n,["useCustomRanking","page","queryToken"]);r&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead'),s&&console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');const a=i?{token:i}:s?{token:Z(s,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{options:a})}),{paging:c}=l,u=Xa(l,["paging"]),d=Za(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){Ya(d);const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},s)})];Te(e,{posts:h.map(he("post")),paging:c})}const p=ee(c.next),g=ee(c.previous);return{data:h.map(Cl.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};ip.locally=e=>{var t,n;const r=we();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const s=null!=e?e:{},{page:i}=s,o=Xa(s,["page"]),a=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ce(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>Ce(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Cl.post),{paging:d}=l,h=ee(null==l?void 0:l.paging.previous),f=ee(null==l?void 0:l.paging.next);return u.length===(null===(n=null==l?void 0:l.posts)||void 0===n?void 0:n.length)?{data:u,cachedAt:c,prevPage:h,nextPage:f,paging:d}:void 0};const op=async e=>{const t=we();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r,queryToken:s,limit:i}=n,o=Xa(n,["page","queryToken","limit"]),a=s?{token:s}:r?{token:Z(r,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},o),{limit:s?void 0:i,options:a})}),{paging:c}=l,u=Xa(l,["paging"]),d=Za(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){Ya(d);const e=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Te(e,{posts:h.map(he("post")),paging:c})}const p=ee(c.next),g=ee(c.previous);return{data:h.map(Cl.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};op.locally=e=>{var t,n;const r=we();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const s=null!=e?e:{},{page:i}=s,o=Xa(s,["page"]),a=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ce(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>Ce(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=ee(null==l?void 0:l.paging.previous),h=ee(null==l?void 0:l.paging.next),{paging:f}=l;return u.length===(null===(n=null==l?void 0:l.posts)||void 0===n?void 0:n.length)?{data:u.map(Cl.post),cachedAt:c,prevPage:d,nextPage:h,paging:f}:void 0};var ap=Object.freeze({__proto__:null,queryGlobalFeed:ip,getCustomRankingGlobalFeed:op});const lp=async e=>{const t=we();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=>{_(null==t?void 0:t.code)&&Qa("post",e)})),t}const s=Za(r,"communityUsers"),i=t.cache&&Date.now();return t.cache&&Ya(s,{cachedAt:i}),{data:s.posts.map(Cl.post),cachedAt:i}};lp.locally=e=>{var t;const n=we();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Ce(["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(Cl.post),cachedAt:i.cachedAt}};const cp=async(e,t=!1)=>{var n;const r=we(),s=await _d(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await gf(s.data.targetId),t=(null!==(n=Se(["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));et("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return et("post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Qa("post",e)}),0):_e(["post","get",e],{isDeleted:!0}),Cl.post(i)},up=async e=>{const t=we();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=>{_(null==t?void 0:t.code)&&Qa("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),{data:r.comments.map((e=>Cl.comment(e))),cachedAt:s}};up.locally=e=>{var t;const n=we();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Ce(["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=>Cl.comment(e))),cachedAt:i.cachedAt}};const dp=(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})},hp=async e=>{const t=we();t.log("story/getStoryByStoryId",e);const n=Ce(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;dc("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=dp(n.data)}catch(t){throw _(null==t?void 0:t.code)&&Qa("story",e),t}const s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),{data:r.stories[0],cachedAt:s}};hp.locally=e=>{const t=we();t.log("story/getStorybyStoryId",e);const n=Ce(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;dc("story",e)}const r=t.cache&&Date.now(),s=Ce(["story","get",e]);if(s)return{data:s.data,cachedAt:r}};const fp=async(e,t=!1)=>{const n=we(),r=await Id(e);await n.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},r.data),{isDeleted:!0});if("story"===r.data.referenceType){const e=await hp(r.data.referenceId);et("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=await _d(r.data.referenceId);et("local.post.updated",{posts:[e.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}return et("local.comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?Ye((()=>Qa("comment",e))):_e(["comment","get",e],{isDeleted:!0}),s},pp=async e=>{const t=we();let n;t.log("comment/getComment",e),dc("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&Qa("comment",e),t}const r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:r}};pp.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ce(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const gp=async e=>{const t=we();t.log("comment/queryComments",e);const{limit:n=10,includeDeleted:r}=e,s=Xa(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:o}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:Vl(r),options:i})}),{paging:a}=o,l=(e=>{const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})})(Xa(o,["paging"])),{comments:c}=l,u=t.cache&&Date.now();if(t.cache){Ya(l,{cachedAt:u});const e=["comment","query",Object.assign(Object.assign({},s),{options:{limit:n}})];Te(e,{comments:c.map(he("comment")),paging:a})}return{data:c,cachedAt:u,paging:a}};var mp=Object.freeze({__proto__:null,getCommentByIds:up,createComment:async e=>{const t=we();t.log("comment/createComment",e);const{data:n}=await t.http.post("/api/v3/comments",e),{comments:r}=n;if(0===r.length)throw new Error("Comment not created");const s=t.cache&&Date.now();if(t.cache&&Ya(n,{cachedAt:s}),["post","content"].includes(e.referenceType)){const t=await _d(e.referenceId);et("local.post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=Ce(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ce(["story","get",t.data]);(null==e?void 0:e.data)&&et("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,r[0].commentId])]})],categories:[],comments:r,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return et("local.comment.created",n),{data:Cl.comment(r[0]),cachedAt:s}},updateComment:async(e,t)=>{const n=we();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&&Ya(r,{cachedAt:s}),et("comment.updated",r);const{comments:i}=r;return{data:Cl.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:fp,softDeleteComment:async e=>{we().log("comment/softDeleteComment",e);return fp(e)},hardDeleteComment:async e=>{we().log("comment/hardDeleteComment",e);return fp(e,!0)},flagComment:async e=>{const t=we();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Ya(n),et("comment.flagged",n),!!n},unflagComment:async e=>{const t=we();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Ya(n),et("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=we();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:zd,onCommentUpdated:Wd,onCommentDeleted:Yd,onCommentFlagged:Qd,onCommentUnflagged:Xd,onCommentReactionAdded:Jd,onCommentReactionRemoved:Zd,observeComments:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const s=[],i=(n,r)=>{var s,i;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(s=t.onEvent)||void 0===s||s.call(t,r,n),null===(i=t[r])||void 0===i||i.call(t,n)}};return s.push(zd((e=>i(e,"onCreate"))),Wd((e=>i(e,"onUpdate"))),Yd((e=>i(e,"onDelete"))),Qd((e=>i(e,"onFlagged"))),Xd((e=>i(e,"onUnflagged"))),Jd((e=>i(e,"onReactionAdded"))),Zd((e=>i(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeComment(tmpid: ${s}) > listen`);const i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},o=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&i(t,n)},a=[];return a.push(Wd((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Yd((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),Qd((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Xd((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),Jd((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Zd((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ce(ae(pp,e),(e=>(e.data||e.error)&&i(e,"onFetch")),le(n)),()=>{r(`observeComment(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getComment:(e,t)=>$u(e,t,"commentId",pp,[Yd,Qd,Jd,Zd,Xd,Wd,t=>zd((n=>{if(n.parentId!==e)return;const r=Ce(["comment","get",n.parentId]);(null==r?void 0:r.data)&&t(Object.assign(Object.assign({},r.data),{childrenNumber:r.data.childrenNumber+1,children:[...new Set([...r.data.children,n.commentId])]}))}))]),getComments:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();r(`getComments(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),{policy:l=p}=null!=n?n:{},c=[],u=e.sortBy?e.sortBy:"lastCreated",d=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||"",sortBy:u}],h=n=>{var r,s;let i=null!==(r=n.data.map((e=>Ce(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>Cl.comment(e))))&&void 0!==r?r:[];e.includeDeleted||(i=Ae(i,"isDeleted",!1)),i=i.sort("lastCreated"===u?je:Ne),t({onNextPage:g,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},f=t=>n=>{var r;const s=null===(r=Ce(d))||void 0===r?void 0:r.data;e.referenceId===n.referenceId&&e.referenceType===n.referenceType&&s&&("onCreate"===t?s.data=[...new Set([n.commentId,...s.data])]:"onDelete"===t&&(s.data=s.data.filter((e=>e!==n.commentId))),Te(d,s),h(s))},g=(e=!1)=>{var t,n,r;const s=null===(t=Ce(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const c=ae(gp,Object.assign(Object.assign({},a),{limit:o,page:e||null==s?void 0:s.params.page}));ce(c,(({data:t,error:n,loading:r,paging:s})=>{const o={loading:r,error:n,params:{page:null==s?void 0:s.next},data:i};t&&(o.data=e?t.map(he("comment")):[...new Set([...i,...t.map(he("comment"))])]),Te(d,o),h(o)}),le(l,E))};return c.push(zd(f("onCreate")),Wd(f("onUpdate")),Yd(f("onDelete")),Qd(f("onFlagged")),Xd(f("onUnflagged")),Jd(f("onReactionAdded")),Zd(f("onReactionRemoved"))),g(!0),c.push((()=>Ie(d))),()=>{r(`getComments(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const yp=async e=>{const t=we();t.log("post/queryPosts",e);const{page:n,limit:r=10,includeDeleted:s}=e,i=Xa(e,["page","limit","includeDeleted"]),{dataTypes:o,matchingOnlyParentPost:a}=i,l=n?{token:n}:r?{limit:r}:void 0,{data:c}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},i),{isDeleted:Vl(s),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:l})}),{paging:u}=c,d=Xa(c,["paging"]),h=Za(d,"communityUsers"),{posts:f}=d,p=t.cache&&Date.now();if(t.cache){Ya(h,{cachedAt:p});const e=["post","query",Object.assign(Object.assign({},i),{options:l})];Te(e,{posts:f.map(he("post")),paging:u})}return{data:f.map(Cl.post),cachedAt:p,paging:u}};var vp=Object.freeze({__proto__:null,getPostByIds:lp,createPost:async e=>{const t=we();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);et("post.created",n);const r=Za(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Ya(r,{cachedAt:s});const{posts:i}=r;return{data:Cl.post(i[0]),cachedAt:s}},updatePost:async(e,t)=>{const n=we();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Za(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i}),et("local.post.updated",s);const{posts:o}=s;return{data:Cl.post(o.find((t=>t.postId===e))),cachedAt:i}},editPost:async(e,t)=>{const n=we();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Za(r,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ya(s,{cachedAt:i}),et("local.post.updated",s);const{posts:o}=s;return{data:Cl.post(o.find((t=>t.postId===e))),cachedAt:i}},deletePost:cp,softDeletePost:async e=>{we().log("post/softDeletePost",e);const t=await cp(e,!1);return Cl.post(t)},hardDeletePost:async e=>{we().log("post/hardDeletePost",e);const t=await cp(e,!0);return Cl.post(t)},approvePost:async e=>{const t=we();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);et("post.approved",n),"community"===n.posts[0].targetType&&et("community.updated",n);const r=Za(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),{data:Cl.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=we();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&et("community.updated",n),et("post.declined",n);const r=Za(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ya(r,{cachedAt:s}),{data:Cl.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=we();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Ya(Za(n,"communityUsers")),et("post.flagged",n),!!n},unflagPost:async e=>{const t=we();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Ya(Za(n,"communityUsers")),et("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=we();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Ud,onPostUpdated:Nd,onPostDeleted:Bd,onPostApproved:jd,onPostDeclined:$d,onPostFlagged:qd,onPostUnflagged:Kd,onPostReactionAdded:Gd,onPostReactionRemoved:Hd,observePosts:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const s=[],i=(n,r)=>{var s,i;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(Cl.post(n));null===(s=t.onEvent)||void 0===s||s.call(t,r,Cl.post(n)),null===(i=t[r])||void 0===i||i.call(t,Cl.post(n))}};return s.push(Ud((e=>i(e,"onCreate"))),Nd((e=>i(e,"onUpdate"))),Bd((e=>i(e,"onDelete"))),jd((e=>i(e,"onApproved"))),$d((e=>i(e,"onDeclined"))),qd((e=>i(e,"onFlagged"))),Kd((e=>i(e,"onUnflagged"))),Gd((e=>i(e,"onReactionAdded"))),Hd((e=>i(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observePost(tmpid: ${s}) > listen`);const i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},o=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&i(Object.assign(Object.assign({},t),{data:t.data&&Cl.post(t.data)}),n)},a=[];return a.push(Nd((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Bd((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),jd((e=>o({data:e,loading:!1,origin:"event"},"onApproved"))),$d((e=>o({data:e,loading:!1,origin:"event"},"onDeclined"))),qd((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Kd((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),Gd((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Hd((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ce(ae(_d,e),(e=>(e.data||e.error)&&i(Object.assign(Object.assign({},e),{data:e.data&&Cl.post(e.data)}),"onFetch")),le(n)),()=>{r(`observePosts(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPost:(e,t)=>$u(e,t,"postId",_d,[jd,$d,t=>Bd((n=>{var r;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Ce(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Te(["post","get",e.postId],e),s=e)}t(s)})),qd,e=>Gd((t=>{e(Cl.post(t))})),e=>Hd((t=>{e(Cl.post(t))})),Kd,Nd,oh((t=>zd((async n=>{n.referenceId===e&&(await _d(e),t(n))}))),"referenceId","post"),oh((t=>Yd((async n=>{n.referenceId===e&&(await _d(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getPosts(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["post","collection",{targetId:e.targetId,targetType:e.targetType}],h=n=>{var r,s,i;let o=null!==(r=n.data.map((e=>Ce(["post","get",e]))).filter(Boolean).map((({data:e})=>Cl.post(e))))&&void 0!==r?r:[];const a=e.sortBy?e.sortBy:"lastCreated";o=o.sort("lastCreated"===a?je:Ne),e.includeDeleted||(o=Ae(o,"isDeleted",!1)),e.tags&&(o=o.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(o=Oe(o,e.feedType)),(null===(s=e.dataTypes)||void 0===s?void 0:s.length)&&(o=Pe(o,e.dataTypes)),t({onNextPage:y,data:o,hasNextPage:!!(null===(i=n.params)||void 0===i?void 0:i.page),loading:n.loading,error:n.error})},m=t=>n=>{var r,s;const i=null===(r=Ce(d))||void 0===r?void 0:r.data;if(i){if(n.parentPostId&&n.isDeleted){const t=null===(s=Ce(["post","get",n.parentPostId]))||void 0===s?void 0:s.data;if(!t||(null==t?void 0:t.targetId)!==e.targetId)return;t.children=t.children.filter((e=>e!==n.postId)),Te(["post","get",t.postId],t)}else{if(e.targetId!==n.targetId)return;if(e.targetType!==n.targetType)return}i.data="onDeclined"===t?i.data.filter((e=>e!==n.postId)):[...new Set([n.postId,...i.data])],Te(d,i),h(i)}},y=(e=!1)=>{var t,n,r;const s=null===(t=Ce(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const o=ae(yp,Object.assign(Object.assign({},a),{limit:e?l:void 0,page:e||null==s?void 0:s.params.page}));ce(o,(({data:t,error:n,loading:r,paging:s})=>{const o={loading:r,error:n,params:{page:null==s?void 0:s.next},data:i};t&&(o.data=e?t.map(he("post")):[...new Set([...i,...t.map(he("post"))])]),Te(d,o),h(o)}),le(c,E))};return u.push(Ud(m("onCreate")),jd(m("onApproved")),$d(m("onDeclined")),Bd(m("onDelete")),Nd(m("onUpdate")),qd(m("onFlagged")),Kd(m("onUnflagged")),Gd(m("onReactionAdded")),Hd(m("onReactionRemoved")),oh((e=>zd((async t=>{var n;const r=null===(n=Ce(d))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await _d(t.referenceId),e(t))}))),"referenceId","post")(m("onUpdate")),oh((e=>Yd((async t=>{var n;const r=null===(n=Ce(d))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await _d(t.referenceId),e(t))}))),"referenceId","post")(m("onUpdate"))),y(!0),u.push((()=>Ie(d))),()=>{r(`getPosts(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const bp=async e=>{const t=we();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}};bp.locally=e=>{const t=we();if(t.log("stream/getStream",e),!t.cache)return;const n=Ce(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const wp=e=>{const t=we();return Ze(t,"stream/onStreamStarted","v3.video-streaming.didStart",(t=>{Ya(t),e(t.videoStreamings[0])}))},Ep=e=>{const t=we();return Ze(t,"stream/onStreamStropped","v3.video-streaming.didStop",(t=>{Ya(t),e(t.videoStreamings[0])}))},Sp=e=>{const t=we();return Ze(t,"stream/onStreamRecorded","v3.video-streaming.didRecord",(t=>{Ya(t),e(t.videoStreamings[0])}))},Cp=(e,t)=>$u(e,t,"streamId",bp,[Sp,wp,Ep]);Cp.locally=e=>{const t=we();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Ce(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Tp=async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:s}=n,i=Xa(n,["page","limit"]),o=r?{token:r}:s?{limit:s}:void 0,{data:a}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},i),{options:o})}),{paging:l,results:c}=a,{videoStreamings:u}=c,d=t.cache&&Date.now();return t.cache&&Ya(c,{cachedAt:d}),{data:u,cachedAt:d,paging:l}};var kp=Object.freeze({__proto__:null,createStream:async e=>{const t=we();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s[0],cachedAt:r}},updateStream:async(e,t)=>{const n=we();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&&Ya(r,{cachedAt:s});const{videoStreamings:i}=r;return{data:i.find((t=>t.streamId===e)),cachedAt:s}},deleteStream:async e=>{const t=we();t.log("stream/deleteStream",e);const n=await bp(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 _e(["stream","get",e],i),s},disposeStream:async e=>{const t=we();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&&Ya(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}},queryStreams:async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r}=n,s=Xa(n,["page"]),{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:Z(r,"skiplimit")}})}),{paging:o,results:a}=i,{videoStreamings:l}=a,c=t.cache&&Date.now();t.cache&&Ya(a,{cachedAt:c});const u=ee(o.next);return{data:l,cachedAt:c,prevPage:ee(o.previous),nextPage:u}},getStream:bp,onStreamStarted:wp,onStreamStopped:Ep,onStreamRecorded:Sp,getStreamById:Cp,getStreams:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(g);const i=Date.now();r(`getStreams(tmpid: ${i}) > listen`);const{limit:o}=e,a=Xa(e,["limit"]),l=null!=o?o:f,{policy:c=p}=null!=n?n:{},u=[],d=["streams","collection",e],h=t=>{let n=Ae(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?je:Ne),n},m=(e,n=!1)=>{var r,s;const i=null!==(r=e.data.map((e=>Ce(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?h(i):i,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},y=e=>e=>{var t;const n=null===(t=Ce(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Te(d,n),m(n,!0))},v=(e=!1)=>{var t,n;const r=null===(t=Ce(d))||void 0===t?void 0:t.data,s=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==r?void 0:r.params.page))return;const i=ae(Tp,Object.assign(Object.assign({},a),{limit:e?l:void 0,page:e||null==r?void 0:r.params.page}));ce(i,(({data:e,error:t,loading:n,paging:r})=>{const i={loading:n,error:t,params:{page:null==r?void 0:r.next},data:s};e&&(i.data=[...new Set([...s,...e.map(he("stream"))])]),Te(d,i),m(i)}),le(c))};return u.push(Sp(y()),wp(y()),Ep(y())),v(!0),()=>{r(`getStreams(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const _p=async e=>{const t=we();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}};_p.locally=e=>{const t=we();if(t.log("poll/getPoll",e),!t.cache)return;const n=Ce(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ip=e=>{const t=we();return Ze(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Ya(n),e(n.polls[0])}))},Ap=e=>{const t=we();return Ze(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Ya(n),e(n.polls[0])}))};var Rp=Object.freeze({__proto__:null,createPoll:async e=>{const t=we();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Ya(n,{cachedAt:r});const{polls:s}=n;return{data:s[0],cachedAt:r}},closePoll:async e=>{const t=we();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&&Ya(n,{cachedAt:r}),et("poll.updated",n);const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=we();t.log("poll/deletePoll",e);const n=await _p(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=r,i=Object.assign(Object.assign({},n.data),{isDeleted:!0});return _e(["poll","get",e],i),et("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const n=we();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&&Ya(r,{cachedAt:s});const{polls:i}=r;return et("poll.updated",r),{data:i.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:Ip,onPollDeleted:Ap,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observePoll(tmpid: ${s}) > listen`);const i=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},o=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&i(t,n)},a=[];return a.push(Ip((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Ap((e=>o({data:e,loading:!1,origin:"event"},"onDelete")))),ce(ae(_p,e),(e=>(e.data||e.error)&&i(e,"onFetch")),le(n)),()=>{r(`observePoll(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPoll:(e,t)=>$u(e,t,"pollId",_p,[Ip,Ap])});function Lp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Dp={exports:{}};!function(e,t){var n,r,s,i,o;n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=o.normalizePath(s.path),o.buildURLFromParts(s)}var i=o.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return n.alwaysNormalize?(i.path=o.normalizePath(i.path),o.buildURLFromParts(i)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var l=r.exec(a.path);a.netLoc=l[1],a.path=l[2]}a.netLoc&&!a.path&&(a.path="/");var c={scheme:a.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=a.netLoc,"/"!==i.path[0]))if(i.path){var u=a.path,d=u.substring(0,u.lastIndexOf("/")+1)+i.path;c.path=o.normalizePath(d)}else c.path=a.path,i.params||(c.params=a.params,i.query||(c.query=a.query));return null===c.path&&(c.path=n.alwaysNormalize?o.normalizePath(i.path):i.path),o.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=o}(Dp);var Op=Dp.exports;function xp(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 Pp(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?xp(Object(n),!0).forEach((function(t){Mp(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xp(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Mp(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 Fp(){return Fp=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},Fp.apply(this,arguments)}const Up=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let Np=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}({}),Bp=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}({}),jp=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 $p=function(){},qp={trace:$p,debug:$p,log:$p,warn:$p,info:$p,error:$p};let Kp=qp;function Gp(e,...t){t.forEach((function(t){Kp[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):$p}(t)}))}const Hp=Kp,Vp=/^(\d+)x(\d+)$/,zp=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Wp{constructor(e){"string"==typeof e&&(e=Wp.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=Vp.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(zp.lastIndex=0;null!==(t=zp.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 Yp(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class Qp{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]){Hp.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Fp(new Wp({}),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"]);Up(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(Up(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&&Up(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Xp{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 Jp="audio",Zp="video",eg="audiovideo";class tg{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Jp]:null,[Zp]:null,[eg]: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=Op.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class ng extends tg{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 Xp,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(!Up(this.programDateTime))return null;const e=Up(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:o}=this,a=o[e];a?(a.startPTS=Math.min(a.startPTS,t),a.endPTS=Math.max(a.endPTS,n),a.startDTS=Math.min(a.startDTS,r),a.endDTS=Math.max(a.endDTS,s)):o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Jp]=null,e[Zp]=null,e[eg]=null}}class rg extends tg{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 Xp,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 sg{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&&Up(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 ig(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function og(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=ig(s)):n=function(e){const t=ag(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}(s)}}return n}function ag(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var lg={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},cg="org.w3.clearkey",ug="com.apple.streamingkeydelivery",dg="com.microsoft.playready",hg="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function fg(e){switch(e){case ug:return lg.FAIRPLAY;case dg:return lg.PLAYREADY;case hg:return lg.WIDEVINE;case cg:return lg.CLEARKEY}}var pg="edef8ba979d64acea3c827dcd51d21ed";function gg(e){switch(e){case lg.FAIRPLAY:return ug;case lg.PLAYREADY:return dg;case lg.WIDEVINE:return hg;case lg.CLEARKEY:return cg}}function mg(e){const{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[lg.FAIRPLAY,lg.WIDEVINE,lg.PLAYREADY,lg.CLEARKEY].filter((e=>!!t[e])):[];return!r[lg.WIDEVINE]&&n&&r.push(lg.WIDEVINE),r}const yg="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function vg(e,t,n){return Uint8Array.prototype.slice?e.slice(t,n):new Uint8Array(Array.prototype.slice.call(e,t,n))}const bg=(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,wg=(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,Eg=(e,t)=>{const n=t;let r=0;for(;bg(e,t);){r+=10;r+=Sg(e,t+6),wg(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)},Sg=(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},Cg=(e,t)=>bg(e,t)&&Sg(e,t+6)+10<=e.length-t,Tg=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,kg=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=Sg(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}},_g=e=>{let t=0;const n=[];for(;bg(e,t);){const r=Sg(e,t+6);t+=10;const s=t+r;for(;t+8<s;){const r=kg(e.subarray(t)),s=Ig(r);s&&n.push(s),t+=r.size+10}wg(e,t)&&(t+=10)}return n},Ig=e=>"PRIV"===e.type?Ag(e):"W"===e.type[0]?Lg(e):Rg(e),Ag=e=>{if(e.size<2)return;const t=Og(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}},Rg=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const n=Og(e.data.subarray(t),!0);t+=n.length+1;const r=Og(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=Og(e.data.subarray(1));return{key:e.type,data:t}},Lg=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const n=Og(e.data.subarray(t),!0);t+=n.length+1;const r=Og(e.data.subarray(t));return{key:e.type,info:n,data:r}}const t=Og(e.data);return{key:e.type,data:t}},Dg=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)}},Og=(e,t=!1)=>{const n=Pg();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,o,a="",l=0;for(;l<r;){if(s=e[l++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],a+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],o=e[l++],a+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&o)<<0)}}return a};let xg;function Pg(){return xg||void 0===self.TextDecoder||(xg=new self.TextDecoder("utf-8")),xg}const Mg=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},Fg=Math.pow(2,32)-1,Ug=[].push,Ng={video:1,audio:2,id3:3,text:4};function Bg(e){return String.fromCharCode.apply(null,e)}function jg(e,t){const n=e[t]<<8|e[t+1];return n<0?65536+n:n}function $g(e,t){const n=qg(e,t);return n<0?4294967296+n:n}function qg(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Kg(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 Gg(e,t){const n=[];if(!t.length)return n;const r=e.byteLength;for(let s=0;s<r;){const i=$g(e,s),o=i>1?s+i:r;if(Bg(e.subarray(s+4,s+8))===t[0])if(1===t.length)n.push(e.subarray(s+8,o));else{const r=Gg(e.subarray(s+8,o),t.slice(1));r.length&&Ug.apply(n,r)}s=o}return n}function Hg(e){const t=[],n=e[0];let r=8;const s=$g(e,r);r+=4;r+=0===n?8:16,r+=2;let i=e.length+0;const o=jg(e,r);r+=2;for(let n=0;n<o;n++){let n=r;const o=$g(e,n);n+=4;const a=2147483647&o;if(1===(2147483648&o)>>>31)return Hp.warn("SIDX has hierarchical references (not supported)"),null;const l=$g(e,n);n+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+a-1}}),i+=a,n+=4,r=n}return{earliestPresentationTime:0,timescale:s,version:n,referencesCount:o,references:t}}function Vg(e){const t=[],n=Gg(e,["moov","trak"]);for(let e=0;e<n.length;e++){const r=n[e],s=Gg(r,["tkhd"])[0];if(s){let e=s[0],n=0===e?12:20;const i=$g(s,n),o=Gg(r,["mdia","mdhd"])[0];if(o){e=o[0],n=0===e?12:20;const s=$g(o,n),a=Gg(r,["mdia","hdlr"])[0];if(a){const e=Bg(a.subarray(8,12)),n={soun:Jp,vide:Zp}[e];if(n){const e=Gg(r,["mdia","minf","stbl","stsd"])[0];let o;e&&(o=Bg(e.subarray(12,16))),t[i]={timescale:s,type:n},t[n]={timescale:s,id:i,codec:o}}}}}}return Gg(e,["moov","mvex","trex"]).forEach((e=>{const n=$g(e,4),r=t[n];r&&(r.default={duration:$g(e,12),flags:$g(e,20)})})),t}function zg(e){const t=Gg(e,["schm"])[0];if(t){const n=Bg(t.subarray(4,8));if("cbcs"===n||"cenc"===n)return Gg(e,["schi","tenc"])[0]}return Hp.error("[eme] missing 'schm' box"),null}function Wg(e){const t=$g(e,0);let n=8;1&t&&(n+=4),4&t&&(n+=4);let r=0;const s=$g(e,4);for(let i=0;i<s;i++){if(256&t){r+=$g(e,n),n+=4}512&t&&(n+=4),1024&t&&(n+=4),2048&t&&(n+=4)}return r}function Yg(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Qg(e,t){const n=[],r=t.samples,s=t.timescale,i=t.id;let o=!1;return Gg(r,["moof"]).map((a=>{const l=a.byteOffset-8;Gg(a,["traf"]).map((a=>{const c=Gg(a,["tfdt"]).map((e=>{const t=e[0];let n=$g(e,4);return 1===t&&(n*=Math.pow(2,32),n+=$g(e,8)),n/s}))[0];return void 0!==c&&(e=c),Gg(a,["tfhd"]).map((c=>{const u=$g(c,4),d=16777215&$g(c,0);let h=0;const f=0!=(16&d);let p=0;const g=0!=(32&d);let m=8;u===i&&(0!=(1&d)&&(m+=8),0!=(2&d)&&(m+=4),0!=(8&d)&&(h=$g(c,m),m+=4),f&&(p=$g(c,m),m+=4),g&&(m+=4),"video"===t.type&&(o=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)),Gg(a,["trun"]).map((i=>{const a=i[0],c=16777215&$g(i,0),u=0!=(1&c);let d=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 E=0;const S=$g(i,4);let C=8;u&&(d=$g(i,C),C+=4),f&&(C+=4);let T=d+l;for(let l=0;l<S;l++){if(g?(m=$g(i,C),C+=4):m=h,y?(v=$g(i,C),C+=4):v=p,b&&(C+=4),w&&(E=0===a?$g(i,C):qg(i,C),C+=4),t.type===Zp){let t=0;for(;t<v;){const i=$g(r,T);if(T+=4,Xg(o,r[T])){Jg(r.subarray(T,T+i),o?2:1,e+E/s,n)}T+=i,t+=i+4}}e+=m/s}})))}))}))})),n}function Xg(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Jg(e,t,n,r){const s=Zg(e);let i=0;i+=t;let o=0,a=0,l=!1,c=0;for(;i<s.length;){o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);const e=s.length-i;if(!l&&4===o&&i<s.length){l=!0;if(181===s[i++]){const e=jg(s,i);if(i+=2,49===e){const e=$g(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],a=31&t,l=64&t,c=l?2+3*a:0,u=new Uint8Array(c);if(l){u[0]=t;for(let e=1;e<c;e++)u[e]=s[i++]}r.push({type:e,payloadType:o,pts:n,bytes:u})}}}}}else if(5===o&&a<e){if(l=!0,a>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=a-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];r.push({payloadType:o,pts:n,uuid:e.join(""),userData:Og(l),userDataBytes:l})}}else if(a<e)i+=a;else if(a>e)break}}function Zg(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 o=0;for(r=0;r<s;o++,r++)o===n[0]&&(o++,n.shift()),i[r]=e[o];return i}function em(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 o=new Uint8Array(4);return n&&n.byteLength>0&&new DataView(o.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,o,n||new Uint8Array)}let tm={};class nm{static clearKeyUriToKeyIdMap(){tm={}}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 ug:case hg:case dg:case cg: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||Hp.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 nm(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=og(this.uri);if(t)switch(this.keyFormat){case hg:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case dg:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=em(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=ig(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=tm[this.uri];if(!e){const t=Object.keys(tm).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),tm[this.uri]=e}this.keyId=e}return this}}const rm=/\{\$([a-zA-Z0-9-_]+)\}/g;function sm(e){return rm.test(e)}function im(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]=om(e,i))}}function om(e,t){if(null!==e.variableList||e.hasVariableRefs){const n=e.variableList;return t.replace(rm,(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 am(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 lm(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 cm(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const um={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}},dm=cm();function hm(e,t){var n;return null!=(n=null==dm?void 0:dm.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&n}const fm=/#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,pm=/#EXT-X-MEDIA:(.*)/g,gm=/^#EXT(?:INF|-X-TARGETDURATION):/m,mm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),ym=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 vm{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 Op.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return gm.test(e)}static parseMasterPlaylist(e,t){const n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:sm(e)},r=[];let s;for(fm.lastIndex=0;null!=(s=fm.exec(e));)if(s[1]){var i;const e=new Wp(s[1]);im(n,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const o=om(n,s[2]),a={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:vm.resolve(o,t)},l=e.decimalResolution("RESOLUTION");l&&(a.width=l.width,a.height=l.height),Em((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),a),a.videoCodec&&-1!==a.videoCodec.indexOf("avc1")&&(a.videoCodec=vm.convertAVC1ToAVCOTI(a.videoCodec)),null!=(i=a.unknownCodecs)&&i.length||r.push(a),n.levels.push(a)}else if(s[3]){const e=s[3],r=s[4];switch(e){case"SESSION-DATA":{const e=new Wp(r);im(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=bm(r,t,n);e.encrypted&&e.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(e)):Hp.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const e=new Wp(r);im(n,e,["NAME","VALUE","QUERYPARAM"]),am(n,e,t)}break;case"CONTENT-STEERING":{const e=new Wp(r);im(n,e,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:vm.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":n.startTimeOffset=wm(r)}}const o=r.length>0&&r.length<n.levels.length;return n.levels=o?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,o={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 a=0;for(pm.lastIndex=0;null!==(r=pm.exec(e));){const e=new Wp(r[1]),i=e.TYPE;if(i){const r=o[i],l=s[i]||[];s[i]=l,im(n,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:a++,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?vm.resolve(e.URI,t):""};if(null!=r&&r.length){const e=vm.findGroup(r,c.groupId)||r[0];Sm(c,e,"audioCodec"),Sm(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,n,r,s,i){const o=new sg(t),a=o.fragments;let l,c,u,d=null,h=0,f=0,p=0,g=0,m=null,y=new ng(r,t),v=-1,b=!1;for(mm.lastIndex=0,o.m3u8=e,o.hasVariableRefs=sm(e);null!==(l=mm.exec(e));){b&&(b=!1,y=new ng(r,t),y.start=p,y.sn=h,y.cc=g,y.level=n,d&&(y.initSegment=d,y.rawProgramDateTime=d.rawProgramDateTime,d.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(Up(y.duration)){y.start=p,u&&km(y,u,o),y.sn=h,y.level=n,y.cc=g,y.urlId=s,a.push(y);const e=(" "+l[3]).slice(1);y.relurl=om(o,e),Cm(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=a.length);else{if(l=l[0].match(ym),!l){Hp.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":o.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(s);break;case"SKIP":{const e=new Wp(s);im(o,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(Up(t)){o.skippedSegments=t;for(let e=t;e--;)a.unshift(null);h+=t}const n=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(o.recentlyRemovedDateranges=n.split("\t"));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(s),1);break;case"VERSION":o.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":o.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 Wp(s);im(o,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),im(o,e,e.clientAttrs);const t=new Qp(e,o.dateRanges[e.ID]);t.isValid||o.skippedSegments?o.dateRanges[t.id]=t:Hp.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new Wp(s);im(o,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?lm(o,e,i):am(o,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=bm(s,t,o);if(e.isSupported()){if("NONE"===e.method){u=void 0;break}u||(u={}),u[e.keyFormat]&&(u=Fp({},u)),u[e.keyFormat]=e}else Hp.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":o.startTimeOffset=wm(s);break;case"MAP":{const e=new Wp(s);if(im(o,e,["BYTERANGE","URI"]),y.duration){const s=new ng(r,t);Tm(s,e,n,u),d=s,y.initSegment=d,d.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=d.rawProgramDateTime)}else Tm(y,e,n,u),d=y,b=!0;break}case"SERVER-CONTROL":{const e=new Wp(s);o.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),o.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new Wp(s);o.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=o.partList;e||(e=o.partList=[]);const n=f>0?e[e.length-1]:void 0,r=f++,i=new Wp(s);im(o,i,["BYTERANGE","URI"]);const a=new rg(i,y,t,r,n);e.push(a),y.duration+=a.duration;break}case"PRELOAD-HINT":{const e=new Wp(s);im(o,e,["URI"]),o.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Wp(s);im(o,e,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(e);break}default:Hp.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(a.pop(),p-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(Cm(y,m),y.cc=g,o.fragmentHint=y,u&&km(y,u,o));const w=a.length,E=a[0],S=a[w-1];if(p+=o.skippedSegments*o.targetduration,p>0&&w&&S){o.averagetargetduration=p/w;const e=S.sn;o.endSN="initSegment"!==e?e:0,o.live||(S.endList=!0),E&&(o.startCC=E.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(p+=o.fragmentHint.duration),o.totalduration=p,o.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}}(a,v),o}}function bm(e,t,n){var r,s;const i=new Wp(e);im(n,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=null!=(r=i.METHOD)?r:"",a=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,u=null!=(s=i.KEYFORMAT)?s:"identity";a&&i.IV&&!l&&Hp.error(`Invalid IV: ${i.IV}`);const d=a?vm.resolve(a,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new nm(o,d,u,h,l)}function wm(e){const t=new Wp(e).decimalFloatingPoint("TIME-OFFSET");return Up(t)?t:null}function Em(e,t){["video","audio","text"].forEach((n=>{const r=e.filter((e=>function(e,t){const n=um[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 Sm(e,t,n){const r=t[n];r&&(e[n]=r)}function Cm(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Up(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function Tm(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 km(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 _m="manifest",Im="level",Am="audioTrack",Rm="subtitleTrack",Lm="main",Dm="audio",Om="subtitle";function xm(e){const{type:t}=e;switch(t){case Am:return Dm;case Rm:return Om;default:return Lm}}function Pm(e,t){let n=e.url;return void 0!==n&&0!==n.indexOf("data:")||(n=t.url),n}class Mm{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(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.LEVEL_LOADING,this.onLevelLoading,this),e.on(Np.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Np.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.LEVEL_LOADING,this.onLevelLoading,this),e.off(Np.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Np.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:_m,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:Im,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:Am,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:Rm,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 Hp.trace("[playlist-loader]: playlist request ongoing");Hp.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===_m?n.manifestLoadPolicy.default:Fp({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===Im&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Am&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Rm&&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=Fp({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const i=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},a={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(),vm.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,o,a)}handleMasterPlaylist(e,t,n,r){const s=this.hls,i=e.data,o=Pm(e,n),a=vm.parseMasterPlaylist(i,o);if(a.playlistParsingError)return void this.handleManifestParsingError(e,n,a.playlistParsingError,r,t);const{contentSteering:l,levels:c,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f}=a;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=vm.parseMasterPlaylistMedia(i,o,a);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(Hp.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 Wp({}),bitrate:0,url:""}))}s.trigger(Np.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,n,r,s){const i=this.hls,{id:o,level:a,type:l}=n,c=Pm(e,n),u=Up(o)?o:0,d=Up(a)?a:u,h=xm(n),f=vm.parseLevelPlaylist(e.data,c,d,h,u,this.variableList);if(l===_m){const e={attrs:new Wp({}),bitrate:0,details:f,name:"",url:c};i.trigger(Np.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(Np.ERROR,{type:Bp.NETWORK_ERROR,details:jp.MANIFEST_PARSING_ERROR,fatal:t.type===_m,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===Im?i+=`: ${e.level} id: ${e.id}`:e.type!==Am&&e.type!==Rm||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(i);Hp.warn(`[playlist-loader]: ${i}`);let a=jp.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case _m:a=n?jp.MANIFEST_LOAD_TIMEOUT:jp.MANIFEST_LOAD_ERROR,l=!0;break;case Im:a=n?jp.LEVEL_LOAD_TIMEOUT:jp.LEVEL_LOAD_ERROR,l=!1;break;case Am:a=n?jp.AUDIO_TRACK_LOAD_TIMEOUT:jp.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Rm:a=n?jp.SUBTITLE_TRACK_LOAD_TIMEOUT:jp.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const u={type:Bp.NETWORK_ERROR,details:a,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:s};if(r){const n=(null==t?void 0:t.url)||e.url;u.response=Pp({url:n,data:void 0},r)}this.hls.trigger(Np.ERROR,u)}handlePlaylistLoaded(e,t,n,r,s,i){const o=this.hls,{type:a,level:l,id:c,groupId:u,deliveryDirectives:d}=r,h=Pm(t,r),f=xm(r),p="number"==typeof r.level&&f===Lm?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void o.trigger(Np.ERROR,{type:Bp.NETWORK_ERROR,details:jp.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)o.trigger(Np.ERROR,{type:Bp.NETWORK_ERROR,details:jp.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)),a){case _m:case Im:o.trigger(Np.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:n,networkDetails:s,deliveryDirectives:d});break;case Am:o.trigger(Np.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:n,networkDetails:s,deliveryDirectives:d});break;case Rm:o.trigger(Np.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:n,networkDetails:s,deliveryDirectives:d})}}}function Fm(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 Um(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){Hp.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){Hp.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===n&&(e.mode=n)}function Nm(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 Bm(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,o=e.length;i<o;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 jm="org.id3",$m="com.apple.quicktime.HLS",qm="https://aomedia.org/emsg/ID3";function Km(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Gm=(()=>{const e=Km();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Hm(e,t){return e.getTime()/1e3-t}class Vm{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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Np.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Np.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Nm(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 Fm(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=Km();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===qm&&!n||!r)continue;const o=_g(s[e].data);if(o){const n=s[e].pts;let r=n+s[e].duration;r>Gm&&(r=Gm);r-n<=0&&(r=n+.25);for(let e=0;e<o.length;e++){const s=o[e];if(!Tg(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===Gm&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:a}}=i;if(s&&(o||a)){let e;e="audio"===r?e=>e.type===jm&&a:"video"===r?e=>e.type===qm&&o:e=>e.type===jm&&a||e.type===qm&&o,Bm(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 o=t.fragments[t.fragments.length-1];if(0===i.length||!Up(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=o.programDateTime/1e3-o.start,l=Km();for(let e=0;e<i.length;e++){const t=i[e],r=s[t],o=n[t],d=(null==o?void 0:o.cues)||{};let h=(null==o?void 0:o.durationKnown)||!1;const f=Hm(r.startDate,a);let p=Gm;const g=r.endDate;if(g)p=Hm(g,a),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=Hm(e.startDate,a),h=!0)}const m=Object.keys(r.attr);for(let e=0;e<m.length;e++){const n=m[e];if("ID"===(u=n)||"CLASS"===u||"START-DATE"===u||"DURATION"===u||"END-DATE"===u||"END-ON-NEXT"===u)continue;let s=d[n];if(s)h&&!o.durationKnown&&(s.endTime=p);else{let e=r.attr[n];s=new l(f,p,""),Yp(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=$m,s.id=t,this.id3Track.addCue(s),d[n]=s}}n[t]={cues:d,dateRange:r,durationKnown:h}}var c,u}}class zm{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:o}=this.config,a=this.hls.userConfig;let l=o&&n||t;(a.liveSyncDuration||a.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,o=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(i,s),o)}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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Np.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Np.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Np.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Np.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===jp.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(n=this.levelDetails)&&n.live&&Hp.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 o=n-i,a=o<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&a&&o>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),n=Math.round(2/(1+Math.exp(-.75*o-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 Wm=["NONE","TYPE-0","TYPE-1",null];var Ym="",Qm="YES",Xm="v2";class Jm{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 Zm{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 ey(e,t){const n=t.startPTS;if(Up(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 ty(e,t,n,r,s,i){r-n<=0&&(Hp.warn("Fragment should have a positive duration",t),r=n+t.duration,i=s+t.duration);let o=n,a=r;const l=t.startPTS,c=t.endPTS;if(Up(l)){const e=Math.abs(l-n);Up(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,o=Math.max(n,l),n=Math.min(n,l),s=Math.min(s,t.startDTS),a=Math.min(r,c),r=Math.max(r,c),i=Math.max(i,t.endDTS)}const u=n-t.start;0!==t.start&&(t.start=n),t.duration=r-t.start,t.startPTS=n,t.maxStartPTS=o,t.startDTS=s,t.endPTS=r,t.minEndPTS=a,t.endDTS=i;const d=t.sn;if(!e||d<e.startSN||d>e.endSN)return 0;let h;const f=d-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)ey(p[h],p[h-1]);for(h=f;h<p.length-1;h++)ey(p[h],p[h+1]);return e.fragmentHint&&ey(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function ny(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,o=t.startSN-e.startSN,a=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[o+e];let i=a[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),Up(e.startPTS)&&Up(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){Hp.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=Fp({},e);n&&n.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const n=new Qp(t[e].attr,r[e]);n.isValid?r[e]=n:Hp.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const o=t.fragments;if(i){Hp.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<o.length;e++)o[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],o=t[s+r];i&&o&&i.index===o.index&&i.fragment.sn===o.fragment.sn?n(i,o):r--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?ty(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):ry(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const e=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=e),t.driftEndTime=a,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function ry(e,t){const n=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;n<0||n>=r.length||sy(t,r[n].start)}function sy(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 iy(e,t,n){var r;return null!=e&&e.details?oy(null==(r=e.details)?void 0:r.partList,t,n):null}function oy(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 ay(e){switch(e.details){case jp.FRAG_LOAD_TIMEOUT:case jp.KEY_LOAD_TIMEOUT:case jp.LEVEL_LOAD_TIMEOUT:case jp.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ly(e,t){const n=ay(t);return e.default[(n?"timeout":"error")+"Retry"]}function cy(e,t){const n="linear"===e.backoff?1:Math.pow(2,t);return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function uy(e){return Pp(Pp({},e),{errorRetry:null,timeoutRetry:null})}function dy(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 hy=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 o=t(i);if(o>0)n=s+1;else{if(!(o<0))return i;r=s-1}}return null};function fy(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===py(n,r,s))return s;const i=hy(t,py.bind(null,n,r));return!i||i===e&&s?s:i}function py(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 gy(e,t,n){const r=1e3*Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return(n.endProgramDateTime||0)-r>e}var my=0,yy=2,vy=5,by=0,wy=1,Ey=2;function Sy(e,t,n){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const r=e.details;if(t.details===jp.FRAG_GAP&&r&&t.frag){const e=t.frag.start,n=fy(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 Cy{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=Hp.log.bind(Hp,`${t}:`),this.warn=Hp.warn.bind(Hp,`${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 o;try{o=new self.URL(i.URI,t.url).href}catch(e){Hp.warn(`Could not construct new URL for Rendition Report: ${e}`),o=i.URI||""}if(o===e){r=s;break}o===e.substring(0,o.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 Jm(s,i>=0?i:void 0,Ym)}}}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(),o=s.loading.first?Math.max(0,i-s.loading.first):0;if(r.advancedDateTime=Date.now()-o,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&&ny(n,r),!this.canLoad||!r.live)return;let o,a,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,i=r.endSN,c=r.lastPartIndex,u=s===i,d=e?0:c;-1!==c?(a=u?i+1:s,l=u?d:c+1):a=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(a+=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(o=this.getDeliveryDirectives(r,t.deliveryDirectives,a,l),e||!u)return void this.loadPlaylist(o)}else r.canBlockReload&&(o=this.getDeliveryDirectives(r,t.deliveryDirectives,a,l));const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,d=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-u));r.updated&&i>this.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==a&&r.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+d<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=d);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(o)),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?Xm:Qm:Ym}(e,n);return null!=t&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,s=Ym),new Jm(n,r,s)}checkRetry(e){const t=e.details,n=ay(e),r=e.errorAction,{action:s,retryCount:i=0,retryConfig:o}=r||{},a=!!r&&!!o&&(s===vy||!r.resolved&&s===yy);if(a){var l;if(this.requestScheduled=-1,i>=o.maxNumRetry)return!1;if(n&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=cy(o,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return a}}let Ty;class ky extends Cy{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(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Np.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Np.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Np.FRAG_LOADED,this.onFragLoaded,this),e.on(Np.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Np.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Np.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Np.FRAG_LOADED,this.onFragLoaded,this),e.off(Np.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"))&&(Ty||(Ty=/chrome|firefox/i.test(navigator.userAgent)),Ty&&(e.audioCodec=void 0));const{AUDIO:o,CODECS:a,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:u,SUBTITLES:d}=i,h=`${`${c||"."}-`}${e.bitrate}-${u}-${l}-${a}`;s=r[h],s?s.addFallback(e):(s=new Zm(e),r[h]=s,n.push(s)),_y(s,"audio",o),_y(s,"text",d)})),this.filterAndSortMediaOptions(n,t)}filterAndSortMediaOptions(e,t){let n=[],r=[],s=!1,i=!1,o=!1,a=e.filter((({audioCodec:e,videoCodec:t,width:n,height:r,unknownCodecs:a})=>(s||(s=!(!n||!r)),i||(i=!!t),o||(o=!!e),!(null!=a&&a.length)&&(!e||hm(e,"audio"))&&(!t||hm(t,"video")))));if((s||i)&&o&&(a=a.filter((({videoCodec:e,width:t,height:n})=>!!e||!(!t||!n)))),0===a.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||hm(e.audioCodec,"audio"))),Iy(n)),t.subtitles&&(r=t.subtitles,Iy(r));const l=a.slice(0);a.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&&(a=this.steering.filterParsedLevels(a),a.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===a[0].pathwayId){c=l[e];break}this._levels=a;for(let e=0;e<a.length;e++)if(a[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${a.length} level(s) found, first bitrate: ${c.bitrate}`);break}const u=o&&!i,d={levels:a,audioTracks:n,subtitleTracks:r,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:o,video:i,altAudio:!u&&n.some((e=>!!e.url))};this.hls.trigger(Np.MANIFEST_PARSED,d),(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(Np.ERROR,{type:Bp.OTHER_ERROR,details:jp.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],o=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,n===e&&i.details&&r&&s===o)return;this.log(`Switching to level ${e}${o?" with Pathway "+o:""} from level ${n}${s?" with Pathway "+s:""}`);const a=Fp({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete a._attrs,delete a._urlId,this.hls.trigger(Np.LEVEL_SWITCHING,a);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===Im&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===Lm){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 o;if(!i)return this.warn(`Invalid level index ${r}`),void(null!=(o=t.deliveryDirectives)&&o.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(Np.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(Np.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 _y(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 Iy(e){const t={};e.forEach((e=>{const n=e.groupId||"";e.id=t[n]=t[n]||0,t[n]++}))}var Ay="NOT_LOADED",Ry="APPENDING",Ly="PARTIAL",Dy="OK";class Oy{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(Np.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Np.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Np.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Np.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Np.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 o=i.range[e];o&&o.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=Py(n),i=this.fragments[s];if(!i||i.buffered&&n.gap)return;const o=!n.relurl;Object.keys(t).forEach((e=>{const s=n.elementaryStreams[e];if(!s)return;const a=t[e],l=o||!0===s.partial;i.range[e]=this.getBufferedTimes(n,r,l,a)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),xy(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=Py(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,o=e.end,a=e.minEndPTS||o,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&&a<=n){s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(o,r.end(e))});break}if(i<n&&o>t)s.partial=!0,s.time.push({startPTS:Math.max(i,r.start(e)),endPTS:Math.min(o,r.end(e))});else if(o<=t)break}return s}getPartialFragment(e){let t,n,r,s=null,i=0;const{bufferPadding:o,fragments:a}=this;return Object.keys(a).forEach((l=>{const c=a[l];c&&xy(c)&&(n=c.body.start-o,r=c.body.end+o,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||xy(t))}getState(e){const t=Py(e),n=this.fragments[t];return n?n.buffered?xy(n)?Ly:Dy:Ry:Ay}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=Py(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=Py(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 o=this.fragments[i];if(!o)return;const a=o.body;a.type!==n||r&&!a.gap||a.start<t&&a.end>e&&(o.buffered||s)&&this.removeFragment(a)}))}removeFragment(e){const t=Py(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 xy(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 Py(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const My=Math.pow(2,17);class Fy{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 By({type:Bp.NETWORK_ERROR,details:jp.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void a(Ny(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new i(r),c=Uy(e),u=uy(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:My};e.stats=l.stats,l.load(c,d,{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)),o({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,r,s,i)=>{this.resetLoader(e,l),a(new By({type:Bp.NETWORK_ERROR,details:jp.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Pp({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),a(new By({type:Bp.NETWORK_ERROR,details:jp.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,l),a(new By({type:Bp.NETWORK_ERROR,details:jp.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void a(Ny(e,t));const l=this.loader=e.loader=s?new s(r):new i(r),c=Uy(e,t),u=uy(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:My};t.stats=l.stats,l.load(c,d,{onSuccess:(r,s,i,a)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:r.data,networkDetails:a};n(c),o(c)},onError:(n,r,s,i)=>{this.resetLoader(e,l),a(new By({type:Bp.NETWORK_ERROR,details:jp.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Pp({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),a(new By({type:Bp.NETWORK_ERROR,details:jp.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:n}))},onTimeout:(n,r,s)=>{this.resetLoader(e,l),a(new By({type:Bp.NETWORK_ERROR,details:jp.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.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),o=(r-i)*Math.round(n.loaded/i);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);const i=n.loading,o=r.loading;i.start?i.first+=o.first-o.start:(i.start=o.start,i.first=o.first),i.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Uy(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(Up(s)&&Up(i)){var o;let t=s,n=i;if("initSegment"===e.sn&&"AES-128"===(null==(o=e.decryptdata)?void 0:o.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 Ny(e,t){const n=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:Bp.MEDIA_ERROR,details:jp.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new By(r)}class By extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class jy{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=jp.KEY_LOAD_ERROR,n,r,s){return new By({type:Bp.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,jp.KEY_LOAD_ERROR,n))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,jp.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let o=this.keyUriToKeyInfo[i];if(null!=(n=o)&&n.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});var a;if(null!=(r=o)&&r.keyLoadPromise)switch(null==(a=o.mediaKeySessionContext)?void 0:a.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:o})))}switch(o=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(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,jp.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 o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},a=n.keyLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{const{frag:o,keyInfo:a,url:l}=n;if(!o.decryptdata||a!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(o,jp.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));a.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,a.loader=null,s({frag:o,keyInfo:a})},onError:(e,n,r,s)=>{this.resetLoader(n),i(this.createKeyLoadError(t,jp.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,Pp({url:o.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,jp.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,n,r)=>{this.resetLoader(n),i(this.createKeyLoadError(t,jp.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(o,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 $y={length:0,start:()=>0,end:()=>0};class qy{static isBuffered(e,t){try{if(e){const n=qy.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=qy.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,o=t,a=t;for(let e=0;e<r.length;e++){const l=r[e].start,c=r[e].end;if(t+n>=l&&t<c)o=l,a=c,i=a-t;else if(t+n<l){s=l;break}}return{len:i,start:o||0,end:a||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return Hp.log("failed to get media.buffered",e),$y}}}class Ky{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 Gy(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 Hy(e,t){if(e){const n=e.start+t;e.start=e.startPTS=n,e.endPTS=n+e.duration}}function Vy(e,t){const n=t.fragments;for(let t=0,r=n.length;t<r;t++)Hy(n[t],e);t.fragmentHint&&Hy(t.fragmentHint,e),t.alignedSliding=!0}function zy(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 Hp.log("No fragments to align");const i=Gy(r,s[0].cc);if(i&&(!i||i.startPTS))return i;Hp.log("No frag in previous level to align on")}(n.details,t);e&&Up(e.start)&&(Hp.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Vy(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&&Up(s)&&(Hp.log(`Adjusting PTS using programDateTime delta ${r-n}ms, sliding:${s.toFixed(3)} ${e.url} `),Vy(s,e))}(n,t.details),n.alignedSliding||!t.details||n.skippedSegments||ry(t.details,n))}function Wy(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=Gy(n,s.cc)||n[Math.round(n.length/2)-1],o=s.programDateTime,a=i.programDateTime;if(null===o||null===a)return;Vy((a-o)/1e3-(i.start-s.start),e)}class Yy{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 Qy{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 Xy{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],o=n[3],a=this.invSubMix,l=a[0],c=a[1],u=a[2],d=a[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 a=h[f],g=h[a],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,o[f]=y,y=16843009*m^65537*g^257*a^16843008*f,l[n]=y<<24|y>>>8,c[n]=y<<16|y>>>16,u[n]=y<<8|y>>>24,d[n]=y,f?(f=a^h[h[h[m^a]]],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 o,a;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),u=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(o=0;o<i;o++)o<s?y=l[o]=t[o]:(v=y,o%s==0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v],v^=d[o/s|0]<<24):s>6&&o%s==4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v]),l[o]=y=(l[o-s]^v)>>>0);for(a=0;a<i;a++)o=i-a,v=3&a?l[o]:l[o-4],c[a]=a<4||o<=4?v:f[u[v>>>24]]^p[u[v>>>16&255]]^g[u[v>>>8&255]]^m[u[255&v]],c[a]=c[a]>>>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,o=this.invSubMix,a=o[0],l=o[1],c=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n);let h=d[0],f=d[1],p=d[2],g=d[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,E,S,C,T,k,_,I,A,R,L,D;const O=this.networkToHostOrderSwap;for(;t<m.length;){for(_=O(m[t]),I=O(m[t+1]),A=O(m[t+2]),R=O(m[t+3]),S=_^s[0],C=R^s[1],T=A^s[2],k=I^s[3],L=4,D=1;D<r;D++)v=a[S>>>24]^l[C>>16&255]^c[T>>8&255]^u[255&k]^s[L],b=a[C>>>24]^l[T>>16&255]^c[k>>8&255]^u[255&S]^s[L+1],w=a[T>>>24]^l[k>>16&255]^c[S>>8&255]^u[255&C]^s[L+2],E=a[k>>>24]^l[S>>16&255]^c[C>>8&255]^u[255&T]^s[L+3],S=v,C=b,T=w,k=E,L+=4;v=i[S>>>24]<<24^i[C>>16&255]<<16^i[T>>8&255]<<8^i[255&k]^s[L],b=i[C>>>24]<<24^i[T>>16&255]<<16^i[k>>8&255]<<8^i[255&S]^s[L+1],w=i[T>>>24]<<24^i[k>>16&255]<<16^i[S>>8&255]<<8^i[255&C]^s[L+2],E=i[k>>>24]<<24^i[S>>16&255]<<16^i[C>>8&255]<<8^i[255&T]^s[L+3],y[t]=O(v^h),y[t+1]=O(E^f),y[t+2]=O(w^p),y[t+3]=O(b^g),h=_,f=I,p=A,g=R,t+=4}return y.buffer}}class Jy{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?vg(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=Yg(i,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(n=r);let a=this.softwareDecrypter;a||(a=this.softwareDecrypter=new Xy),a.expandKey(t);const l=s;return this.currentResult=a.decrypt(o.buffer,0,n),this.currentIV=vg(o,-16).buffer,l||null}webCryptoDecrypt(e,t,n){const r=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new Qy(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 Yy(r,new Uint8Array(n)).decrypt(e.buffer,t)})).catch((r=>(Hp.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=vg(e,0,n),this.remainderData=vg(e,n)),t}logOnce(e){this.logEnabled&&(Hp.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Zy=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},ev="STOPPED",tv="IDLE",nv="KEY_LOADING",rv="FRAG_LOADING",sv="FRAG_LOADING_WAITING_RETRY",iv="WAITING_TRACK",ov="PARSING",av="PARSED",lv="ENDED",cv="ERROR",uv="WAITING_INIT_PTS",dv="WAITING_LEVEL";class hv 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=ev,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=Hp.log.bind(Hp,`${r}:`),this.warn=Hp.warn.bind(Hp,`${r}:`),this.hls=e,this.fragmentLoader=new Fy(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Jy(e.config),e.on(Np.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=ev}_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 qy.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===ev&&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,o=qy.bufferInfo(r||n,i,e.maxBufferHole);if(this.log(`media seeking to ${Up(i)?i.toFixed(3):i}, state: ${s}`),this.state===lv)this.resetLoadingState();else if(t){const n=e.maxFragLookUpTolerance,r=t.start-n,s=t.start+t.duration+n;if(!o.len||s<o.start||r>o.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||o.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=ev,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===rv||!this.fragCurrent&&n===ov)&&(this.fragmentTracker.removeFragment(e),this.state=tv):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Np.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==ev&&this.state!==cv&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:n}=this;if(n.getState(e)===Ry){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)===Ly&&n.removeFragment(e))}flushMainBuffer(e,t,n=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:n};this.hls.trigger(Np.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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return n.trigger(Np.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 o=e.stats;this.state=tv,t.fragmentError=0,e.data=new Uint8Array(n.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),n.frag===r&&s.trigger(Np.FRAG_BUFFERED,{stats:o,frag:r,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==ev&&this.state!==cv&&(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 o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Lm?"level":"track"} ${e.level} (frag:[${(null!=(n=e.startPTS)?n:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${o?Zy(qy.getBuffered(o)):"(detached)"})`),this.state=tv,o&&(!this.loadedmetadata&&e.type==Lm&&o.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)),o=new Ky(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!i);t.flush(o)}_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 o=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=nv,this.fragCurrent=e,o=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Np.KEY_LOADED,e),this.state===nv&&(this.state=tv),e})),this.hls.trigger(Np.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=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 a=this.getNextPart(s,e,n);if(a>-1){const l=s[a];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${a}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=rv,c=o?o.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(Np.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))}`),Up(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=rv;const a=this.config.progressive;let l;return l=a&&o?o.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,a?r:void 0),o]).then((([e])=>(!a&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Np.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 o;const a=[],l=null==(o=n.details)?void 0:o.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{a[t.index]=r;const i=r.part;this.hls.trigger(Np.FRAG_LOADED,r);const o=iy(n,e.sn,t.index+1)||oy(l,e.sn,t.index+1);if(!o)return s({frag:e,part:i,partsLoaded:a});c(o)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===jp.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Np.ERROR,t)}else this.hls.trigger(Np.ERROR,{type:Bp.OTHER_ERROR,details:jp.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==ov)return void(this.fragCurrent||this.state===ev||this.state===cv||(this.state=tv));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 o=t[r],a=i>-1?iy(o,s,i):null,l=a?a.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)}(o,s,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:a,level:o}):null}bufferFragmentData(e,t,n,r,s){var i;if(!e||this.state!==ov)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=Yg(o,a)),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(Np.BUFFER_APPENDING,c),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!qy.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const n=t.currentTime,r=qy.bufferInfo(t,n,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),o=Math.max(Math.min(e.start-i,r.end-i),n+i);e.start-o>i&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const n=this.getLoadPosition();return Up(n)?this.getFwdBufferInfoAtPos(e,n,t):null}getFwdBufferInfoAtPos(e,t,n){const{config:{maxBufferHole:r}}=this,s=qy.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 qy.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=Lm){const n=this.fragmentTracker.getAppendedFrag(e,Lm);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 o;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||(o=this.getInitialLiveFragment(t,n),this.startPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=i&&(o=n[0]);if(!o){const n=s.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,n,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const n=this.fragmentTracker.getState(e);return(n===Dy||n===Ly&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,s){const i=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(null===o)return o;if(e=o,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 o=0,a=e.length;o<a;o++){const a=e[o];if(i=i&&!a.independent,r>-1&&n<a.start)break;const l=a.loaded;l?r=-1:(s||a.independent||i)&&a.fragment===t&&(r=o),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||!Up(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(gy(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 hy(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:o}=n;const{fragmentHint:a}=n,l=r.maxFragLookUpTolerance,c=n.partList,u=!!(r.lowLatencyMode&&null!=c&&c.length&&a);let d;if(u&&a&&!this.bitrateTest&&(i=i.concat(a),o=a.sn),e<t){d=fy(s,i,e,e>t-l?0:l)}else d=i[i.length-1];if(d){const e=d.sn-n.startSN,t=this.fragmentTracker.getState(d);if((t===Dy||t===Ly&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!u||c[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=i[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==Dy?t:null}}}return d}synchronizeToLiveEdge(e){const{config:t,media:n}=this;if(!n)return;const r=this.hls.liveSyncPosition,s=n.currentTime,i=e.fragments[0].start,o=e.edge,a=s>=i-t.maxFragLookUpTolerance&&s<=o;if(null!==r&&n.duration>r&&(s<r||!a)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!a&&n.readyState<4||s<o-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: ${o}, 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,o=e.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const a=e.fragments[0].start,l=!t,c=e.alignedSliding&&Up(a);if(l||!c&&!a){zy(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: ${o}`),n}return a}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&&Up(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===sv)||(this.state=tv)}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===jp.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const i=t.errorAction,{action:o,retryCount:a=0,retryConfig:l}=i||{};if(i&&o===vy&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:n.level);const r=cy(l,a);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${a+1}/${l.maxNumRetry} in ${r}ms`),i.resolved=!0,this.retryDate=self.performance.now()+r,this.state=sv}else l&&i?(this.resetFragmentErrors(e),a<l.maxNumRetry?s||(i.resolved=!0):Hp.warn(`${t.details} reached or exceeded max retry (${a})`)):(null==i?void 0:i.action)===yy?this.state=dv:this.state=cv;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===ov||this.state===av){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===Dm&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ev&&(this.state=tv)}afterBufferFlushed(e,t,n){if(!e)return;const r=qy.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===lv&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=tv}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 o=e.elementaryStreams[s];if(o){const a=o.endPTS-o.startPTS;if(a<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${a})`),t||!1;const l=r?0:ty(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(Np.LEVEL_PTS_UPDATED,{details:i,level:n,drift:l,type:s,frag:e,start:o.startPTS,end:o.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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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=av,this.hls.trigger(Np.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 fv(){return self.SourceBuffer||self.WebKitSourceBuffer}function pv(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class gv{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=Yg(this.cachedData,e),this.cachedData=null);let n,r=Eg(e,0),s=r?r.length:0;const i=this._audioTrack,o=this._id3Track,a=r?(e=>{const t=_g(e);for(let e=0;e<t.length;e++){const n=t[e];if(Tg(n))return Dg(n)}})(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Up(a))&&(this.basePTS=mv(a,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:jm,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 Cg(e,s)?(r=Eg(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:jm,duration:Number.POSITIVE_INFINITY}),s+=r.length,n=s):s++;if(s===l&&n!==l){const t=vg(e,n);this.cachedData?this.cachedData=Yg(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:pv(),id3Track:o,textTrack:pv()}}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:pv(),id3Track:this._id3Track,textTrack:pv()}}destroy(){}}const mv=(e,t,n)=>{if(Up(e))return 90*e;return 9e4*t+(n?9e4*n.baseTime/n.timescale:0)};function yv(e,t){return 255===e[t]&&240==(246&e[t+1])}function vv(e,t){return 1&e[t+1]?7:9}function bv(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function wv(e,t){return t+1<e.length&&yv(e,t)}function Ev(e,t){if(wv(e,t)){const n=vv(e,t);if(t+n>=e.length)return!1;const r=bv(e,t);if(r<=n)return!1;const s=t+r;return s===e.length||wv(e,s)}return!1}function Sv(e,t,n,r,s){if(!e.samplerate){const i=function(e,t,n,r){let s,i,o,a;const l=navigator.userAgent.toLowerCase(),c=r,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[n+2])>>>6);const d=(60&t[n+2])>>>2;if(!(d>u.length-1))return o=(1&t[n+2])<<2,o|=(192&t[n+3])>>>6,Hp.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,a=new Array(4),i=d-3):(s=2,a=new Array(2),i=d):-1!==l.indexOf("android")?(s=2,a=new Array(2),i=d):(s=5,a=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&d>=6?i=d-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(d>=6&&1===o||/vivaldi/i.test(l))||!r&&1===o)&&(s=2,a=new Array(2)),i=d)),a[0]=s<<3,a[0]|=(14&d)>>1,a[1]|=(1&d)<<7,a[1]|=o<<3,5===s&&(a[1]|=(14&i)>>1,a[2]=(1&i)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:u[d],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${d}`})}(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,Hp.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function Cv(e){return 9216e4/e}function Tv(e,t,n,r,s){const i=r+s*Cv(e.samplerate),o=function(e,t){const n=vv(e,t);if(t+n<=e.length){const r=bv(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}(t,n);let a;if(o){const{frameLength:r,headerLength:s}=o,l=s+r,c=Math.max(0,n+l-t.length);c?(a=new Uint8Array(l-s),a.set(t.subarray(n+s,t.length),0)):a=t.subarray(n+s,n+l);const u={unit:a,pts:i};return c||e.samples.push(u),{sample:u,length:l,missing:c}}const l=t.length-n;a=new Uint8Array(l),a.set(t.subarray(n,t.length),0);return{sample:{unit:a,pts:i},length:l,missing:-1}}const kv=/\/emsg[-/]ID3/i;let _v=null;const Iv=[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],Av=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Rv=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lv=[0,1,1,4];function Dv(e,t,n,r,s){if(n+24>t.length)return;const i=Ov(t,n);if(i&&n+i.frameLength<=t.length){const o=r+s*(9e4*i.samplesPerFrame/i.sampleRate),a={unit:t.subarray(n,n+i.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(a),{sample:a,length:i.frameLength,missing:0}}}function Ov(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 o=e[t+2]>>1&1,a=e[t+3]>>6,l=1e3*Iv[14*(3===n?3-r:3===r?3:4)+s-1],c=Av[3*(3===n?0:2===n?1:2)+i],u=3===a?1:2,d=Rv[n][r],h=Lv[r],f=8*d*h,p=Math.floor(d*l/c+o)*h;if(null===_v){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_v=e?parseInt(e[1]):0}return!!_v&&_v<=87&&2===r&&l>=224e3&&0===a&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:u,frameLength:p,samplesPerFrame:f}}}function xv(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function Pv(e,t){return t+1<e.length&&xv(e,t)}function Mv(e,t){if(t+1<e.length&&xv(e,t)){const n=4,r=Ov(e,t);let s=n;null!=r&&r.frameLength&&(s=r.frameLength);const i=t+s;return i===e.length||Pv(e,i)}return!1}class Fv{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&&Hp.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,o=0;const a=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);a();const g=a();if(l(5),d(3),a(),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&&d(1),f(),f(),d(1),u())for(t=3!==e?8:12,n=0;n<t;n++)u()&&p(n<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(d(1),h(),h(),e=c(),n=0;n<e;n++)h();f(),d(1);const y=c(),v=c(),b=l(1);0===b&&d(1),d(1),u()&&(r=c(),s=c(),i=c(),o=c());let w=[1,1];if(u()&&u()){switch(a()){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=[a()<<8|a(),a()<<8|a()]}}return{width:Math.ceil(16*(y+1)-2*r-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+o),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Uv{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Jy(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=Zg(s.data),o=this.getAvcEncryptedData(i);this.decryptBuffer(o.buffer).then((o=>{s.data=this.getAvcDecryptedUnit(i,o),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 Nv=188;class Bv{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=Bv.syncOffset(e);return t>0&&Hp.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-Nv)+1,r=0;for(;r<n;){let s=!1,i=-1,o=0;for(let a=r;a<t;a+=Nv){if(71!==e[a]){if(o)return-1;break}if(o++,-1===i&&(i=a,0!==i&&(n=Math.min(i+18612,e.length-Nv)+1)),s||(s=0===$v(e,a)),s&&o>1&&(0===i&&o>2||a+Nv>n))return i}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Ng[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=Bv.createTrack("video"),this._audioTrack=Bv.createTrack("audio",r),this._id3Track=Bv.createTrack("id3"),this._txtTrack=Bv.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,o=this._audioTrack,a=this._id3Track,l=this._txtTrack;let c=i.pid,u=i.pesData,d=o.pid,h=a.pid,f=o.pesData,p=a.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=Yg(this.remainderData,e)).length,this.remainderData=null),v<Nv&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:i,id3Track:a,textTrack:l};const b=Math.max(0,Bv.syncOffset(e));v-=(v-b)%Nv,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+=Nv)if(71===e[t]){const r=!!(64&e[t+1]),v=$v(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+Nv)continue}else w=t+4;switch(v){case c:r&&(u&&(s=Gv(u))&&this.parseAVCPES(i,l,s,!1),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,t+Nv)),u.size+=t+Nv-w);break;case d:if(r){if(f&&(s=Gv(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+Nv)),f.size+=t+Nv-w);break;case h:r&&(p&&(s=Gv(p))&&this.parseID3PES(a,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+Nv)),p.size+=t+Nv-w);break;case 0:r&&(w+=e[w]+1),y=this._pmtId=qv(e,w);break;case y:{r&&(w+=e[w]+1);const s=Kv(e,w,this.typeSupported,n);c=s.avc,c>0&&(i.pid=c),d=s.audio,d>0&&(o.pid=d,o.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(a.pid=h),null===g||m||(Hp.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(Np.ERROR,Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=u,o.pesData=f,a.pesData=p;const E={audioTrack:o,videoTrack:i,id3Track:a,textTrack:l};return r&&this.extractRemainingSamples(E),E}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,o=t.pesData,a=r.pesData;let l;if(i&&(l=Gv(i))?(this.parseAVCPES(n,s,l,!0),n.pesData=null):n.pesData=i,o&&(l=Gv(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=o&&o.size&&Hp.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;a&&(l=Gv(a))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=a}demuxSampleAes(e,t,n){const r=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new Uv(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,o=this.avcSample,a=!1;n.data=null,o&&s.length&&!e.audFound&&(Hv(o,e),o=this.avcSample=jv(!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(a&&s.length>4){const e=new Fv(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=o)&&l.frame&&!o.key&&(Hv(o,e),o=this.avcSample=null);o||(o=this.avcSample=jv(!0,n.pts,n.dts,"")),o.frame=!0,o.key=t;break}case 5:i=!0,null!=(s=o)&&s.frame&&!o.key&&(Hv(o,e),o=this.avcSample=null),o||(o=this.avcSample=jv(!0,n.pts,n.dts,"")),o.key=!0,o.frame=!0;break;case 6:i=!0,Jg(r.data,1,n.pts,t.samples);break;case 7:if(i=!0,a=!0,!e.sps){const t=r.data,n=new Fv(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,o&&Hv(o,e),o=this.avcSample=jv(!1,n.pts,n.dts,"");break;case 12:i=!0;break;default:i=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&i){o.units.push(r)}})),r&&o&&(Hv(o,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 o,a,l,c=0,u=-1,d=0;for(-1===r&&(u=0,d=31&t[0],r=0,c=1);c<n;)if(o=t[c++],r)if(1!==r)if(o)if(1===o){if(u>=0){const e={data:t.subarray(u,c-r-1),type:d};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)),a=c-r-1,a>0)){const e=new Uint8Array(n.data.byteLength+a);e.set(n.data,0),e.set(t.subarray(0,a),n.data.byteLength),n.data=e,n.state=0}}c<n?(l=31&t[c],u=c,d=l,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(u>=0&&r>=0){const e={data:t.subarray(u,n),type:d,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,o,a=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+a.byteLength);e.set(r.sample.unit,0),e.set(a,s),a=e}else{const i=s-t;r.sample.unit.set(a.subarray(0,t),i),e.samples.push(r.sample),n=r.missing}}for(s=n,i=a.length;s<i-1&&!wv(a,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(Hp.warn(`parsing error: ${e}`),this.observer.emit(Np.ERROR,Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:n,reason:e}),!t)return}if(Sv(e,this.observer,a,s,this.audioCodec),void 0!==t.pts)o=t.pts;else{if(!r)return void Hp.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Cv(e.samplerate);o=r.sample.pts+t}}let l,c=0;for(;s<i;){if(l=Tv(e,a,s,o,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!wv(a,s);s++);}}parseMPEGPES(e,t){const n=t.data,r=n.length;let s=0,i=0;const o=t.pts;if(void 0!==o)for(;i<r;)if(Pv(n,i)){const t=Dv(e,n,i,o,s);if(!t)break;i+=t.length,s++}else i++;else Hp.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void Hp.warn("[tsdemuxer]: ID3 PES unknown PTS");const n=Fp({},t,{type:this._avcTrack?qm:jm,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function jv(e,t,n,r){return{key:e,frame:!1,pts:t,dts:n,units:[],debug:r,length:0}}function $v(e,t){return((31&e[t+1])<<8)+e[t+2]}function qv(e,t){return(31&e[t+10])<<8|e[t+11]}function Kv(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=$v(e,t);switch(e[t]){case 207:if(!r){Hp.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){Hp.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?Hp.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:Hp.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function Gv(e){let t,n,r,s,i,o=0;const a=e.data;if(!e||0===e.size)return null;for(;a[0].length<19&&a.length>1;){const e=new Uint8Array(a[0].length+a[1].length);e.set(a[0]),e.set(a[1],a[0].length),a[0]=e,a.splice(1,1)}t=a[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&&(Hp.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 u=new Uint8Array(e.size);for(let e=0,n=a.length;e<n;e++){t=a[e];let n=t.byteLength;if(c){if(c>n){c-=n;continue}t=t.subarray(c),n-=c,c=0}u.set(t,o),o+=n}return n&&(n-=r+3),{data:u,pts:s,dts:i,len:n}}return null}function Hv(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&&Hp.log(e.pts+"/"+e.dts+":"+e.debug)}class Vv{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 zv=Math.pow(2,32)-1;class Wv{static init(){let e;for(e in Wv.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:[]},Wv.types)Wv.types.hasOwnProperty(e)&&(Wv.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]);Wv.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]);Wv.STTS=Wv.STSC=Wv.STCO=s,Wv.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Wv.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Wv.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Wv.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);Wv.FTYP=Wv.box(Wv.types.ftyp,i,a,i,o),Wv.DINF=Wv.box(Wv.types.dinf,Wv.box(Wv.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 Wv.box(Wv.types.hdlr,Wv.HDLR_TYPES[e])}static mdat(e){return Wv.box(Wv.types.mdat,e)}static mdhd(e,t){t*=e;const n=Math.floor(t/(zv+1)),r=Math.floor(t%(zv+1));return Wv.box(Wv.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 Wv.box(Wv.types.mdia,Wv.mdhd(e.timescale,e.duration),Wv.hdlr(e.type),Wv.minf(e))}static mfhd(e){return Wv.box(Wv.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?Wv.box(Wv.types.minf,Wv.box(Wv.types.smhd,Wv.SMHD),Wv.DINF,Wv.stbl(e)):Wv.box(Wv.types.minf,Wv.box(Wv.types.vmhd,Wv.VMHD),Wv.DINF,Wv.stbl(e))}static moof(e,t,n){return Wv.box(Wv.types.moof,Wv.mfhd(e),Wv.traf(n,t))}static moov(e){let t=e.length;const n=[];for(;t--;)n[t]=Wv.trak(e[t]);return Wv.box.apply(null,[Wv.types.moov,Wv.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(Wv.mvex(e)))}static mvex(e){let t=e.length;const n=[];for(;t--;)n[t]=Wv.trex(e[t]);return Wv.box.apply(null,[Wv.types.mvex,...n])}static mvhd(e,t){t*=e;const n=Math.floor(t/(zv+1)),r=Math.floor(t%(zv+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 Wv.box(Wv.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 Wv.box(Wv.types.sdtp,n)}static stbl(e){return Wv.box(Wv.types.stbl,Wv.stsd(e),Wv.box(Wv.types.stts,Wv.STTS),Wv.box(Wv.types.stsc,Wv.STSC),Wv.box(Wv.types.stsz,Wv.STSZ),Wv.box(Wv.types.stco,Wv.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 o=Wv.box(Wv.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),a=e.width,l=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return Wv.box(Wv.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,a>>8&255,255&a,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]),o,Wv.box(Wv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Wv.box(Wv.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}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 Wv.box(Wv.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]),Wv.box(Wv.types.esds,Wv.esds(e)))}static mp3(e){const t=e.samplerate;return Wv.box(Wv.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?Wv.box(Wv.types.stsd,Wv.STSD,Wv.mp3(e)):Wv.box(Wv.types.stsd,Wv.STSD,Wv.mp4a(e)):Wv.box(Wv.types.stsd,Wv.STSD,Wv.avc1(e))}static tkhd(e){const t=e.id,n=e.duration*e.timescale,r=e.width,s=e.height,i=Math.floor(n/(zv+1)),o=Math.floor(n%(zv+1));return Wv.box(Wv.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,o>>24,o>>16&255,o>>8&255,255&o,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=Wv.sdtp(e),r=e.id,s=Math.floor(t/(zv+1)),i=Math.floor(t%(zv+1));return Wv.box(Wv.types.traf,Wv.box(Wv.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Wv.box(Wv.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])),Wv.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Wv.box(Wv.types.trak,Wv.tkhd(e),Wv.mdia(e))}static trex(e){const t=e.id;return Wv.box(Wv.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 o,a,l,c,u,d;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),o=0;o<r;o++)a=n[o],l=a.duration,c=a.size,u=a.flags,d=a.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,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*o);return Wv.box(Wv.types.trun,i)}static initSegment(e){Wv.types||Wv.init();const t=Wv.moov(e),n=new Uint8Array(Wv.FTYP.byteLength+t.byteLength);return n.set(Wv.FTYP),n.set(t,Wv.FTYP.byteLength),n}}Wv.types=void 0,Wv.HDLR_TYPES=void 0,Wv.STTS=void 0,Wv.STSC=void 0,Wv.STCO=void 0,Wv.STSZ=void 0,Wv.VMHD=void 0,Wv.SMHD=void 0,Wv.STSD=void 0,Wv.FTYP=void 0,Wv.DINF=void 0;function Yv(e,t,n=1,r=!1){const s=e*t*n;return r?Math.round(s):s}function Qv(e,t=!1){return Yv(e,1e3,1/9e4,t)}let Xv,Jv=null,Zv=null;class eb{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===Jv){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jv=e?parseInt(e[1]):0}if(null===Zv){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Zv=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){Hp.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){Hp.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Hp.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,tb(e,n.pts)):r>0?e:n.pts}),e[0].pts);return t&&Hp.debug("PTS rollover detected"),n}remux(e,t,n,r,s,i,o,a){let l,c,u,d,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=o&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||o){this.ISGenerated||(u=this.generateIS(e,t,s,i));const n=this.isVideoContiguous;let r,o=-1;if(w&&(o=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,o>0){Hp.warn(`[mp4-remuxer]: Dropped ${o} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(o),t.dropped+=o,g+=(t.samples[0].pts-e)/t.inputTimeScale,r=g}else-1===o&&(Hp.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=(tb(e.samples[0].pts,n)-n)/t.inputTimeScale;p+=Math.max(0,r),g+=Math.max(0,-r)}if(b){if(e.samplerate||(Hp.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||a===Dm?g:void 0),w){const r=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(Hp.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=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=o,l.independent=-1!==o,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(h=nb(n,s,this._initPTS,this._initDTS)),r.samples.length&&(d=rb(r,s,this._initPTS))),{audio:c,video:l,initSegment:u,independent:f,text:d,id3:h}}generateIS(e,t,n,r){const s=e.samples,i=t.samples,o=this.typeSupported,a={},l=this._initPTS;let c,u,d,h=!l||r,f="audio/mp4";if(h&&(c=u=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)o.mpeg?(f="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");a.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):Wv.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(d=e.inputTimeScale,l&&d===l.timescale?h=!1:c=u=s[0].pts-Math.round(d*n))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,a.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Wv.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(d=t.inputTimeScale,l&&d===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(d*n);u=Math.min(u,tb(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(a).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:d},this._initDTS={baseTime:u,timescale:d}):c=d=void 0,{tracks:a,initPTS:c,timescale:d}}remuxVideo(e,t,n,r){const s=e.inputTimeScale,i=e.samples,o=[],a=i.length,l=this._initPTS;let c,u,d=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!n||null===d){d=t*s-(i[0].pts-tb(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<a;e++){const t=i[e];t.pts=tb(t.pts-y,d),t.dts=tb(t.dts-y,d),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,u=i[i.length-1].dts;const v=u-c,b=v?Math.round(v/(a-1)):f||e.inputTimeScale/30;if(n){const e=c-d,t=e>b,n=e<-1;if((t||n)&&(t?Hp.warn(`AVC: ${Qv(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):Hp.warn(`AVC: ${Qv(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!n||d>=i[0].pts)){c=d;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,Hp.log(`Video: First PTS/DTS adjusted: ${Qv(t,!0)}/${Qv(c,!0)}, delta: ${Qv(e,!0)} ms`)}}c=Math.max(0,c);let w=0,E=0;for(let e=0;e<a;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;E+=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)}u=i[a-1].dts;const S=E+4*w+8;let C;try{C=new Uint8Array(S)}catch(e){return void this.observer.emit(Np.ERROR,Np.ERROR,{type:Bp.MUX_ERROR,details:jp.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating video mdat ${S}`})}const T=new DataView(C.buffer);T.setUint32(0,S),C.set(Wv.types.mdat,4);let k=!1,_=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,R=Number.NEGATIVE_INFINITY;for(let e=0;e<a;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,C.set(r,h),h+=s,c+=4+s}if(e<a-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const n=this.config,o=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-o,f<0?f=o:k=!0,Hp.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}const u=Math.round(t.pts-t.dts);_=Math.min(_,f),A=Math.max(A,f),I=Math.min(I,l),R=Math.max(R,l),o.push(new sb(t.key,f,c,u))}if(o.length)if(Jv){if(Jv<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Zv&&R-I<A-_&&b/A<.025&&0===o[0].cts){Hp.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=o.length;t<n;t++){const r=e+o[t].duration,s=e+o[t].cts;if(t<n-1){const e=r+o[t+1].cts;o[t].duration=e-s}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=r}}f=k||!f?b:f,this.nextAvcDts=d=u+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const L={data1:Wv.moof(e.sequenceNumber++,c,Fp({},e,{samples:o})),data2:C,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,L}remuxAudio(e,t,n,r,s){const i=e.inputTimeScale,o=i/(e.samplerate?e.samplerate:i),a="aac"===e.segmentCodec?1024:1152,l=a*o,c=this._initPTS,u="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==s;let f=e.samples,p=u?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(tb(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=tb(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],o=s.pts,a=o-r,c=Math.abs(1e3*a/i);if(a<=-t*l&&h)0===n&&(Hp.warn(`Audio frame @ ${(o/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*a/i)} ms.`),this.nextAudioPts=g=r=o);else if(a>=t*l&&c<1e4&&h){let t=Math.round(a/l);r=o-t*l,r<0&&(t--,r+=l),0===n&&(this.nextAudioPts=g=r),Hp.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/i).toFixed(3)}s due to ${Math.round(1e3*a/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(r,0);let i=Vv.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(Hp.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,E=0,S=f.length;for(;S--;)E+=f[S].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){d[t-1].duration=Math.round((i-w)/o)}else{if(n&&"aac"===e.segmentCodec&&(i=g),b=i,!(E>0))return;E+=p;try{v=new Uint8Array(E)}catch(e){return void this.observer.emit(Np.ERROR,Np.ERROR,{type:Bp.MUX_ERROR,details:jp.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!u){new DataView(v.buffer).setUint32(0,E),v.set(Wv.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,d.push(new sb(!0,a,l,0)),w=i}const C=d.length;if(!C)return;const T=d[d.length-1];this.nextAudioPts=g=w+o*T.duration;const k=u?new Uint8Array(0):Wv.moof(e.sequenceNumber++,b/o,Fp({},e,{samples:d}));e.samples=[];const _=b/i,I=g/i,A={data1:k,data2:v,startPTS:_,endPTS:I,startDTS:_,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,A}remuxEmptyAudio(e,t,n,r){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),o=this.nextAudioPts,a=this._initDTS,l=9e4*a.baseTime/a.timescale,c=(null!==o?o:r.startDTS*s)+l,u=r.endDTS*s+l,d=1024*i,h=Math.ceil((u-c)/d),f=Vv.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(Hp.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Hp.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*d;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,n,!1)}}function tb(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 nb(e,t,n,r){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let o=0;o<s;o++){const s=e.samples[o];s.pts=tb(s.pts-n.baseTime*i/n.timescale,t*i)/i,s.dts=tb(s.dts-r.baseTime*i/r.timescale,t*i)/i}const o=e.samples;return e.samples=[],{samples:o}}function rb(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=tb(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 sb{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 ib(e)}}class ib{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 ob(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===Zp?"avc1.42e01e":"mp4a.40.5"}try{Xv=self.performance.now.bind(self.performance)}catch(e){Hp.debug("Unable to use Performance API on this environment"),Xv="undefined"!=typeof self&&self.Date.now}const ab=[{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=pv("video",1),i=this.audioTrack=pv("audio",1),o=this.txtTrack=pv("text",1);if(this.id3Track=pv("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const a=Vg(e);if(a.video){const{id:e,timescale:t,codec:n}=a.video;s.id=e,s.timescale=o.timescale=t,s.codec=n}if(a.audio){const{id:e,timescale:t,codec:n}=a.audio;i.id=e,i.timescale=t,i.codec=n}o.id=Ng.text,s.sampleDuration=0,s.duration=i.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Gg(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=Yg(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},n=Gg(e,["moof"]);if(!n)return t;if(n.length<2)return t.remainder=e,t;const r=n[n.length-1];return t.valid=vg(e,0,r.byteOffset-8),t.remainder=vg(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=Qg(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=Qg(e,t),{videoTrack:t,audioTrack:pv(),id3Track:r,textTrack:pv()}}extractID3Track(e,t){const n=this.id3Track;if(e.samples.length){const r=Gg(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let n="",r="",s=0,i=0,o=0,a=0,l=0,c=0;if(0===t){for(;"\0"!==Bg(e.subarray(c,c+1));)n+=Bg(e.subarray(c,c+1)),c+=1;for(n+=Bg(e.subarray(c,c+1)),c+=1;"\0"!==Bg(e.subarray(c,c+1));)r+=Bg(e.subarray(c,c+1)),c+=1;r+=Bg(e.subarray(c,c+1)),c+=1,s=$g(e,12),i=$g(e,16),a=$g(e,20),l=$g(e,24),c=28}else if(1===t){c+=4,s=$g(e,c),c+=4;const t=$g(e,c);c+=4;const i=$g(e,c);for(c+=4,o=2**32*t+i,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,Hp.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=$g(e,c),c+=4,l=$g(e,c),c+=4;"\0"!==Bg(e.subarray(c,c+1));)n+=Bg(e.subarray(c,c+1)),c+=1;for(n+=Bg(e.subarray(c,c+1)),c+=1;"\0"!==Bg(e.subarray(c,c+1));)r+=Bg(e.subarray(c,c+1)),c+=1;r+=Bg(e.subarray(c,c+1)),c+=1}return{schemeIdUri:n,value:r,timeScale:s,presentationTime:o,presentationTimeDelta:i,eventDuration:a,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(kv.test(r.schemeIdUri)){const e=Up(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:qm,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&&Gg(e,["moov","trak"]).forEach((e=>{const t=Gg(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=Gg(t,["enca"]);const s=r.length>0;s||(r=Gg(t,["encv"])),r.forEach((e=>{Gg(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=zg(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(Hp.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Mg(e)} -> ${Mg(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=Vg(e);t||(t=ob(r.audio,Jp)),n||(n=ob(r.video,Zp));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"}:Hp.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,n,r,s,i){var o,a;let{initPTS:l,lastEndTime:c}=this;const u={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};Up(c)||(c=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return u;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(o=f)&&o.length||(this.generateInitSegment(d),f=this.initData),null==(a=f)||!a.length)return Hp.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let n=0,r=0,s=0;const i=Gg(e,["moof","traf"]);for(let e=0;e<i.length;e++){const o=i[e],a=Gg(o,["tfhd"])[0],l=t[$g(a,4)];if(!l)continue;const c=l.default,u=$g(a,0)|(null==c?void 0:c.flags);let d=null==c?void 0:c.duration;8&u&&(d=$g(a,2&u?12:8));const h=l.timescale||9e4,f=Gg(o,["trun"]);for(let e=0;e<f.length;e++)n=Wg(f[e]),!n&&d&&(n=d*$g(f[e],4)),l.type===Zp?r+=n/h:l.type===Jp&&(s+=n/h)}if(0===r&&0===s){let t=0;const n=Gg(e,["sidx"]);for(let e=0;e<n.length;e++){const r=Hg(n[e]);null!=r&&r.references&&(t+=r.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return r||s}(d,f),g=function(e,t){return Gg(t,["moof","traf"]).reduce(((t,n)=>{const r=Gg(n,["tfdt"])[0],s=r[0],i=Gg(n,["tfhd"]).reduce(((t,n)=>{const i=$g(n,4),o=e[i];if(o){let e=$g(r,4);if(1===s){if(e===Fg)return Hp.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=Fg+1,e+=$g(r,8)}const n=e/(o.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,d),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&&Hp.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){Gg(t,["moof","traf"]).forEach((t=>{Gg(t,["tfhd"]).forEach((r=>{const s=$g(r,4),i=e[s];if(!i)return;const o=i.timescale||9e4;Gg(t,["tfdt"]).forEach((e=>{const t=e[0];let r=$g(e,4);if(0===t)r-=n*o,r=Math.max(r,0),Kg(e,4,r);else{r*=Math.pow(2,32),r+=$g(e,8),r-=n*o,r=Math.max(r,0);const t=Math.floor(r/(Fg+1)),s=Math.floor(r%(Fg+1));Kg(e,4,t),Kg(e,8,s)}}))}))}))}(f,d,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(Hp.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,w=!!f.video;let E="";b&&(E+="audio"),w&&(E+="video");const S={data1:d,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:E,hasAudio:b,hasVideo:w,nb:1,dropped:0};return u.audio="audio"===S.type?S:void 0,u.video="audio"!==S.type?S:void 0,u.initSegment=h,u.id3=nb(n,s,l,l),r.samples.length&&(u.text=rb(r,s,l)),u}}},{demux:Bv,remux:eb},{demux:class extends gv{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=(Eg(e,0)||[]).length;for(let n=e.length;t<n;t++)if(Ev(e,t))return Hp.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)&&yv(e,t)&&bv(e,t)<=e.length-t}(e,t)}appendFrame(e,t,n){Sv(e,this.observer,t,n,e.manifestCodec);const r=Tv(e,t,n,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:eb},{demux:class extends gv{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=(Eg(e,0)||[]).length;for(let n=e.length;t<n;t++)if(Mv(e,t))return Hp.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return xv(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,n){if(null!==this.basePTS)return Dv(e,t,n,this.basePTS,this.frameIndex)}},remux:eb}];class lb{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=Xv();let i=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:a}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:c,trackSwitch:u,accurateTimeOffset:d,timeOffset:h,initSegmentChange:f}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=a,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=Xv(),cb(n);i=new Uint8Array(t)}}const w=this.needsProbing(c,u);if(w){const e=this.configureTransmuxer(i);if(e)return Hp.warn(`[transmuxer] ${e.message}`),this.observer.emit(Np.ERROR,Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=Xv(),cb(n)}(c||u||f||w)&&this.resetInitSegment(v,p,g,y,t),(c||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const E=this.transmux(i,b,h,d,n),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,s.executeEnd=Xv(),E}flush(e){const t=e.transmuxing;t.executeStart=Xv();const{decrypter:n,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:o}=r;if(n){const t=n.flush();t&&i.push(this.push(t,null,e))}const{demuxer:a,remuxer:l}=this;if(!a||!l)return t.executeEnd=Xv(),[cb(e)];const c=a.flush(o);return ub(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:o}=t,{accurateTimeOffset:a,timeOffset:l}=this.currentTransmuxState;Hp.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,o,l,a,!0,this.id);e.push({remuxResult:c,chunkMeta:n}),n.transmuxing.executeEnd=Xv()}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:o}=this;i&&o&&(i.resetInitSegment(e,t,n,r),o.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:o,textTrack:a}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,o,a,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=ab.length;t<n;t++)if(ab[t].demux.probe(e)){i=ab[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,a=this.remuxer,l=i.remux,c=i.demux;a&&a instanceof l||(this.remuxer=new l(n,t,r,s)),o&&o 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 Jy(this.config)),e}}const cb=e=>({remuxResult:{},chunkMeta:e});function ub(e){return"then"in e&&e.then instanceof Function}class db{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 hb{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 fb={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,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,i||e,o),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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,o=new Array(i);s<i;s++)o[s]=r[s].fn;return o},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,s,i,o){var a=n?n+e:e;if(!this._events[a])return!1;var l,c,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,s),!0;case 5:return u.fn.call(u.context,t,r,s,i),!0;case 6:return u.fn.call(u.context,t,r,s,i,o),!0}for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var h,f=u.length;for(c=0;c<f;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),d){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,r);break;case 4:u[c].fn.call(u[c].context,t,r,s);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u[c].fn.apply(u[c].context,l)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,s){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||r&&a.context!==r||o(this,i);else{for(var l=0,c=[],u=a.length;l<u;l++)(a[l].fn!==t||s&&!a[l].once||r&&a[l].context!==r)&&c.push(a[l]);c.length?this._events[i]=1===c.length?c[0]:c:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(fb);var pb=Lp(fb.exports);const gb=cm()||{isTypeSupported:()=>!1};class mb{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===Np.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new pb,this.observer.on(Np.FRAG_DECRYPTED,i),this.observer.on(Np.ERROR,i);const o={mp4:gb.isTypeSupported("video/mp4"),mpeg:gb.isTypeSupported("audio/mpeg"),mp3:gb.isTypeSupported('audio/mp4; codecs="mp3"')},a=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(Hp.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)):(Hp.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,Hp.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(Np.ERROR,{type:Bp.OTHER_ERROR,details:jp.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:n})},e.postMessage({cmd:"init",typeSupported:o,vendor:a,id:t,config:JSON.stringify(s)})}catch(e){Hp.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new lb(this.observer,o,s,a,t)}return}}this.transmuxer=new lb(this.observer,o,s,a,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,o,a,l,c){var u,d;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),E=!y&&(1===v||0===v&&(1===b||w&&b<=0)),S=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=S),!i||!b&&E||(i.stats.parsing.start=S);const C=!(g&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=g.initSegment)?void 0:d.url)),T=new hb(m,E,a,y,f,C);if(!E||m||C){Hp.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: ${E}\n accurateTimeOffset: ${a}\n timeOffset: ${f}\n initSegmentChange: ${C}`);const e=new db(n,r,t,o,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);ub(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);ub(n)||t.async?(ub(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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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":Hp[t.data.logType]&&Hp[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 yb{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:o}=r,a=this.seeking&&!o,l=!this.seeking&&o;if(this.seeking=o,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;Hp.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||a)return void(this.stalled=null);if(r.paused&&!o||r.ended||0===r.playbackRate||!qy.getBuffered(r).length)return;const c=qy.bufferInfo(r,i,0),u=c.len>0,d=c.nextStart||0;if(!u&&!d)return;if(o){const e=c.len>2,n=!d||t&&t.start<=i||d-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(d,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(!o&&p>=250&&(this._reportStall(c),!this.media))return;const g=qy.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,o=r.getPartialFragment(i);if(o){if(this._trySkipBufferHole(o)||!this.media)return}(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-i<n.maxBufferHole)&&t>1e3*n.highBufferWatchdogPeriod&&(Hp.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)})`);Hp.warn(r.message),t.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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=qy.bufferInfo(r,s,0),o=s<i.start?i.start:i.nextStart;if(o){const a=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&r.readyState<3,c=o-s;if(c>0&&(a||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let n=!1;if(0===s){const e=t.getAppendedFrag(0,Lm);e&&o<e.end&&(n=!0)}if(!n){const n=e||t.getAppendedFrag(s,Lm);if(n){let e=!1,r=n.end;for(;r<o;){const n=t.getPartialFragment(r);if(!n){e=!0;break}r+=n.duration}if(e)return 0}}}const i=Math.max(o+.05,s+.1);if(Hp.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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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,o=new Error(`Nudging 'currentTime' from ${s} to ${i}`);Hp.warn(o.message),n.currentTime=i,t.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);Hp.error(n.message),t.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}class vb extends hv{constructor(e,t,n){super(e,t,n,"[stream-controller]",Lm),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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.LEVEL_LOADING,this.onLevelLoading,this),e.on(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Np.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Np.ERROR,this.onError,this),e.on(Np.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Np.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Np.BUFFER_CREATED,this.onBufferCreated,this),e.on(Np.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Np.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Np.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Np.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Np.ERROR,this.onError,this),e.off(Np.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Np.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Np.BUFFER_CREATED,this.onBufferCreated,this),e.off(Np.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Np.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Np.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=tv,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=ev}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case dv:{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=tv;break}if(this.hls.nextLoadLevel!==this.level){this.state=tv;break}break}case sv:{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=tv)}}this.state===tv&&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 o=n[i],a=this.getMainFwdBufferInfo();if(null===a)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(Np.BUFFER_EOS,e),void(this.state=lv)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=o.details;if(!c||this.state===dv||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=dv);const u=a.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Dy){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&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?Jp:Zp,t=(e===Zp?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Lm)}f=this.getNextFragmentLoopLoading(f,c,a,Lm,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,o,h))}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===Ay||r===Ly?"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,Lm)}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 nv:case rv:case sv:case ov:case av:this.state=tv}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 yb(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;Up(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(Np.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=fv();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!==tv)return;const r=n[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=dv)}onLevelLoaded(e,t){var n;const{levels:r}=this,s=t.level,i=t.details,o=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:${o}`);const a=r[s],l=this.fragCurrent;!l||this.state!==rv&&this.state!==sv||l.level===t.level&&l.urlId===a.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(n=a.details)&&n.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,a.details)}if(a.details=i,this.levelLastLoaded=s,this.hls.trigger(Np.LEVEL_UPDATED,{details:i,level:s}),this.state===dv){if(this.waitForCdnTuneIn(i))return;this.state=tv}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 o=i[n.level],a=o.details;if(!a)return this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),void this.fragmentTracker.removeFragment(n);const l=o.videoCodec,c=a.PTSKnown||!a.live,u=null==(t=n.initSegment)?void 0:t.data,d=this._getAudioCodec(o),h=this.transmuxer=this.transmuxer||new mb(this.hls,Lm,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,p=-1!==f,g=new Ky(n.level,n.sn,n.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[n.cc];h.push(s,u,d,l,n,r,a.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(Np.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(Np.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!==Lm)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===av&&(this.state=tv));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=cv;else switch(t.details){case jp.FRAG_GAP:case jp.FRAG_PARSING_ERROR:case jp.FRAG_DECRYPT_ERROR:case jp.FRAG_LOAD_ERROR:case jp.FRAG_LOAD_TIMEOUT:case jp.KEY_LOAD_ERROR:case jp.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Lm,t);break;case jp.LEVEL_LOAD_ERROR:case jp.LEVEL_LOAD_TIMEOUT:case jp.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==dv||(null==(n=t.context)?void 0:n.type)!==Im||(this.state=tv);break;case jp.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case jp.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!qy.getBuffered(e).length){const e=this.state!==tv?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=tv,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Jp||this.audioOnly&&!this.altAudio){const e=(t===Zp?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,Lm)}}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=qy.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=tv,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(Np.FRAG_LOADED,n),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const n="main",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{video:u,text:d,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=ov,f){if(null!=f&&f.tracks){const e=a.initSegment||a;this._bufferInitSegment(c,f.tracks,e,i),r.trigger(Np.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Up(e)&&(this.initPTS[a.cc]={baseTime:e,timescale:t},r.trigger(Np.INIT_PTS_FOUND,{frag:a,id:n,initPTS:e,timescale:t}))}if(u&&p&&"initSegment"!==a.sn){const e=p.fragments[a.sn-1-p.startSN],t=a.sn===p.startSN,n=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:o}=u;if(l)l.elementaryStreams[u.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:o};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!n&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!n)return void this.backtrack(a);n&&(a.gap=!0),a.setElementaryStreamInfo(u.type,a.start,r,a.start,o,!0)}a.setElementaryStreamInfo(u.type,e,r,s,o),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,l,i,t||n)}else{if(!t&&!n)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=g;l&&(l.elementaryStreams[Jp]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),a.setElementaryStreamInfo(Jp,e,t,n,r),this.bufferFragmentData(g,a,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:n,frag:a,details:p,samples:h.samples};r.trigger(Np.FRAG_PARSING_METADATA,e)}if(p&&d){const e={id:n,frag:a,details:p,samples:d.samples};r.trigger(Np.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,n,r){if(this.state!==ov)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:o}=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}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(Np.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(Np.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,Lm)}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=tv}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const n=e.currentTime;if(qy.isBuffered(e,n)?t=this.getAppendedFrag(n):qy.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(Np.FRAG_CHANGED,{frag:t}),e&&e.level===n||this.hls.trigger(Np.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&&Up(t)&&Up(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 bb{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 wb{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 bb(e),this.fast_=new bb(t),this.defaultTTFB_=r,this.ttfb_=new bb(e)}update(e,t){const{slow_:n,fast_:r,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new bb(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new bb(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new bb(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 Eb{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 Sb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Cb(e[n].attrs,t[n].attrs))return!1;return!0}function Cb(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 Tb{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 kb(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 _b{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){Hp.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 Ib=cm(),Ab=/([ha]vc.)(?:\.[^.,]+)+/;const Rb={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},Lb=function(e){let t=e;return Rb.hasOwnProperty(e)&&(t=Rb[e]),String.fromCharCode(t)},Db=15,Ob=100,xb={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Pb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Mb={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Fb={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ub=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Nb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const n="function"==typeof t?t():t;Hp.log(`${this.time} [${e}] ${n}`)}}}const Bb=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t};class jb{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 $b{constructor(e,t,n,r,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new jb(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 qb{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<Ob;e++)this.chars.push(new $b);this.logger=e,this.pos=0,this.currPenState=new jb}equals(e){let t=!0;for(let n=0;n<Ob;n++)if(!this.chars[n].equals(e.chars[n])){t=!1;break}return t}copy(e){for(let t=0;t<Ob;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ob;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>Ob&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ob)}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=Lb(e);this.pos>=Ob?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<Ob;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<Ob;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 Kb{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<Db;t++)this.rows.push(new qb(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<Db;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<Db;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<Db;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Db;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<Db;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<Db;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 Gb{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 Kb(n),this.nonDisplayedMemory=new Kb(n),this.lastOutputScreen=new Kb(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 Hb{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const r=new Nb;this.channels=[null,new Gb(e,t,r),new Gb(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,"["+Bb([t[e],t[e+1]])+"] -> ("+Bb([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 "+Bb([r,s])+" orig: "+Bb([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(zb(e,t,n))return Vb(null,null,n),this.logger.log(3,"Repeated command ("+Bb([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),Vb(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 ("+Bb([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(zb(e,t,r))return Vb(null,null,r),!0;const s=e<=23?1:2;n=t>=64&&t<=95?1===s?xb[e]:Mb[e]:1===s?Pb[e]:Fb[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(n,t)),Vb(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 '"+Lb(e)+"' in channel "+n),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);if(r){const n=Bb(r);this.logger.log(3,"Char codes = "+n.join(",")),Vb(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=Ub[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),Vb(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 Vb(e,t,n){n.a=e,n.b=t}function zb(e,t,n){return n.a===e&&n.b===t}class Wb{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 Yb=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,o){const a=this,l={enumerable:!0};a.hasBeenReset=!1;let c="",u=!1,d=t,h=i,f=o,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",E=50,S="middle";Object.defineProperty(a,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(a,"pauseOnExit",s({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(a,"startTime",s({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"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(a,"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(a,"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(a,"size",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"align",s({},l,{get:function(){return S},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),a.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class Qb{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Xb(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 Jb{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 Zb(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 ew=new Yb(0,0,""),tw="middle"===ew.align?"middle":"center";function nw(e,t,n){const r=e;function s(){const t=Xb(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 Jb;Zb(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",tw,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",tw,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",tw,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===ew.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",tw);let i=r.get("position","auto");"auto"===i&&50===ew.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function rw(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class sw{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Qb,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=rw(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)?Zb(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 Yb(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{nw(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 iw=/\r\n|\n\r|\n|\r/g,ow=function(e,t,n=0){return e.slice(n,n+t.length)===t},aw=function(e){let t=5381,n=e.length;for(;n;)t=33*t^e.charCodeAt(--n);return(t>>>0).toString()};function lw(e,t,n){return aw(e.toString())+aw(t.toString())+aw(n)}function cw(e,t,n,r,s,i,o){const a=new sw,l=Og(new Uint8Array(e)).trim().replace(iw,"\n").split("\n"),c=[],u=t?function(e,t=1){return Yv(e,9e4,1/t)}(t.baseTime,t.timescale):0;let d,h="00:00.000",f=0,p=0,g=!0;a.oncue=function(e){const i=n[r];let o=n.ccOffset;const a=(f-u)/9e4;if(null!=i&&i.new&&(void 0!==p?o=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,a)),a){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));o=a-n.presentationOffset}const l=e.endTime-e.startTime,h=tb(9e4*(e.startTime+o-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=lw(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},a.onparsingerror=function(e){d=e},a.onflush=function(){d?o(d):i(c)},l.forEach((e=>{if(g){if(ow(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{ow(e,"LOCAL:")?h=e.slice(6):ow(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(!(Up(t)&&Up(n)&&Up(r)&&Up(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=6e4*r,t+=36e5*s,t}(h)/1e3}catch(e){d=e}return}""===e&&(g=!1)}a.parse(e+"\n")})),a.flush()}const uw="stpp.ttml.im1t",dw=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,hw=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,fw={left:"start",center:"center",right:"end",start:"start",end:"end"};function pw(e,t,n,r){const s=Gg(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>Og(e))),o=function(e,t,n=1,r=!1){return Yv(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)),{}),o="preserve"!==r.getAttribute("xml:space"),a=mw(gw(r,"styling","style")),l=mw(gw(r,"layout","region")),c=gw(r,"body","[begin]");return[].map.call(c,(e=>{const n=yw(e,o);if(!n||!e.hasAttribute("begin"))return null;const r=ww(e.getAttribute("begin"),i),s=ww(e.getAttribute("dur"),i);let c=ww(e.getAttribute("end"),i);if(null===r)throw bw(e);if(null===c){if(null===s)throw bw(e);c=r+s}const u=new Yb(r-t,c-t,n);u.id=lw(u.startTime,u.endTime,u.text);const d=function(e,t,n){const r="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;o&&n.hasOwnProperty(o)&&(s=n[o]);return i.reduce(((n,i)=>{const o=vw(t,r,i)||vw(e,r,i)||vw(s,r,i);return o&&(n[i]=o),n}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:h}=d;if(h){const e=fw[h];e&&(u.lineAlign=e),u.align=h}return Fp(u,d),u})).filter((e=>null!==e))}(e,o))))}catch(e){r(e)}}function gw(e,t,n){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function mw(e){return e.reduce(((e,t)=>{const n=t.getAttribute("xml:id");return n&&(e[n]=t),e}),{})}function yw(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?yw(n,t):t?e+n.textContent.trim().replace(/\s+/g," "):e+n.textContent}),"")}function vw(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function bw(e){return new Error(`Could not parse ttml timestamp ${e}`)}function ww(e,t){if(!e)return null;let n=Xb(e);return null===n&&(dw.test(e)?n=function(e,t){const n=dw.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):hw.test(e)&&(n=function(e,t){const n=hw.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 Ew(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class Sw{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(Np.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Np.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Np.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,Sw.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 o=0;o<e.length;o+=1){const a=e[o];if((a.width>=t||a.height>=n)&&(s=a,!(i=e[o+1])||s.width!==i.width||s.height!==i.height)){r=o;break}}var s,i;return r}}const Cw="[eme]";class Tw{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=Tw.CDMCleanupPromise?[Tw.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Hp.debug.bind(Hp,Cw),this.log=Hp.log.bind(Hp,Cw),this.warn=Hp.warn.bind(Hp,Cw),this.error=Hp.error.bind(Hp,Cw),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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Np.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Np.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Np.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Np.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===lg.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 o=e.shift();this.getMediaKeysPromise(o,r,s).then((e=>t({keySystem:o,mediaKeys:e}))).catch((t=>{e.length?i(e):n(t instanceof kw?t:new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.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===yg&&"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 lg.FAIRPLAY:s=["cenc","sinf"];break;case lg.WIDEVINE:case lg.PLAYREADY:s=["cenc"];break;case lg.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: ${Mg(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 Mg(e.keyId)}updateKeySession(e,t){var n;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Mg((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=mg(this.config),s=e.map(fg).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=gg(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 kw?this.hls.trigger(Np.ERROR,e.data):this.hls.trigger(Np.ERROR,{type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[t];if(!n){const t=fg(e.keyFormat),n=t?[t]:mg(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=mg(this.config)),0===e.length)throw new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.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[lg.FAIRPLAY]){const e=Bg(new Uint8Array(n));try{const t=ig(JSON.parse(e).sinf),n=zg(new Uint8Array(t));if(!n)return;r=n.subarray(8,24),s=lg.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=Mg(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===pg&&e.data&&(r=e.data.subarray(8,24)),s=function(e){if(e===pg)return lg.WIDEVINE}(e.systemId)}if(!s||!r)return;const i=Mg(r),{keyIdToKeySessionPromise:o,mediaKeySessions:a}=this;let l=o[i];for(let e=0;e<a.length;e++){const s=a[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const u=Mg(c.keyId);if(i===u||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=o[u],delete o[u],c.pssh=new Uint8Array(n),c.keyId=r,l=o[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,n,"encrypted-event-key-match")));break}}l||(l=o[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var o;this.throwIfDestroyed();const a=new nm("ISO-23001-7",i,null!=(o=gg(e))?o:"");return a.pssh=new Uint8Array(n),a.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:a,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 o=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(o)try{const r=o.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 a;if(this.warn(e.message),null!=(a=this.hls)&&a.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 pb;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===lg.FAIRPLAY&&(this.updateKeySession(e,ag("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 u=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(n=>{n.startsWith("usable")?e():"output-restricted"===n?t(new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===n?t(new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.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 kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).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: ${Mg("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${Mg(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 o={responseType:"arraybuffer",url:r},a=t.certLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,n,r)=>{s(e.data)},onError:(t,n,s,a)=>{i(new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:Pp({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,s)=>{i(new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,n)=>{i(new Error("aborted"))}};n.load(o,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 kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.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 kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.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 o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,o,i,e)}catch(e){this.error(e)}r(t)}else{const a=n.errorRetry,l=a?a.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)s(new kw({type:Bp.KEY_SYSTEM_ERROR,details:jp.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:i,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${i}). Status: ${o.status} (${o.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=o,this.setupLicenseXHR(o,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={},nm.clearKeyUriToKeyIdMap();const n=t.length;Tw.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}`)}))}}}Tw.CDMCleanupPromise=void 0;class kw 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 _w="m",Iw="a",Aw="v",Rw="av",Lw="i",Dw="tt";class Ow{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:_w,su:!this.initialized})}catch(e){Hp.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!==Aw&&r!==Iw&&r!=Rw||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){Hp.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||Ow.uuid(),this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Np.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Np.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={}){Fp(t,this.createData());const n=t.ot===Lw||t.ot===Aw||t.ot===Rw;if(this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const n=Ow.toHeaders(t);if(!Object.keys(n).length)return;e.headers||(e.headers={}),Fp(e.headers,n)}else{const n=Ow.toQuery(t);if(!n)return;e.url=Ow.appendQueryToUri(e.url,n)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Dw:"initSegment"===e.sn?Lw:"audio"===t?Iw:"main"===t?this.hls.audioTracks.length?Aw:Rw:void 0}getTopBandwidth(e){let t,n=0;const r=this.hls;if(e===Iw)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===Iw?this.audioBuffer:this.videoBuffer;if(!n||!t)return NaN;return 1e3*qy.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},o=Object.keys(e||{}).sort();for(const r of o){let s=e[r];if(!n(s))continue;if("v"===r&&1===s)continue;if("pr"==r&&1===s)continue;const o=i[r];o&&(s=o(s));const a=typeof s;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${s}`:"boolean"===a?r:"number"===a?`${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=Ow.serialize(s[e]);t&&(n[`CMCD-${r[e]}`]=t)}return n}static toQuery(e){return`CMCD=${encodeURIComponent(Ow.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const n=e.includes("?")?"&":"?";return`${e}${n}${t}`}}function xw(e,t,n,r){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=Fp({},e);return i.details=void 0,i.attrs=new Wp(i.attrs),i.url=i.attrs.URI=Pw(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 Pw(e,t,n,r){const{HOST:s,PARAMS:i,[n]:o}=r;let a;t&&(a=null==o?void 0:o[t],a&&(e=a));const l=new self.URL(e);return s&&!a&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const Mw=/^age:\s*[\d.]+\s*$/im;class Fw{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 Xp,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&&Up(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,o="arraybuffer"===t.responseType?s.byteLength:s.length;if(n.loaded=n.total=o,n.bwEstimate=8e3*n.total/(n.loading.end-n.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(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;dy(i,n.retry,!1,r)?this.retry(i):(Hp.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(dy(t,this.stats.retry,!0))this.retry(t);else{Hp.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=cy(e,n.retry),n.retry++,Hp.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&&Mw.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 Uw=/(\d+)-(\d+)\/(\d+)/;class Nw{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||Bw,this.controller=new self.AbortController,this.stats=new Xp}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(Fp({},e.headers))};e.rangeEnd&&n.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return n}(e,this.controller.signal),i=n.onProgress,o="arraybuffer"===e.responseType,a=o?"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&&Up(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 a=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-(a-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new jw(t||"fetch, bad network response",e,s)}return r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Uw.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Up(e))return e}const n=e.get("Content-Length");if(n)return parseInt(n)}(s.headers)||r.total,i&&Up(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,i):o?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:o}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[a];l&&(r.loaded=r.total=l);const c={url:o.url,data:s,code:o.status};i&&!Up(t.highWaterMark)&&i(r,e,s,o),n.onSuccess(c,r,e,o)})).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 Eb,o=e.body.getReader(),a=()=>o.read().then((o=>{if(o.done)return i.dataLength&&s(t,n,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=o.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),a()})).catch((()=>Promise.reject()));return a()}}function Bw(e,t){return new self.Request(e.url,t)}class jw extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}}const $w=/\s/,qw={newCue(e,t,n,r){const s=[];let i,o,a,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(i=r.rows[h],a=!0,l=0,c="",!i.isEmpty()){var d;for(let e=0;e<i.chars.length;e++)$w.test(i.chars[e].uchar)&&a?l++:(c+=i.chars[e].uchar,a=!1);i.cueStartTime=t,t===n&&(n+=1e-4),l>=16?l--:l++;const r=rw(c.trim()),f=lw(t,n,r);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(o=new u(t,n,r),o.id=f,o.line=h+1,o.align="left",o.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(o))}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=>Um(e,t)))),s}},Kw=Pp(Pp({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:Fw,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 wb(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Np.FRAG_LOADING,this.onFragLoading,this),e.on(Np.FRAG_LOADED,this.onFragLoaded,this),e.on(Np.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Np.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(Np.FRAG_LOADING,this.onFragLoading,this),e.off(Np.FRAG_LOADED,this.onFragLoaded,this),e.off(Np.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Np.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;Up(r)&&Up(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(),o=t?t.stats:e.stats,a=t?t.duration:e.duration,l=i-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.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 u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(s.playbackRate);if(l<=Math.max(u,a/(2*d)*1e3))return;const h=c.len/d;if(h>=2*a/d)return;const f=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=n,v=m[e.level],b=o.total||Math.max(o.loaded,Math.round(a*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*o.loaded/g));const E=p?1e3*o.loaded/w:0,S=E?(b-o.loaded)/E:8*b/g+u/1e3;if(S<=h)return;const C=E?8*E:g;let T,k=Number.POSITIVE_INFINITY;for(T=e.level-1;T>y;T--){const e=m[T].maxBitrate;if(k=this.getTimeToLoadFrag(u/1e3,C,a*e,!m[T].details),k<h)break}k>=S||k>10*a||(n.nextLoadLevel=T,p?this.bwEstimator.sample(l-Math.min(u,f),o.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),Hp.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: ${S.toFixed(3)} s\n Estimated load time for down switch fragment: ${k.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${Up(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(Np.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:n}){const r=n?n.stats:t.stats;if(t.type===Lm&&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,o=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:o},s.realBitrate=Math.round(8*i/o)}if(t.bitrateTest){const e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(Np.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!==Lm||"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:o}=n,a=t?t.duration:e?e.duration:0,l=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,u=n.mainForwardBufferInfo,d=(u?u.len:0)/l;let h=this.findBestLevel(c,i,r,d,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;Hp.trace(`[abr] ${d?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!d){const e=this.bitrateTestDelay;if(e){f=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,Hp.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,d+f,p,g),Math.max(h,0)}findBestLevel(e,t,n,r,s,i){var o;const{fragCurrent:a,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:u}=this.hls,d=u[c],h=!(null==d||null==(o=d.details)||!o.live),f=null==d?void 0:d.codecSet,p=l?l.duration:a?a.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let o=n;o>=t;o--){const t=u[o];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(o,m),y=Math.max(o,y));continue}-1!==y&&Hp.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${u[y].attrs.CODECS}"; not compatible with "${d.attrs.CODECS}"`);const n=t.details,a=(l?null==n?void 0:n.partTarget:null==n?void 0:n.averagetargetduration)||p;let v;v=o<=c?s*e:i*e;const b=u[o].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*a,void 0===n);if(Hp.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${a.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!Up(w)||h&&!this.bitrateTestDelay||w<r))return o}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;Hp.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Np.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{Hp.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{Hp.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&Hp.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(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.BUFFER_RESET,this.onBufferReset,this),e.on(Np.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Np.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Np.BUFFER_EOS,this.onBufferEos,this),e.on(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Np.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Np.FRAG_PARSED,this.onFragParsed,this),e.on(Np.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.BUFFER_RESET,this.onBufferReset,this),e.off(Np.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Np.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Np.BUFFER_EOS,this.onBufferEos,this),e.off(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Np.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Np.FRAG_PARSED,this.onFragParsed,this),e.off(Np.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new _b(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,Hp.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const n=this.media=t.media;if(n&&Ib){const e=this.mediaSource=new Ib;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(Hp.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){Hp.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()):Hp.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(Np.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){Hp.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:o,metadata:a}=t[e],l=(n.levelCodec||n.codec).replace(Ab,"$1"),c=(i||s).replace(Ab,"$1");if(l!==c){const t=`${o};codecs=${i||s}`;this.appendChangeType(e,t),Hp.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:n.buffer,codec:s,container:o,levelCodec:i,metadata:a,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&&(Hp.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{Hp.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:o,frag:a,part:l,chunkMeta:c}=t,u=c.buffering[o],d=self.performance.now();u.start=d;const h=a.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=d),f&&0===f.start&&(f.start=d);const p=s.audio;let g=!1;"audio"===o&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=a.start,y={execute:()=>{if(u.executeStart=self.performance.now(),g){const e=this.sourceBuffer[o];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(Hp.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${a.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,o)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();u.executeEnd=u.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]=qy.getBuffered(t[e]);this.appendError=0,this.hls.trigger(Np.BUFFER_APPENDED,{type:o,frag:a,part:l,chunkMeta:c,parent:a.type,timeRanges:n})},onError:e=>{Hp.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,e);const t={type:Bp.MEDIA_ERROR,parent:a.type,details:jp.BUFFER_APPEND_ERROR,frag:a,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=jp.BUFFER_FULL_ERROR:(this.appendError++,t.details=jp.BUFFER_APPEND_ERROR,this.appendError>n.config.appendErrorMaxRetry&&(Hp.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),n.trigger(Np.ERROR,t)}};r.append(y,o)}onBufferFlushing(e,t){const{operationQueue:n}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Np.BUFFER_FLUSHED,{type:e})},onError:t=>{Hp.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[eg]?s.push("audiovideo"):(i[Jp]&&s.push("audio"),i[Zp]&&s.push("video"));0===s.length&&Hp.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(Np.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})}),s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){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,Hp.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0)&&(Hp.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?(Hp.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&Hp.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(!Up(i)||i<0)return;const o=n.currentTime,a=t.levelTargetDuration,l=Math.max(i,a),c=Math.floor(o/a)*a-l;s.forEach((n=>{const s=r[n];if(s){const r=qy.getBuffered(s);if(r.length>0&&c>r.start(0)){if(e.trigger(Np.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(Np.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&r.end(r.length-1)-o<2*a)return void Hp.info(`[buffer-controller]: Cannot flush ${n} back buffer while SourceBuffer is in ended state`);e.trigger(Np.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,o=Up(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(Hp.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(e)):(s>o&&s>i||!Up(i))&&(Hp.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(Np.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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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,o=`${s.container};codecs=${i}`;Hp.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const e=t[r]=n.addSourceBuffer(o),a=r;this.addBufferListener(a,"updatestart",this._onSBUpdateStart),this.addBufferListener(a,"updateend",this._onSBUpdateEnd),this.addBufferListener(a,"error",this._onSBUpdateError),this.tracks[r]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){Hp.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:o})}}}_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`);Hp.error(`[buffer-controller]: ${n}`,t),this.hls.trigger(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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:o}=this,a=o[e];if(!r||!s||!a)return Hp.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=Up(r.duration)?r.duration:1/0,c=Up(s.duration)?s.duration:1/0,u=Math.max(0,t),d=Math.min(n,l,c);d>u&&!a.ending?(a.ended=!1,Hp.log(`[buffer-controller]: Removing [${u},${d}] from the ${e} SourceBuffer`),a.remove(u,d)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:n,sourceBuffer:r}=this,s=r[t];if(!s)return Hp.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 Hp.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:Sw,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=Hp.log.bind(Hp,"[info]:"),this.warn=Hp.warn.bind(Hp,"[warning]:"),this.error=Hp.error.bind(Hp,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Np.ERROR,this.onError,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Np.ERROR,this.onError,this),e.off(Np.ERROR,this.onErrorOut,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.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)===Lm?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 jp.FRAG_LOAD_ERROR:case jp.FRAG_LOAD_TIMEOUT:case jp.KEY_LOAD_ERROR:case jp.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case jp.FRAG_PARSING_ERROR:if(null!=(n=t.frag)&&n.gap)return void(t.errorAction={action:my,flags:by});case jp.FRAG_GAP:case jp.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=yy);case jp.LEVEL_EMPTY_ERROR:case jp.LEVEL_PARSING_ERROR:{var o,a;const e=t.parent===Lm?t.level:s.loadLevel;t.details===jp.LEVEL_EMPTY_ERROR&&null!=(o=t.context)&&null!=(a=o.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case jp.LEVEL_LOAD_ERROR:case jp.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case jp.AUDIO_TRACK_LOAD_ERROR:case jp.AUDIO_TRACK_LOAD_TIMEOUT:case jp.SUBTITLE_LOAD_ERROR:case jp.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===Am&&i.groupId===e.audioGroupId||i.type===Rm&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=yy,void(t.errorAction.flags=wy)}return;case jp.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],n=null==e?void 0:e.attrs["HDCP-LEVEL"];n&&(t.errorAction={action:yy,flags:Ey,hdcpLevel:n})}return;case jp.BUFFER_ADD_CODEC_ERROR:case jp.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case jp.INTERNAL_EXCEPTION:case jp.BUFFER_APPENDING_ERROR:case jp.BUFFER_APPEND_ERROR:case jp.BUFFER_FULL_ERROR:case jp.LEVEL_SWITCH_ERROR:case jp.BUFFER_STALLED_ERROR:case jp.BUFFER_SEEK_OVER_HOLE:case jp.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:my,flags:by})}if(t.type===Bp.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=ly(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(n=e.response)?void 0:n.code;if(dy(r,s,ay(e),i))return{action:vy,flags:by,retryConfig:r,retryCount:s};const o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,o=ly(e.details.startsWith("key")?i:s,e),a=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){var l;e.details!==jp.FRAG_GAP&&r.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(dy(o,a,ay(e),t))return{action:vy,flags:by,retryConfig:o,retryCount:a}}const c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=a),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:o,loadLevel:a,minAutoLevel:l,maxAutoLevel:c}=n,u=null==(s=e.frag)?void 0:s.type,{type:d,groupId:h}=null!=(i=e.context)?i:{};for(let n=o.length;n--;){const s=(n+a)%o.length;if(s!==a&&s>=l&&s<=c&&0===o[s].loadError){const n=o[s];if(e.details===jp.FRAG_GAP&&e.frag){const t=o[s].details;if(t){const n=fy(e.frag,t.fragments,e.frag.start);if(null!=n&&n.gap)continue}}else{if(d===Am&&h===n.audioGroupId||d===Rm&&h===n.textGroupId)continue;if(u===Dm&&r.audioGroupId===n.audioGroupId||u===Om&&r.textGroupId===n.textGroupId)continue}t=s;break}}if(t>-1&&n.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:yy,flags:by,nextAutoLevel:t}}return{action:yy,flags:wy}}onErrorOut(e,t){var n;switch(null==(n=t.errorAction)?void 0:n.action){case my:break;case yy:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===jp.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 by:this.switchLevel(e,i);break;case wy:n.resolved||(n.resolved=this.redundantFailover(e));break;case Ey:s&&(t.maxHdcpLevel=Wm[Wm.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===Lm?e.level:t.loadLevel,s=t.levels[r],i=s.url.length,o=e.frag?e.frag.urlId:s.urlId;s.urlId!==o||e.frag&&!s.details||this.penalizeRendition(s,e);for(let a=1;a<i;a++){const l=(o+a)%i,c=n[l];if(!c||Sy(c,e,n[o]))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(Np.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Np.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,o=1e3*s/e,a=this.hls;if(a.trigger(Np.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:n}),o>0&&s>a.config.fpsDroppedMonitoringThreshold*i){let e=a.currentLevel;Hp.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===a.autoLevelCapping||a.autoLevelCapping>=e)&&(e-=1,a.trigger(Np.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:a.currentLevel}),a.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:yg,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:qw,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 hv{constructor(e,t,n){super(e,t,n,"[subtitle-stream-controller]",Om),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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Np.ERROR,this.onError,this),e.on(Np.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Np.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Np.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Np.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Np.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Np.ERROR,this.onError,this),e.off(Np.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Np.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Np.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Np.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Np.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Np.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=tv,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=tv,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const o=n.start;for(let e=0;e<s.length;e++)if(o>=s[e].start&&o<=s[e].end){i=s[e];break}const a=n.start+n.duration;i?i.end=a:(i={start:o,end:a},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,Om)}}onFragBuffered(e,t){var n;this.loadedmetadata||t.frag.type!==Lm||null!=(n=this.media)&&n.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const n=t.frag;(null==n?void 0:n.type)===Om&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ev&&(this.state=tv))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){Sb(this.levels,t)?this.levels=t.map((e=>new Zm(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Zm(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Om),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:o}=this;if(!o.length)return;const a=o[i];if(s>=o.length||s!==i||!a)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(n=a.details)&&n.live){const e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;const t=e.fragments[0];a.details?(l=this.alignPlaylists(r,a.details),0===l&&t&&(l=t.start,sy(r,l))):r.hasProgramDateTime&&e.hasProgramDateTime?(Wy(r,e),l=r.fragments[0].start):t&&(l=t.start,sy(r,l))}if(a.details=r,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(a.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===tv){fy(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),a.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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((n=>{const r=performance.now();s.trigger(Np.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=tv}))}}doTick(){if(this.media){if(this.state===tv){const{currentTrackId:e,levels:t}=this,n=t[e];if(!t.length||!n||!n.details)return;const{config:r}=this,s=this.getLoadPosition(),i=qy.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:o,len:a}=i,l=this.getFwdBufferInfo(this.media,Lm),c=n.details;if(a>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const u=c.fragments,d=u.length,h=c.edge;let f=null;const p=this.fragPrevious;if(o<h){const e=r.maxFragLookUpTolerance,t=o>h-e?0:e;f=fy(p,u,Math.max(u[0].start,o),t),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=u[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===Ay&&(f=e)}this.fragmentTracker.getState(f)===Ay&&this.loadFragment(f,n,o)}}else this.state=tv}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 Tb(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Cy{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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.LEVEL_LOADING,this.onLevelLoading,this),e.on(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Np.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Np.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.LEVEL_LOADING,this.onLevelLoading,this),e.off(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Np.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Np.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);kb(this.media.textTracks).forEach((e=>{Nm(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 o=i.details;i.details=t.details,this.log(`subtitle track ${n} loaded [${r.startSN}-${r.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}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(Np.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===Rm&&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(Np.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=kb(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:o}=s;this.hls.trigger(Np.SUBTITLE_TRACK_SWITCH,{id:e,groupId:n,name:r,type:i,url:o});const a=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(a)}else this.hls.trigger(Np.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=kb(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 Wb(this,"textTrack1"),t=new Wb(this,"textTrack2"),n=new Wb(this,"textTrack3"),r=new Wb(this,"textTrack4");this.cea608Parser1=new Hb(1,e,t),this.cea608Parser2=new Hb(3,n,r)}e.on(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Np.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Np.FRAG_LOADING,this.onFragLoading,this),e.on(Np.FRAG_LOADED,this.onFragLoaded,this),e.on(Np.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Np.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Np.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Np.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Np.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Np.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Np.FRAG_LOADING,this.onFragLoading,this),e.off(Np.FRAG_LOADED,this.onFragLoaded,this),e.off(Np.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Np.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Np.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Np.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Np.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],u=(o=r[0],a=r[1],l=t,c=n,Math.min(a,c)-Math.max(o,l));if(u>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),i=!0,u/(n-t)>.5))return}var o,a,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(Np.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(Np.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],o=this.getExistingTrack(e);if(o)n[e]=o,Nm(n[e]),Fm(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(Np.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=>{Nm(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++)Nm(t[e])}onSubtitleTracksUpdated(e,t){const n=t.subtitleTracks||[],r=n.some((e=>e.textCodec===uw));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Sb(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(Ew(e[r],t)){n=e[r];break}n&&(r=n)}if(r)Nm(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(Np.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===Lm){var o,a;const e=t.frag.sn,l=null!=(o=null==t||null==(a=t.part)?void 0:a.index)?o:-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===Om)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===uw?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(Np.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const n=this.hls;pw(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),n.trigger(Np.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{Hp.log(`Failed to parse IMSC1: ${t}`),n.trigger(Np.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:n,payload:r}=e,{initPTS:s,unparsedVttFrags:i}=this,o=s.length-1;if(!s[n.cc]&&-1===o)return void i.push(e);const a=this.hls;cw(null!=(t=n.initSegment)&&t.data?Yg(n.initSegment.data,new Uint8Array(r)):r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,(e=>{this._appendCues(e,n.level),a.trigger(Np.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),Hp.log(`Failed to parse VTT cue: ${t}`),s&&o>n.cc||a.trigger(Np.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})}))}_fallbackToIMSC1(e,t){const n=this.tracks[e.level];n.textCodec||pw(t,this.initPTS[e.cc],(()=>{n.textCodec=uw,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=>Um(n,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;n.trigger(Np.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:n}=t;n.type===Om&&this.onFragLoaded(Np.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!==Lm||"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=>Bm(e[r],t,n)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((n=>Bm(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 hv{constructor(e,t,n){super(e,t,n,"[audio-stream-controller]",Dm),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(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Np.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Np.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Np.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Np.ERROR,this.onError,this),e.on(Np.BUFFER_RESET,this.onBufferReset,this),e.on(Np.BUFFER_CREATED,this.onBufferCreated,this),e.on(Np.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Np.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Np.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Np.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Np.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Np.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Np.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Np.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Np.ERROR,this.onError,this),e.off(Np.BUFFER_RESET,this.onBufferReset,this),e.off(Np.BUFFER_CREATED,this.onBufferCreated,this),e.off(Np.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Np.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Np.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===uv&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=ev);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=tv):(this.loadedmetadata=!1,this.state=iv),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case tv:this.doTickIdle();break;case iv:{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=uv}break}case sv:{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=tv);break}case uv:{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=rv;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=qy.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);py(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=tv}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=tv)}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],o=i.details;if(!o||o.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(o))return void(this.state=iv);const a=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&a&&(this.bufferFlushed=!1,this.afterBufferFlushed(a,Jp,Dm));const l=this.getFwdBufferInfo(a,Dm);if(null===l)return;const{bufferedTrack:c,switchingTrack:u}=this;if(!u&&this._streamEnded(l,o))return e.trigger(Np.BUFFER_EOS,{type:"audio"}),void(this.state=lv);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Lm),h=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len);if(h>=f&&!u)return;const p=o.fragments[0].start;let g=l.end;if(u&&n){const e=this.getLoadPosition();c&&u.attrs!==c.attrs&&(g=e),o.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,o),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,o,l,Lm,f)),!m)return void(this.bufferFlushed=!0);const v=d&&m.start>d.end+o.targetduration;if(v||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(m.start,Lm);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===d.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 Zm(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=tv):(this.switchingTrack=null,this.bufferedTrack=t,this.state=ev),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(Np.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 o=r[i];let a=0;if(s.live||null!=(n=o.details)&&n.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!o.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(Wy(s,e),a=s.fragments[0].start):a=this.alignPlaylists(s,o.details)}o.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(o.details,a),this.state!==iv||this.waitForCdnTuneIn(s)||(this.state=tv),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:n,part:r,payload:s}=e,{config:i,trackId:o,levels:a}=this;if(!a)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=a[o];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 u=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new mb(this.hls,Dm,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,o=new Ky(n.level,n.sn,n.stats.chunkCount,s.byteLength,t,i);d.push(s,f,u,"",n,r,c.totalduration,e,o,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 ${o}`);const{cache:e}=this.waitingData=this.waitingData||{frag:n,part:r,cache:new Eb,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=uv}}_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===Dm)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(Np.AUDIO_TRACK_SWITCHED,Pp({},e)))}this.fragBufferedComplete(n,r)}else if(!this.loadedmetadata&&n.type===Lm){const e=this.videoBuffer||this.media;if(e){qy.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var n;if(t.fatal)this.state=cv;else switch(t.details){case jp.FRAG_GAP:case jp.FRAG_PARSING_ERROR:case jp.FRAG_DECRYPT_ERROR:case jp.FRAG_LOAD_ERROR:case jp.FRAG_LOAD_TIMEOUT:case jp.KEY_LOAD_ERROR:case jp.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Dm,t);break;case jp.AUDIO_TRACK_LOAD_ERROR:case jp.AUDIO_TRACK_LOAD_TIMEOUT:case jp.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==iv||(null==(n=t.context)?void 0:n.type)!==Am||(this.state=tv);break;case jp.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 jp.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===Jp&&(this.bufferFlushed=!0,this.state===lv&&(this.state=tv))}_handleTransmuxComplete(e){var t;const n="audio",{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{details:u}=c,{audio:d,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(a)&&u){if(this.state=ov,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=a.initSegment||a;this._bufferInitSegment(p.tracks,e,i),r.trigger(Np.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:p.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;l&&(l.elementaryStreams[Jp]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),a.setElementaryStreamInfo(Jp,e,t,n,r),this.bufferFragmentData(d,a,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Fp({id:n,frag:a,details:u},f);r.trigger(Np.FRAG_PARSING_METADATA,e)}if(h){const e=Fp({id:n,frag:a,details:u},h);r.trigger(Np.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(a)}_bufferInitSegment(e,t,n){if(this.state!==ov)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(Np.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(Np.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||r===Ay||r===Ly)?"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=uv):(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(Np.AUDIO_TRACK_SWITCHED,Pp({},e))}},audioTrackController:class extends Cy{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(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.LEVEL_LOADING,this.onLevelLoading,this),e.on(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Np.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Np.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.LEVEL_LOADING,this.onLevelLoading,this),e.off(Np.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Np.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Np.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 o=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,o)}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(Np.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===Am&&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(Np.AUDIO_TRACK_SWITCHING,Pp({},r)),r.details&&!r.details.live)return;const o=this.switchParams(r.url,null==n?void 0:n.details);this.loadPlaylist(o)}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(Np.ERROR,{type:Bp.MEDIA_ERROR,details:jp.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(Np.AUDIO_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:e||null})}}},emeController:Tw,cmcdController:Ow,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=Hp.log.bind(Hp,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Np.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Np.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Np.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Np.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Np.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)===yy&&n.flags===wy){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,o=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(Np.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];o&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.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":o}=e;if(t.some((e=>e.pathwayId===s)))return;const a=this.getLevelsForPathway(i).map((e=>{const t=Fp({},e);t.details=void 0,t.url=Pw(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o);const i=new Wp(e.attrs);i["PATHWAY-ID"]=s;const a=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;a&&(n[i.AUDIO]=a,i.AUDIO=a),l&&(r[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new Zm(t);return _y(c,"audio",a),_y(c,"text",l),c}));t.push(...a),xw(this.audioTracks,n,o,s),xw(this.subtitleTracks,r,o,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,o=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.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":o,"PATHWAY-CLONES":a,"PATHWAY-PRIORITY":l}=i;if(o)try{this.uri=new self.URL(o,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||n.url),a&&this.clonePathways(a),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,a,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function Gw(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Gw):Object.keys(e).reduce(((t,n)=>(t[n]=Gw(e[n]),t)),{}):e}function Hw(e){const t=e.loader;if(t!==Nw&&t!==Fw)Hp.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=Nw,e.progressive=!0,e.enableSoftwareAES=!0,Hp.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Vw{static get version(){return"1.4.10"}static isSupported(){return function(){const e=cm();if(!e)return!1;const t=fv(),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 Np}static get ErrorTypes(){return Bp}static get ErrorDetails(){return jp}static get DefaultConfig(){return Vw.defaultConfig?Vw.defaultConfig:Kw}static set DefaultConfig(e){Vw.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new pb,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){Gp(e,"debug","log","info","warn","error");try{Kp.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){Kp=qp}}else Kp=qp}(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=Gw(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],o=[];r.forEach((r=>{const a=`${e}Loading${r}`,l=t[a];if(void 0!==l&&i){o.push(a);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}}})),o.length&&Hp.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),Pp(Pp({},n),t)}(Vw.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Hw(t);const{abrController:n,bufferController:r,capLevelController:s,errorController:i,fpsController:o}=t,a=new i(this),l=this.abrController=new n(this),c=this.bufferController=new r(this),u=this.capLevelController=new s(this),d=new o(this),h=new Mm(this),f=new Vm(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new ky(this,g),y=new Oy(this),v=new jy(this.config),b=this.streamController=new vb(this,y,v);u.setStreamController(b),d.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const E=[l,c,u,d,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const S=t.audioStreamController;S&&w.push(new S(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const C=t.subtitleStreamController;C&&w.push(new C(this,y,v)),this.createController(t.timelineController,E),v.emeController=this.emeController=this.createController(t.emeController,E),this.cmcdController=this.createController(t.cmcdController,E),this.latencyController=this.createController(zm,E),this.coreComponents=E,w.push(a);const T=a.onErrorOut;"function"==typeof T&&this.on(Np.ERROR,T,a)}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){Hp.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(Np.ERROR,{type:Bp.OTHER_ERROR,details:jp.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){Hp.log("destroy"),this.trigger(Np.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){Hp.log("attachMedia"),this._media=e,this.trigger(Np.MEDIA_ATTACHING,{media:e})}detachMedia(){Hp.log("detachMedia"),this.trigger(Np.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,n=this.url,r=this.url=Op.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});Hp.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Np.MANIFEST_LOADING,{url:e})}startLoad(e=-1){Hp.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){Hp.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){Hp.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Hp.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){Hp.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){Hp.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){Hp.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){Hp.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){Hp.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&&(Hp.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Wm.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}}Vw.defaultConfig=void 0;const zw={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function Ww(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=String.fromCharCode(e)})),N(n)}function Yw(e){const t=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),n=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(H(t));return crypto.subtle.importKey("pkcs8",n,zw,!1,["sign"])}async function Qw({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const s=e();if(s.length)try{const n=(new Date).toISOString(),i=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=$a.v4(),s=`nonceStr=${r}&timestamp=${e}&data=${n}==`,i=(new TextEncoder).encode(s),o=await Yw("-----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:Ww(await crypto.subtle.sign(zw,o,i)),nonceStr:r}}({timestamp:n,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const o={signature:i.signature,nonceStr:i.nonceStr,timestamp:n,streams:s},a=we();return await a.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||r(),!0}catch(e){return s.forEach((e=>n(e))),!1}}class Xw{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((()=>{Qw({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Jw=null;class Zw{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Jw||(Jw=new Xw,Jw),this._usageCollector.registerStream(e.id),this._sessionId=String($a.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_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 eE=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(!Vw.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await bp(t),{watcherUrl:r,status:s,recordings:i=[],resolution:o}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const a=document.createElement("video");a.id=t,a.controls=!0;const l=new Vw;if(l.attachMedia(a),"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");a.src=e.mp4.url}return new Zw(a,o).registerEvents(),a}});const tE=e=>{const t=(e=>{var t;const n=we(),r=new Date,s=r.getTime()+31536e6,i=new Date(s).toISOString();let o=null===(t=Ce(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:i,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Ya({storyTargets:[o]})),{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 Ya(t),t},nE=({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(tE(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(tE(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},rE=async e=>{const t=we();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=dp(n.data);t.cache&&Ya(r),Te(["story-sync-state",e.targetId],"synced"),et("local.story.created",r);const s=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:s}},sE=e=>e?Ce(["story","get",e]):{data:void 0,cachedAt:void 0},iE=async(e,t=!1)=>{const n=we();let r;if(n.log("story/deleteStory",e),n.cache&&(r=sE(e),null==r?void 0:r.data)){const{data:e}=r;et("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await n.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},oE=e=>{const t=we(),n=[Ze(t,"onStoryUpdated","story.updated",(async t=>{const n=dp(t);Ya(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},aE=e=>{const t=we(),n=[Ze(t,"onStoryUpdated","local.story.updated",(async t=>{Ya(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},lE=e=>{const t=we(),n=[Ze(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Xa(t,["reactions"]),s=dp(r),i=xd("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Ya(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},cE=e=>{const t=we(),n=[Ze(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Ya(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},uE=e=>{const t=we(),n=[Ze(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Xa(t,["reactions"]),s=dp(r),i=xd("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Ya(i),e(i.stories)}))];return()=>{n.forEach((e=>e()))}},dE=e=>{const t=we(),n=[Ze(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Ya(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},hE=e=>{e.forEach((e=>{const t=Ce(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Te(["story-expire",e.targetId],n.toISOString())}))},fE=e=>{e.forEach((e=>{Te(["story-reference",e.storyId],e.referenceId)}))},pE=async({targetType:e,targetId:t,options:n})=>{const r=we();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"}}}),o=dp(i.data);return r.cache&&(Ya(o),hE(o.stories),fE(o.stories)),{data:o.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},gE=e=>{const t=we(),n=[Ze(t,"onStoryCreated","story.created",(async t=>{const n=dp(t,!0);Ya(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},mE=e=>{const t=we(),n=[Ze(t,"onStoryCreated","local.story.created",(async t=>{Ya(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},yE=e=>{const t=we(),n=[Ze(t,"onStoryDeleted","story.deleted",(async t=>{const n=dp(t);Ya(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},vE=e=>{const t=we(),n=[Ze(t,"onStoryDeleted","local.story.deleted",(async t=>{Ya(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},bE=e=>{const t=we();return Ze(t,"onStoryError","local.story.error",(async t=>{Ya(t),e(t.stories)}))},wE=e=>t=>e((e=>t(e[0]))),EE=async e=>{const t=we();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Ya(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class SE extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=dp(e);t.cache&&(Ya(r,{cachedAt:n}),hE(r.stories),fE(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)Te(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Ce(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Te(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=Ce(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])],Te(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class CE extends Fh{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class TE extends Uh{constructor(e,t){const n=Dh(e),r=["story-target-ids","collection",n],s=new CE(e);super(s,n,r,t),this.query=e,this.queryStreamController=new SE(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=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>Ce(["story","get",e]))).filter(Boolean).map((e=>Cl.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(Ne):r.sort(je)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gE,action:"onCreate"},{fn:oE,action:"onUpdate"},{fn:yE,action:"onDelete"},{fn:bE,action:"onError"}])}}const kE=(e,t)=>{var n,r;const s=null===(n=Ce(e))||void 0===n?void 0:n.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];Te(e,Object.assign(Object.assign({},s),{data:[...new Set([...i,...t])]}))};class _E extends Ph{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=e=>e}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Ya(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Te(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):kE(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&kE(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 IE extends Oh{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 o=await this.createRequest({seenState:this.smartFilterState,limit:r});return l=o,{categories:(a=i).categories.concat(l.categories),communities:a.communities.concat(l.communities),communityUsers:a.communityUsers.concat(l.communityUsers),files:a.files.concat(l.files),storyTargets:a.storyTargets.concat(l.storyTargets),users:a.users.concat(l.users),paging:l.paging};var a,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 AE extends Uh{constructor(e,t){const n=Dh(e),r=["story-global-feed","collection",n],s=new IE(e);super(s,n,r,t),this.query=e,this.queryStreamController=new _E(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=Ce(this.cacheKey))||void 0===e?void 0:e.data)||Te(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=Ce(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let i=s.data.map((e=>Ce(["storyTarget","get",e]))).filter(Boolean).map((e=>Cl.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).map((e=>Xa(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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(Be);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(Be)||[],r=t.unseen.sort(Be)||[],s=t.seen.sort(Be)||[];return n.concat(r,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gE,action:"onCreate"},{fn:oE,action:"onUpdate"},{fn:yE,action:"onDelete"},{fn:mE,action:"onCreate"},{fn:aE,action:"onUpdate"},{fn:vE,action:"onDelete"},{fn:bE,action:"onError"}])}}var RE=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 o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:qa(),dataType:"image",items:i,targetType:e,targetId:t,metadata:r};const a=new Date;Te(["story-sync-state",t],"syncing"),Te(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),nE({payload:o,formData:n},(e=>{et("local.story.created",e)}));try{const{data:e}=await wd(n);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t})}),nE({payload:o,formData:n},(e=>{et("local.story.created",e)}));const r=await rE(o);return r.data?Object.assign(Object.assign({},r),{data:Cl.story(r.data)}):r}catch(e){throw Te(["story-sync-state",t],"error"),nE({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{et("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:qa(),dataType:"video",items:s,targetType:e,targetId:t,metadata:r};const o=new Date;Te(["story-sync-state",t],"syncing"),Te(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),nE({payload:i,formData:n,isVideo:!0},(e=>{et("local.story.created",e)}));try{const{data:e}=await bd(n,c.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}})}),nE({payload:i,formData:n,isVideo:!0},(e=>{et("local.story.created",e)}));const r=await rE(i);return r.data?Object.assign(Object.assign({},r),{data:Cl.story(r.data)}):r}catch(e){throw Te(["story-sync-state",t],"error"),nE({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n,isVideo:!0},(e=>{et("local.story.error",e)})),e}},hardDeleteStory:async e=>await iE(e,!0),softDeleteStory:async e=>await iE(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=we(),s=[],i=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),r||console.log(g);const a=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(Ne):t.sort(je):"asc"===i?t.sort($e):t.sort(qe)},l=e=>{var n;const r=e.data.map((e=>{const t=sE(e);if(null==t?void 0:t.data)return Cl.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=a(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=a(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=a(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=(e,t,n=!1,r=!1,s=!1)=>{const o=Ce(i),a={loading:r,error:s,params:{page:void 0},data:(null==o?void 0:o.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));a.data=a.data.filter((e=>!t.includes(e)))||[]}else a.data=n?e.map(he("story")):[...new Set([...a.data,...e.map(he("story"))])];Te(i,a.data),l(a)},u=e=>t=>{c(t,e)};return(t=>{const n=ae(pE,e);ce(n,(({data:e,error:n,loading:r})=>{c(e,"fetch",t,r,n)}))})(!0),s.push(gE(u("onCreate")),oE(u("onUpdate")),yE(u("onDelete")),lE(u("onReactionAdded")),uE(u("onReactionRemoved")),bE(u("onError")),mE(u("onCreate")),aE(u("onUpdate")),vE(u("onDelete")),cE(u("onReactionAdded")),dE(u("onReactionRemoved")),(e=>{const t=we();return Ze(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ce(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)})),(()=>Ie(i))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>$u(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:Cl.story(e.data)})):t(e)}),"storyId",hp,[wE(oE),wE(yE),wE(lE),wE(uE),wE(bE),wE(aE),wE(vE),wE(cE),wE(dE)]),getTargetById:(e,t)=>$u(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:Cl.storyTarget(e.data[0])})):t(e)}),"query",(e=>EE([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=we(),s=[],i=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),r||console.log(g);const a=(e,n=!1,r=!1,s=!1)=>{const o=Ce(i),a={loading:r,error:s,params:{page:void 0},data:[]};e&&(a.data=n?e.map(he("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(he("storyTarget"))])]),Te(i,a.data),(e=>{var n;const r=e.data.map((e=>{const t=Ce(["storyTarget","get",e]);if(null==t?void 0:t.data)return Cl.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})})(a)};return(t=>{const n=ae(EE,e);ce(n,(({data:e,error:n,loading:r})=>{a(e,t,r,n)}))})(!0),s.push((()=>Ie(i))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:s,userId:i}=we();s||console.log(g);const o=Date.now();r(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const a=new TE(e,t),l=a.startSubscription(),c=a.getCacheKey();return l.push((()=>{Ie(c)})),()=>{r(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:s,userId:i}=we();s||console.log(g);const o=Date.now();r(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const a=new AE(e,t),l=a.startSubscription(),c=a.getCacheKey();return l.push((()=>{Ie(c)})),()=>{r(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});var LE,DE={exports:{}},OE={exports:{}};function xE(){return LE||(LE=1,function(e,t){!function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var n=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),g=Symbol.iterator;function m(e){if(null===e||"object"!=typeof e)return null;var t=g&&e[g]||e["@@iterator"];return"function"==typeof t?t:null}var y={current:null},v={transition:null},b={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},w={current:null},E={},S=null;function C(e){S=e}E.setExtraStackFrame=function(e){S=e},E.getCurrentStack=null,E.getStackAddendum=function(){var e="";S&&(e+=S);var t=E.getCurrentStack;return t&&(e+=t()||""),e};var T={ReactCurrentDispatcher:y,ReactCurrentBatchConfig:v,ReactCurrentOwner:w};function k(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];I("warn",e,n)}function _(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];I("error",e,n)}function I(e,t,n){var r=T.ReactDebugCurrentFrame.getStackAddendum();""!==r&&(t+="%s",n=n.concat([r]));var s=n.map((function(e){return String(e)}));s.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,s)}T.ReactDebugCurrentFrame=E,T.ReactCurrentActQueue=b;var A={};function R(e,t){var n=e.constructor,r=n&&(n.displayName||n.name)||"ReactClass",s=r+"."+t;A[s]||(_("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",t,r),A[s]=!0)}var L={isMounted:function(e){return!1},enqueueForceUpdate:function(e,t,n){R(e,"forceUpdate")},enqueueReplaceState:function(e,t,n,r){R(e,"replaceState")},enqueueSetState:function(e,t,n,r){R(e,"setState")}},D=Object.assign,O={};function x(e,t,n){this.props=e,this.context=t,this.refs=O,this.updater=n||L}Object.freeze(O),x.prototype.isReactComponent={},x.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},x.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};var P={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},M=function(e,t){Object.defineProperty(x.prototype,e,{get:function(){k("%s(...) is deprecated in plain JavaScript React classes. %s",t[0],t[1])}})};for(var F in P)P.hasOwnProperty(F)&&M(F,P[F]);function U(){}function N(e,t,n){this.props=e,this.context=t,this.refs=O,this.updater=n||L}U.prototype=x.prototype;var B=N.prototype=new U;B.constructor=N,D(B,x.prototype),B.isPureReactComponent=!0;var j=Array.isArray;function $(e){return j(e)}function q(e){return""+e}function K(e){if(function(e){try{return q(e),!1}catch(e){return!0}}(e))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),q(e)}function G(e){return e.displayName||"Context"}function H(e){if(null==e)return null;if("number"==typeof e.tag&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case s:return"Fragment";case r:return"Portal";case o:return"Profiler";case i:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case l:return G(e)+".Consumer";case a:return G(e._context)+".Provider";case c:return function(e,t,n){var r=e.displayName;if(r)return r;var s=t.displayName||t.name||"";return""!==s?n+"("+s+")":n}(e,e.render,"ForwardRef");case h:var t=e.displayName||null;return null!==t?t:H(e.type)||"Memo";case f:var n=e,p=n._payload,g=n._init;try{return H(g(p))}catch(e){return null}}return null}var V,z,W,Y=Object.prototype.hasOwnProperty,Q={key:!0,ref:!0,__self:!0,__source:!0};function X(e){if(Y.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}function J(e){if(Y.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}function Z(e,t){var n=function(){V||(V=!0,_("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}function ee(e,t){var n=function(){z||(z=!0,_("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}function te(e){if("string"==typeof e.ref&&w.current&&e.__self&&w.current.stateNode!==e.__self){var t=H(w.current.type);W[t]||(_('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',t,e.ref),W[t]=!0)}}W={};var ne=function(e,t,r,s,i,o,a){var l={$$typeof:n,type:e,key:t,ref:r,props:a,_owner:o,_store:{}};return Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(l,"_self",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.defineProperty(l,"_source",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l};function re(e,t,n){var r,s={},i=null,o=null,a=null,l=null;if(null!=t)for(r in X(t)&&(o=t.ref,te(t)),J(t)&&(K(t.key),i=""+t.key),a=void 0===t.__self?null:t.__self,l=void 0===t.__source?null:t.__source,t)Y.call(t,r)&&!Q.hasOwnProperty(r)&&(s[r]=t[r]);var c=arguments.length-2;if(1===c)s.children=n;else if(c>1){for(var u=Array(c),d=0;d<c;d++)u[d]=arguments[d+2];Object.freeze&&Object.freeze(u),s.children=u}if(e&&e.defaultProps){var h=e.defaultProps;for(r in h)void 0===s[r]&&(s[r]=h[r])}if(i||o){var f="function"==typeof e?e.displayName||e.name||"Unknown":e;i&&Z(s,f),o&&ee(s,f)}return ne(e,i,o,a,l,w.current,s)}function se(e,t,n){if(null==e)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r,s,i=D({},e.props),o=e.key,a=e.ref,l=e._self,c=e._source,u=e._owner;if(null!=t)for(r in X(t)&&(a=t.ref,u=w.current),J(t)&&(K(t.key),o=""+t.key),e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)Y.call(t,r)&&!Q.hasOwnProperty(r)&&(void 0===t[r]&&void 0!==s?i[r]=s[r]:i[r]=t[r]);var d=arguments.length-2;if(1===d)i.children=n;else if(d>1){for(var h=Array(d),f=0;f<d;f++)h[f]=arguments[f+2];i.children=h}return ne(e.type,o,a,l,c,u,i)}function ie(e){return"object"==typeof e&&null!==e&&e.$$typeof===n}var oe=!1,ae=/\/+/g;function le(e){return e.replace(ae,"$&/")}function ce(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(K(e.key),n=""+e.key,r={"=":"=0",":":"=2"},"$"+n.replace(/[=:]/g,(function(e){return r[e]}))):t.toString(36);var n,r}function ue(e,t,s,i,o){var a=typeof e;"undefined"!==a&&"boolean"!==a||(e=null);var l,c,u,d=!1;if(null===e)d=!0;else switch(a){case"string":case"number":d=!0;break;case"object":switch(e.$$typeof){case n:case r:d=!0}}if(d){var h=e,f=o(h),p=""===i?"."+ce(h,0):i;if($(f)){var g="";null!=p&&(g=le(p)+"/"),ue(f,t,g,"",(function(e){return e}))}else null!=f&&(ie(f)&&(!f.key||h&&h.key===f.key||K(f.key),l=f,c=s+(!f.key||h&&h.key===f.key?"":le(""+f.key)+"/")+p,f=ne(l.type,c,l.ref,l._self,l._source,l._owner,l.props)),t.push(f));return 1}var y=0,v=""===i?".":i+":";if($(e))for(var b=0;b<e.length;b++)y+=ue(u=e[b],t,s,v+ce(u,b),o);else{var w=m(e);if("function"==typeof w){var E=e;w===E.entries&&(oe||k("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),oe=!0);for(var S,C=w.call(E),T=0;!(S=C.next()).done;)y+=ue(u=S.value,t,s,v+ce(u,T++),o)}else if("object"===a){var _=String(e);throw new Error("Objects are not valid as a React child (found: "+("[object Object]"===_?"object with keys {"+Object.keys(e).join(", ")+"}":_)+"). If you meant to render a collection of children, use an array instead.")}}return y}function de(e,t,n){if(null==e)return e;var r=[],s=0;return ue(e,r,"","",(function(e){return t.call(n,e,s++)})),r}var he;function fe(e){if(-1===e._status){var t=(0,e._result)();if(t.then((function(t){if(0===e._status||-1===e._status){var n=e;n._status=1,n._result=t}}),(function(t){if(0===e._status||-1===e._status){var n=e;n._status=2,n._result=t}})),-1===e._status){var n=e;n._status=0,n._result=t}}if(1===e._status){var r=e._result;return void 0===r&&_("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",r),"default"in r||_("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",r),r.default}throw e._result}function pe(e){return"string"==typeof e||"function"==typeof e||(e===s||e===o||e===i||e===u||e===d||e===p||"object"==typeof e&&null!==e&&(e.$$typeof===f||e.$$typeof===h||e.$$typeof===a||e.$$typeof===l||e.$$typeof===c||e.$$typeof===he||void 0!==e.getModuleId))}function ge(){var e=y.current;return null===e&&_("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."),e}he=Symbol.for("react.module.reference");var me,ye,ve,be,we,Ee,Se,Ce=0;function Te(){}Te.__reactDisabledLog=!0;var ke,_e=T.ReactCurrentDispatcher;function Ie(e,t,n){if(void 0===ke)try{throw Error()}catch(e){var r=e.stack.trim().match(/\n( *(at )?)/);ke=r&&r[1]||""}return"\n"+ke+e}var Ae,Re=!1,Le="function"==typeof WeakMap?WeakMap:Map;function De(e,t){if(!e||Re)return"";var n,r=Ae.get(e);if(void 0!==r)return r;Re=!0;var s,i=Error.prepareStackTrace;Error.prepareStackTrace=void 0,s=_e.current,_e.current=null,function(){if(0===Ce){me=console.log,ye=console.info,ve=console.warn,be=console.error,we=console.group,Ee=console.groupCollapsed,Se=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Te,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Ce++}();try{if(t){var o=function(){throw Error()};if(Object.defineProperty(o.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(o,[])}catch(e){n=e}Reflect.construct(e,[],o)}else{try{o.call()}catch(e){n=e}e.call(o.prototype)}}else{try{throw Error()}catch(e){n=e}e()}}catch(t){if(t&&n&&"string"==typeof t.stack){for(var a=t.stack.split("\n"),l=n.stack.split("\n"),c=a.length-1,u=l.length-1;c>=1&&u>=0&&a[c]!==l[u];)u--;for(;c>=1&&u>=0;c--,u--)if(a[c]!==l[u]){if(1!==c||1!==u)do{if(c--,--u<0||a[c]!==l[u]){var d="\n"+a[c].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),"function"==typeof e&&Ae.set(e,d),d}}while(c>=1&&u>=0);break}}}finally{Re=!1,_e.current=s,function(){if(0==--Ce){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:D({},e,{value:me}),info:D({},e,{value:ye}),warn:D({},e,{value:ve}),error:D({},e,{value:be}),group:D({},e,{value:we}),groupCollapsed:D({},e,{value:Ee}),groupEnd:D({},e,{value:Se})})}Ce<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=i}var h=e?e.displayName||e.name:"",f=h?Ie(h):"";return"function"==typeof e&&Ae.set(e,f),f}function Oe(e,t,n){if(null==e)return"";if("function"==typeof e)return De(e,function(e){var t=e.prototype;return!(!t||!t.isReactComponent)}(e));if("string"==typeof e)return Ie(e);switch(e){case u:return Ie("Suspense");case d:return Ie("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case c:return De(e.render,!1);case h:return Oe(e.type,t,n);case f:var r=e,s=r._payload,i=r._init;try{return Oe(i(s),t,n)}catch(e){}}return""}Ae=new Le;var xe,Pe={},Me=T.ReactDebugCurrentFrame;function Fe(e){if(e){var t=e._owner,n=Oe(e.type,e._source,t?t.type:null);Me.setExtraStackFrame(n)}else Me.setExtraStackFrame(null)}function Ue(e){if(e){var t=e._owner;C(Oe(e.type,e._source,t?t.type:null))}else C(null)}function Ne(){if(w.current){var e=H(w.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}function Be(e){return null!=e&&void 0!==(t=e.__source)?"\n\nCheck your code at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+".":"";var t}xe=!1;var je={};function $e(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var n=function(e){var t=Ne();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t="\n\nCheck the top-level render call using <"+n+">.")}return t}(t);if(!je[n]){je[n]=!0;var r="";e&&e._owner&&e._owner!==w.current&&(r=" It was passed a child from "+H(e._owner.type)+"."),Ue(e),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,r),Ue(null)}}}function qe(e,t){if("object"==typeof e)if($(e))for(var n=0;n<e.length;n++){var r=e[n];ie(r)&&$e(r,t)}else if(ie(e))e._store&&(e._store.validated=!0);else if(e){var s=m(e);if("function"==typeof s&&s!==e.entries)for(var i,o=s.call(e);!(i=o.next()).done;)ie(i.value)&&$e(i.value,t)}}function Ke(e){var t,n=e.type;if(null!=n&&"string"!=typeof n){if("function"==typeof n)t=n.propTypes;else{if("object"!=typeof n||n.$$typeof!==c&&n.$$typeof!==h)return;t=n.propTypes}if(t){var r=H(n);!function(e,t,n,r,s){var i=Function.call.bind(Y);for(var o in e)if(i(e,o)){var a=void 0;try{if("function"!=typeof e[o]){var l=Error((r||"React class")+": "+n+" type `"+o+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[o]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw l.name="Invariant Violation",l}a=e[o](t,o,r,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(e){a=e}!a||a instanceof Error||(Fe(s),_("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",r||"React class",n,o,typeof a),Fe(null)),a instanceof Error&&!(a.message in Pe)&&(Pe[a.message]=!0,Fe(s),_("Failed %s type: %s",n,a.message),Fe(null))}}(t,e.props,"prop",r,e)}else if(void 0!==n.PropTypes&&!xe){xe=!0,_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",H(n)||"Unknown")}"function"!=typeof n.getDefaultProps||n.getDefaultProps.isReactClassApproved||_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ge(e){for(var t=Object.keys(e.props),n=0;n<t.length;n++){var r=t[n];if("children"!==r&&"key"!==r){Ue(e),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",r),Ue(null);break}}null!==e.ref&&(Ue(e),_("Invalid attribute `ref` supplied to `React.Fragment`."),Ue(null))}function He(e,t,r){var i=pe(e);if(!i){var o="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(o+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var a,l=Be(t);o+=l||Ne(),null===e?a="null":$(e)?a="array":void 0!==e&&e.$$typeof===n?(a="<"+(H(e.type)||"Unknown")+" />",o=" Did you accidentally export a JSX literal instead of a component?"):a=typeof e,_("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",a,o)}var c=re.apply(this,arguments);if(null==c)return c;if(i)for(var u=2;u<arguments.length;u++)qe(arguments[u],e);return e===s?Ge(c):Ke(c),c}var Ve=!1;var ze=!1,We=null;var Ye=0,Qe=!1;function Xe(e){e!==Ye-1&&_("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ye=e}function Je(t,n,r){var s=b.current;if(null!==s)try{et(s),function(t){if(null===We)try{var n=("require"+Math.random()).slice(0,7);We=(e&&e[n]).call(e,"timers").setImmediate}catch(e){We=function(e){!1===ze&&(ze=!0,"undefined"==typeof MessageChannel&&_("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(void 0)}}We(t)}((function(){0===s.length?(b.current=null,n(t)):Je(t,n,r)}))}catch(e){r(e)}else n(t)}var Ze=!1;function et(e){if(!Ze){Ze=!0;var t=0;try{for(;t<e.length;t++){var n=e[t];do{n=n(!0)}while(null!==n)}e.length=0}catch(n){throw e=e.slice(t+1),n}finally{Ze=!1}}}var tt=He,nt=function(e,t,n){for(var r=se.apply(this,arguments),s=2;s<arguments.length;s++)qe(arguments[s],r.type);return Ke(r),r},rt=function(e){var t=He.bind(null,e);return t.type=e,Ve||(Ve=!0,k("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(t,"type",{enumerable:!1,get:function(){return k("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:e}),e}}),t},st={map:de,forEach:function(e,t,n){de(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return de(e,(function(){t++})),t},toArray:function(e){return de(e,(function(e){return e}))||[]},only:function(e){if(!ie(e))throw new Error("React.Children.only expected to receive a single React element child.");return e}};t.Children=st,t.Component=x,t.Fragment=s,t.Profiler=o,t.PureComponent=N,t.StrictMode=i,t.Suspense=u,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=T,t.cloneElement=nt,t.createContext=function(e){var t={$$typeof:l,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};t.Provider={$$typeof:a,_context:t};var n=!1,r=!1,s=!1,i={$$typeof:l,_context:t};return Object.defineProperties(i,{Provider:{get:function(){return r||(r=!0,_("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),t.Provider},set:function(e){t.Provider=e}},_currentValue:{get:function(){return t._currentValue},set:function(e){t._currentValue=e}},_currentValue2:{get:function(){return t._currentValue2},set:function(e){t._currentValue2=e}},_threadCount:{get:function(){return t._threadCount},set:function(e){t._threadCount=e}},Consumer:{get:function(){return n||(n=!0,_("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),t.Consumer}},displayName:{get:function(){return t.displayName},set:function(e){s||(k("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",e),s=!0)}}}),t.Consumer=i,t._currentRenderer=null,t._currentRenderer2=null,t},t.createElement=tt,t.createFactory=rt,t.createRef=function(){var e={current:null};return Object.seal(e),e},t.forwardRef=function(e){null!=e&&e.$$typeof===h?_("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):"function"!=typeof e?_("forwardRef requires a render function but was given %s.",null===e?"null":typeof e):0!==e.length&&2!==e.length&&_("forwardRef render functions accept exactly two parameters: props and ref. %s",1===e.length?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),null!=e&&(null==e.defaultProps&&null==e.propTypes||_("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"));var t,n={$$typeof:c,render:e};return Object.defineProperty(n,"displayName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(n){t=n,e.name||e.displayName||(e.displayName=n)}}),n},t.isValidElement=ie,t.lazy=function(e){var t,n,r={$$typeof:f,_payload:{_status:-1,_result:e},_init:fe};return Object.defineProperties(r,{defaultProps:{configurable:!0,get:function(){return t},set:function(e){_("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),t=e,Object.defineProperty(r,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return n},set:function(e){_("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),n=e,Object.defineProperty(r,"propTypes",{enumerable:!0})}}}),r},t.memo=function(e,t){pe(e)||_("memo: The first argument must be a component. Instead received: %s",null===e?"null":typeof e);var n,r={$$typeof:h,type:e,compare:void 0===t?null:t};return Object.defineProperty(r,"displayName",{enumerable:!1,configurable:!0,get:function(){return n},set:function(t){n=t,e.name||e.displayName||(e.displayName=t)}}),r},t.startTransition=function(e,t){var n=v.transition;v.transition={};var r=v.transition;v.transition._updatedFibers=new Set;try{e()}finally{if(v.transition=n,null===n&&r._updatedFibers)r._updatedFibers.size>10&&k("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),r._updatedFibers.clear()}},t.unstable_act=function(e){var t=Ye;Ye++,null===b.current&&(b.current=[]);var n,r=b.isBatchingLegacy;try{if(b.isBatchingLegacy=!0,n=e(),!r&&b.didScheduleLegacyUpdate){var s=b.current;null!==s&&(b.didScheduleLegacyUpdate=!1,et(s))}}catch(e){throw Xe(t),e}finally{b.isBatchingLegacy=r}if(null!==n&&"object"==typeof n&&"function"==typeof n.then){var i=n,o=!1,a={then:function(e,n){o=!0,i.then((function(r){Xe(t),0===Ye?Je(r,e,n):e(r)}),(function(e){Xe(t),n(e)}))}};return Qe||"undefined"==typeof Promise||Promise.resolve().then((function(){})).then((function(){o||(Qe=!0,_("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))})),a}var l=n;if(Xe(t),0===Ye){var c=b.current;return null!==c&&(et(c),b.current=null),{then:function(e,t){null===b.current?(b.current=[],Je(l,e,t)):e(l)}}}return{then:function(e,t){e(l)}}},t.useCallback=function(e,t){return ge().useCallback(e,t)},t.useContext=function(e){var t=ge();if(void 0!==e._context){var n=e._context;n.Consumer===e?_("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):n.Provider===e&&_("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return t.useContext(e)},t.useDebugValue=function(e,t){return ge().useDebugValue(e,t)},t.useDeferredValue=function(e){return ge().useDeferredValue(e)},t.useEffect=function(e,t){return ge().useEffect(e,t)},t.useId=function(){return ge().useId()},t.useImperativeHandle=function(e,t,n){return ge().useImperativeHandle(e,t,n)},t.useInsertionEffect=function(e,t){return ge().useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return ge().useLayoutEffect(e,t)},t.useMemo=function(e,t){return ge().useMemo(e,t)},t.useReducer=function(e,t,n){return ge().useReducer(e,t,n)},t.useRef=function(e){return ge().useRef(e)},t.useState=function(e){return ge().useState(e)},t.useSyncExternalStore=function(e,t,n){return ge().useSyncExternalStore(e,t,n)},t.useTransition=function(){return ge().useTransition()},t.version="18.2.0","undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()}(OE,OE.exports)),OE.exports}!function(e){e.exports=xE()}(DE);const PE={reachabilityUrl:"https://clients3.google.com/generate_204",reachabilityMethod:"HEAD",reachabilityTest:e=>Promise.resolve(204===e.status),reachabilityShortTimeout:5e3,reachabilityLongTimeout:6e4,reachabilityRequestTimeout:15e3,reachabilityShouldRun:()=>!0,shouldFetchWiFiSSID:!1,useNativeReachability:!0},ME=t.NativeModules.RNCNetInfo;if(!ME)throw new Error("@react-native-community/netinfo: NativeModule.RNCNetInfo is null. To fix this issue try these steps:\n\n• Run `react-native link @react-native-community/netinfo` in the project root.\n• Rebuild and re-run the app.\n• If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.\n• Check that the library was linked correctly when you used the link command by running through the manual installation instructions in the README.\n* If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README.\n\nIf none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-netinfo");let FE=null;var UE={...ME,get eventEmitter(){return FE||(FE=new t.NativeEventEmitter(ME)),FE}};function NE(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class BE{constructor(e,t){NE(this,"_configuration",void 0),NE(this,"_listener",void 0),NE(this,"_isInternetReachable",void 0),NE(this,"_currentInternetReachabilityCheckHandler",null),NE(this,"_currentTimeoutHandle",null),NE(this,"_setIsInternetReachable",(e=>{this._isInternetReachable!==e&&(this._isInternetReachable=e,this._listener(this._isInternetReachable))})),NE(this,"_setExpectsConnection",(e=>{null!==this._currentInternetReachabilityCheckHandler&&(this._currentInternetReachabilityCheckHandler.cancel(),this._currentInternetReachabilityCheckHandler=null),null!==this._currentTimeoutHandle&&(clearTimeout(this._currentTimeoutHandle),this._currentTimeoutHandle=null),e&&this._configuration.reachabilityShouldRun()?(this._isInternetReachable||this._setIsInternetReachable(null),this._currentInternetReachabilityCheckHandler=this._checkInternetReachability()):this._setIsInternetReachable(!1)})),NE(this,"_checkInternetReachability",(()=>{const e=fetch(this._configuration.reachabilityUrl,{method:this._configuration.reachabilityMethod,cache:"no-cache"});let t;const n=new Promise(((e,n)=>{t=setTimeout((()=>n("timedout")),this._configuration.reachabilityRequestTimeout)}));let r=()=>{};const s=new Promise(((e,t)=>{r=()=>t("canceled")}));return{promise:Promise.race([e,n,s]).then((e=>this._configuration.reachabilityTest(e))).then((e=>{this._setIsInternetReachable(e);const t=this._isInternetReachable?this._configuration.reachabilityLongTimeout:this._configuration.reachabilityShortTimeout;this._currentTimeoutHandle=setTimeout(this._checkInternetReachability,t)})).catch((e=>{"canceled"!==e&&(this._setIsInternetReachable(!1),this._currentTimeoutHandle=setTimeout(this._checkInternetReachability,this._configuration.reachabilityShortTimeout))})).then((()=>{clearTimeout(t)}),(e=>{throw clearTimeout(t),e})),cancel:r}})),NE(this,"update",(e=>{"boolean"==typeof e.isInternetReachable&&this._configuration.useNativeReachability?this._setIsInternetReachable(e.isInternetReachable):this._setExpectsConnection(e.isConnected)})),NE(this,"currentState",(()=>this._isInternetReachable)),NE(this,"tearDown",(()=>{null!==this._currentInternetReachabilityCheckHandler&&(this._currentInternetReachabilityCheckHandler.cancel(),this._currentInternetReachabilityCheckHandler=null),null!==this._currentTimeoutHandle&&(clearTimeout(this._currentTimeoutHandle),this._currentTimeoutHandle=null)})),this._configuration=e,this._listener=t}}function jE(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class $E{constructor(e){jE(this,"_nativeEventSubscription",null),jE(this,"_subscriptions",new Set),jE(this,"_latestState",null),jE(this,"_internetReachability",void 0),jE(this,"_handleNativeStateUpdate",(e=>{this._internetReachability.update(e);const t=this._convertState(e);this._latestState=t,this._subscriptions.forEach((e=>e(t)))})),jE(this,"_handleInternetReachabilityUpdate",(e=>{if(!this._latestState)return;const t={...this._latestState,isInternetReachable:e};this._latestState=t,this._subscriptions.forEach((e=>e(t)))})),jE(this,"_fetchCurrentState",(async e=>{const t=await UE.getCurrentState(e);this._internetReachability.update(t);const n=this._convertState(t);return e||(this._latestState=n,this._subscriptions.forEach((e=>e(n)))),n})),jE(this,"_convertState",(e=>"boolean"==typeof e.isInternetReachable?e:{...e,isInternetReachable:this._internetReachability.currentState()})),jE(this,"latest",(e=>e?this._fetchCurrentState(e):this._latestState?Promise.resolve(this._latestState):this._fetchCurrentState())),jE(this,"add",(e=>{this._subscriptions.add(e),this._latestState?e(this._latestState):this.latest().then(e)})),jE(this,"remove",(e=>{this._subscriptions.delete(e)})),jE(this,"tearDown",(()=>{this._internetReachability&&this._internetReachability.tearDown(),this._nativeEventSubscription&&this._nativeEventSubscription.remove(),this._subscriptions.clear()})),this._internetReachability=new BE(e,this._handleInternetReachabilityUpdate),this._nativeEventSubscription=UE.eventEmitter.addListener("netInfo.networkStatusDidChange",this._handleNativeStateUpdate),this._fetchCurrentState()}}let qE,KE;!function(e){e.unknown="unknown",e.none="none",e.cellular="cellular",e.wifi="wifi",e.bluetooth="bluetooth",e.ethernet="ethernet",e.wimax="wimax",e.vpn="vpn",e.other="other"}(qE||(qE={})),function(e){e["2g"]="2g",e["3g"]="3g",e["4g"]="4g",e["5g"]="5g"}(KE||(KE={}));let GE=PE,HE=null;const VE=()=>new $E(GE);function zE(e){GE={...PE,...e},HE&&(HE.tearDown(),HE=VE()),"ios"===t.Platform.OS&&UE.configure(e)}function WE(e){return HE||(HE=VE()),HE.latest(e)}function YE(){return HE||(HE=VE()),HE._fetchCurrentState()}function QE(e){return HE||(HE=VE()),HE.add(e),()=>{HE&&HE.remove(e)}}function XE(e){e&&zE(e);const[t,n]=DE.exports.useState({type:qE.unknown,isConnected:null,isInternetReachable:null,details:null});return DE.exports.useEffect((()=>QE(n)),[]),t}var JE={configure:zE,fetch:WE,refresh:YE,addEventListener:QE,useNetInfo:XE},ZE=Object.freeze({__proto__:null,configure:zE,fetch:WE,refresh:YE,addEventListener:QE,useNetInfo:XE,default:JE,get NetInfoStateType(){return qE},get NetInfoCellularGeneration(){return KE}});return e.API_REGIONS=At,e.CategoryRepository=sp,e.ChannelRepository=lf,e.Client=qu,e.CommentRepository=mp,e.CommunityPostSettingMaps=a,e.CommunityPostSettings=o,e.CommunityRepository=tp,e.ContentFeedType=c,e.DefaultCommunityPostSetting=l,e.FeedRepository=ap,e.FileRepository=Ed,e.FileType=n,e.LiveStreamPlayer=eE,e.MessageContentType=u,e.MessageRepository=jh,e.PollRepository=Rp,e.PostContentType=d,e.PostRepository=vp,e.ReactionRepository=rh,e.StoryRepository=RE,e.StreamRepository=kp,e.SubChannelRepository=zh,e.UserRepository=yd,e.VERSION=h,e.VideoResolution=r,e.VideoSize=i,e.VideoTranscodingStatus=s,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:s}=we();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=ae,e.createReport=async(e,t)=>{const n=we();n.log("report/createReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=sh[e];return`/api/v3/${n}/${encodeURIComponent(t)}/flag`})());if(n.cache)if("message"===e){const e=await Zl(r);Ya(e)}else Ya("post"===e?Za(r,"communityUsers"):r);return et(`${e}.flagged`,r),!!r},e.createUserToken=async(e,t,n)=>{const r=await Ga(),s=Ha(),i=pr(Lt("http",t)),{data:o}=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:o.accessToken}},e.deleteReport=async(e,t)=>{const n=we();n.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=sh[e];return`/api/v3/${n}/${encodeURIComponent(t)}/unflag`})());if(n.cache)if("message"===e){const e=await Zl(r);Ya(e)}else Ya("post"===e?Za(r,"communityUsers"):r);return et(`${e}.unflagged`,r),!!r},e.disableCache=()=>{const e=we();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Ie,e.enableCache=(e={},t)=>{const n=we();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=De,e.filterByCommunityMembership=xe,e.filterByFeedType=Oe,e.filterByPostDataTypes=Pe,e.filterByPropEquality=Ae,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Le,e.filterBySearchTerm=Me,e.filterByStringComparePartially=Re,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=He();return`${ot(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>it(t,n),e.getMarkedMessageTopic=lt,e.getMarkerUserFeedTopic=ct,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=He();return`${ot(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=He();return`${ot(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=ut,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Cd,e.getSmartFeedChannelTopic=dt,e.getSmartFeedMessageTopic=ft,e.getSmartFeedSubChannelTopic=ht,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=He();return`${ot(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=at,e.isAfterBefore=Q,e.isAfterBeforeRaw=X,e.isCachable=ie,e.isFetcher=ne,e.isFresh=oe,e.isLocal=e=>ie(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=re,e.isOffline=se,e.isPaged=J,e.isReportedByMe=async(e,t)=>{var n;const r=we();r.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:s}=sh[e];if("message"===e){const{data:e}=await r.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{data:i}=await r.http.get(`/api/v3/${s}/${t}/isflagbyme`),{result:o,isFlagByMe:a}=null!=i?i:{};return null!==(n=null!=o?o:a)&&void 0!==n&&n},e.isSkip=Y,e.mergeInCache=ke,e.onChannelMarkerFetched=Lu,e.onFeedMarkerFetched=e=>{const t=we();return Ze(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=nu,e.onMessageMarked=Fu,e.onMessageMarkerFetched=Mu,e.onSubChannelMarkerFetched=Du,e.onSubChannelMarkerUpdated=Ou,e.onUserMarkerFetched=xu,e.onUserMarkerFetchedLegacy=Pu,e.pullFromCache=Ce,e.pushToCache=Te,e.queryCache=Se,e.queryOptions=le,e.queryRoles=Sd,e.restoreCache=async(e="amitySdk")=>{var t;const n=we();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=ce,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Fe,e.sortByFirstCreated=Ne,e.sortByFirstUpdated=$e,e.sortByLastActivity=Ke,e.sortByLastCreated=je,e.sortByLastUpdated=qe,e.sortByLocalSortingDate=Be,e.sortByName=Ue,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=pt,e.toPage=ee,e.toPageRaw=te,e.toToken=Z,e.upsertInCache=_e,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=we();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},reactNative);
5
+ var r=e("buffer"),o=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=r:(a(r,n),n.Buffer=s),s.prototype=Object.create(o.prototype),a(o,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(o(t)):null}function o(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function a(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function s(e){var t=a(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=s(e),this.encoding){case"utf16le":this.text=f,this.end=g,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var o=c(t[r]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(e.lastNeed=o-2),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}function d(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,n=d(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=p,i.prototype.text=h,i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),o=e("./util");function a(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=I,n.resolveObject=_,n.format=C,n.Url=a;var s=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(l),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],p=255,f=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&o.isObject(e)&&e instanceof a)return e;var r=new a;return r.parse(e,t,n),r}function C(e){return o.isString(e)&&(e=w(e)),e instanceof a?e.format():a.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function _(e,t){return e?w(e,!1,!0).resolveObject(t):t}a.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var a=e.indexOf("?"),i=-1!==a&&a<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(i);if(C=C.trim(),!n&&1===e.split("#").length){var I=c.exec(C);if(I)return this.path=C,this.href=C,this.pathname=I[1],I[2]?(this.search=I[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var _=s.exec(C);if(_){var S=(_=_[0]).toLowerCase();this.protocol=S,C=C.substr(_.length)}if(n||_||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||_&&y[_]||(C=C.substr(2),this.slashes=!0)}if(!y[_]&&(k||_&&!v[_])){for(var E,A,T=-1,M=0;M<h.length;M++)-1!==(O=C.indexOf(h[M]))&&(-1===T||O<T)&&(T=O);for(-1!==(A=-1===T?C.lastIndexOf("@"):C.lastIndexOf("@",T))&&(E=C.slice(0,A),C=C.slice(A+1),this.auth=decodeURIComponent(E)),T=-1,M=0;M<u.length;M++){var O;-1!==(O=C.indexOf(u[M]))&&(-1===T||O<T)&&(T=O)}-1===T&&(T=C.length),this.host=C.slice(0,T),C=C.slice(T),this.parseHost(),this.hostname=this.hostname||"";var P="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!P)for(var R=this.hostname.split(/\./),U=(M=0,R.length);M<U;M++){var x=R[M];if(x&&!x.match(f)){for(var j="",D=0,N=x.length;D<N;D++)x.charCodeAt(D)>127?j+="x":j+=x[D];if(!j.match(f)){var B=R.slice(0,M),F=R.slice(M+1),q=x.match(g);q&&(B.push(q[1]),F.unshift(q[2])),F.length&&(C="/"+F.join(".")+C),this.hostname=B.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var L=this.port?":"+this.port:"",$=this.hostname||"";this.host=$+L,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!m[S])for(M=0,U=d.length;M<U;M++){var K=d[M];if(-1!==C.indexOf(K)){var z=encodeURIComponent(K);z===K&&(z=escape(K)),C=C.split(K).join(z)}}var V=C.indexOf("#");-1!==V&&(this.hash=C.substr(V),C=C.slice(0,V));var Q=C.indexOf("?");if(-1!==Q?(this.search=C.substr(Q),this.query=C.substr(Q+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,Q)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[S]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){L=this.pathname||"";var H=this.search||"";this.path=L+H}return this.href=this.format(),this},a.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",a=!1,s="";this.host?a=e+this.host:this.hostname&&(a=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(a+=":"+this.port)),this.query&&o.isObject(this.query)&&Object.keys(this.query).length&&(s=b.stringify(this.query));var i=this.search||s&&"?"+s||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==a?(a="//"+(a||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):a||(a=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+a+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},a.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},a.prototype.resolveObject=function(e){if(o.isString(e)){var t=new a;t.parse(e,!1,!0),e=t}for(var n=new a,r=Object.keys(this),s=0;s<r.length;s++){var i=r[s];n[i]=this[i]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var d=c[l];"protocol"!==d&&(n[d]=e[d])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var p=u[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,I=C,_=n.pathname&&n.pathname.split("/")||[],S=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(S&&(n.hostname="",n.port=null,n.host&&(""===_[0]?_[0]=n.host:_.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),C=C&&(""===f[0]||""===_[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,_=f;else if(f.length)_||(_=[]),_.pop(),_=_.concat(f),n.search=e.search,n.query=e.query;else if(!o.isNullOrUndefined(e.search))return S&&(n.hostname=n.host=_.shift(),(M=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=M.shift(),n.host=n.hostname=M.shift())),n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!_.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=_.slice(-1)[0],E=(n.host||e.host||_.length>1)&&("."===k||".."===k)||""===k,A=0,T=_.length;T>=0;T--)"."===(k=_[T])?_.splice(T,1):".."===k?(_.splice(T,1),A++):A&&(_.splice(T,1),A--);if(!C&&!I)for(;A--;A)_.unshift("..");!C||""===_[0]||_[0]&&"/"===_[0].charAt(0)||_.unshift(""),E&&"/"!==_.join("/").substr(-1)&&_.push("");var M,O=""===_[0]||_[0]&&"/"===_[0].charAt(0);return S&&(n.hostname=n.host=O?"":_.length?_.shift():"",(M=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=M.shift(),n.host=n.hostname=M.shift())),(C=C||n.host&&_.length)&&!O&&_.unshift(""),_.length?n.pathname=_.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},a.prototype.parseHost=function(){var e=this.host,t=i.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function o(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return o}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==St?St:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),o=t[t.length-1];return"function"==typeof r&&r!==o&&Object.keys(o).forEach((function(e){r[e]=o[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=o;var r=Object.prototype.hasOwnProperty;function o(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var o in n)r.call(n,o)&&(e[o]=n[o])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,o=arguments.length;n<o;n++)t.push(arguments[n]);return t}function o(e,t,n){var r=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function a(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function s(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,r){if(!(this instanceof i))return new i(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=i,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,o=this.head;null!==o;)n.push(e.call(t,o.value,this)),o=o.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,o=this.tail;null!==o;)n.push(e.call(t,o.value,this)),o=o.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var o=0;null!==r;o++)n=e(n,r.value,o),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var o=this.length-1;null!==r;o--)n=e(n,r.value,o),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=0,a=this.head;null!==a&&o<e;o++)a=a.next;for(;null!==a&&o<t;o++,a=a.next)n.push(a.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=this.length,a=this.tail;null!==a&&o>t;o--)a=a.prev;for(;null!==a&&o>e;o--,a=a.prev)n.push(a.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,a=this.head;null!==a&&r<e;r++)a=a.next;var s=[];for(r=0;a&&r<t;r++)s.push(a.value),a=this.removeNode(a);for(null===a&&(a=this.tail),a!==this.head&&a!==this.tail&&(a=a.prev),r=0;r<n.length;r++)a=o(this,a,n[r]);return s},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var Tt=kt(At.exports);class Mt{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 Ot=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Mt},Pt=()=>b.default.v4().toString();let Rt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Pt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:o})=>{o.tabId!==e&&("startup"===o.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Rt}),"identify"===o.type&&void 0!==o.tabIndex&&o.tabId&&(t[o.tabId]=o.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Rt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Ut=async()=>{const e=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(Ot().localStorage.getItem(e))}))})("deviceId");if(e)return e;const t=`ascWebSdk#${Pt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{Ot().localStorage.setItem(e,t),n(!0)})))("deviceId",t),t},xt=()=>{const e=(()=>{var e,t;return(null===(e=gt.versions)||void 0===e?void 0:e.node)?gt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:R}},jt=1e3;var Dt;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Dt||(Dt={}));const Nt=e=>{let t;return{connect:async function(n){const r=await(async e=>`mqttjs_${await Ut()}_${e}_${Rt}`)(n.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Tt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:jt,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=jt,(()=>{const e=[ht(ct()),ht(lt()),ht(dt()),ht(ut()),ht(at(ze())),ht(it())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||jt),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return 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,n){const r=(t,r)=>{var o;if(t||128===(null===(o=r[0])||void 0===o?void 0:o.qos)){const r=t?new pe(t.message,8e5,"error"):new ge(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Bt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const o=ue[e];if(!o)return;const a=de(o);a&&r.forEach((e=>{(n?_e:ke)([o,"get",a(e)],e,t)}))}))},Ft=(e,t)=>{const{log:n,cache:r}=be(),o=[e,q,t],a={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:o,data:a}),Ee([e,"get",t],!0),_e(o,a))};function qt(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 o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}const Lt=(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(!be().cache)return;return(null===(n=Ie(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},$t=(e,t,n="userId",r="user")=>{const o=e,a=t,s=o[a],i=qt(o,["symbol"==typeof a?a:a+""]),c=Lt(s,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function Kt(e){return e.map((e=>{var{isMentioned:t}=e,n=qt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function zt(e){return Kt(e)}function Vt(e){return Kt(e)}const Qt=e=>{var t,n;return null!==(n=null===(t=Ie(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Ht=["analytic","normal-priority"],Wt=["analytic","high-priority"],Gt=async e=>{const t=be(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class Jt{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=Ie(Ht);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Gt(t),Ee(Ht)}catch(e){this.stop(),Ee(Ht)}}async syncHighPriorityCapturedEvent(){try{const e=Ie(Wt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Gt(t),Ee(Wt)}catch(e){this.stop(),Ee(Wt)}}}class Yt{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({itemId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,o=(()=>n?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*B);return!(r.getTime()-o.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,n={event:[]},r=Ie(Ht);(null==r?void 0:r.data)&&(n.event=r.data.event),n.event.length>=this._poolLimit&&n.event.shift(),n.event.push({contentId:e,contentType:"post",activityType:"view",timestamp:t.toISOString()}),ke(Ht,n),this._recentViewed[e]=t}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({itemId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const o={event:[]},a=Ie(Wt);if((null==a?void 0:a.data)&&(o.event=a.data.event),o.event.length>=this._poolLimit&&o.event.shift(),o.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),ke(Wt,o),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;_e(["story-seen","get",e.storyId],(new Date).toISOString());const s=Ie(["story-last-seen",e.targetId]);(null==s?void 0:s.data)?new Date(s.data).getTime()<new Date(e.expiresAt).getTime()&&_e(["story-last-seen",e.targetId],e.expiresAt):_e(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Xe("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Ee(Ht),Ee(Wt)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class Xt{constructor(){this._client=be(),this._eventCapturer=new Yt,this._eventSyncer=new Jt}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let Zt;var en=()=>(Zt||(Zt=new Xt),Zt);const tn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let n={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const r=Ie(["file","get",`${e.avatarFileId}`]);return(null==r?void 0:r.data)&&(n=null==r?void 0:r.data),n}});class nn{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Ie(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ie(["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=Ie(["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 Ie(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Ce(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r}}=t;return n===this._targetId&&(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 rn=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:o,targetUpdatedAt:a,localFilter:s}=e,i=new nn(n,r,o);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:a,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:s,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},on=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=Ie(["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=Ie(["user","get",e.userId]);if(null==t?void 0:t.data)return tn(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ie(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>on(e)))}}),an=(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=Ie(["messageMarker","get",de("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},sn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Ie(n))||void 0===t?void 0:t.data,o=Ce(["subChannelUnreadInfo","get"]);let a=0,s=!1;if(o&&(null==o?void 0:o.length)>0){const t=null==o?void 0:o.filter((({data:t})=>t.channelId===e&&!t.isDeleted));a=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),s=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:a,isMentioned:s});return _e(n,i),i};class cn{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=be(),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=Ce(["readReceipt"]))||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=Ie(["readReceipt",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:o}=n,a=await(async({subChannelId:e,readToSegment:t})=>{const n=be();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:o});if(a){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Ie(["readReceipt",r]))||void 0===t?void 0:t.data;_e(["readReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:o}))}else a||(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],o=null===(n=Ie(r))||void 0===n?void 0:n.data;if(o&&t>o.readToSegment){o.readToSegment=t,o.unreadCount=Math.max(o.lastSegment-t,0);const e=sn(o.channelId);Xe("local.channelUnread.updated",e),_e(r,o),Xe("local.subChannelUnread.updated",o)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Ie(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)_e(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{_e(["readReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let o=this.getSyncJob(e);null===o||"syncing"===o.syncState?(o={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(o)):o.segment<t&&(o.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 ln=null;var dn=()=>(ln||(ln=new cn),ln);const un=e=>{const{subChannelId:t,channelSegment:n}=e;dn().markRead(t,n)},hn=async e=>{const t=be();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:o,userFeedMarkers:a}=n,s=qt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=zt(o),l=Vt(a);return t.cache&&Bt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},s),{cachedAt:i}),Xe("local.channelMarker.updated",{userEntityMarkers:c}),Xe("local.subChannelMarker.updated",{userFeedMarkers:l}),!0},pn={comment:on,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{en().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Ie(["comment","get",e]))||void 0===t?void 0:t.data;return n?on(n):null})).filter(Boolean)||[]},get creator(){const t=Ie(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return tn(t.data)}}),user:tn,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let n={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const r=Ie(["file","get",`${e.avatarFileId}`]);return(null==r?void 0:r.data)&&(n=null==r?void 0:r.data),n}}),story:e=>{const t=en(),n=Ie(["storyTarget","get",e.targetId]),r=Ie(["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=Ie(["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:o}=r;return o||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Ie(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:o}=r;return o?Object.assign(Object.assign({},o),{fileUrl:`${o.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Ie(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ie(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return tn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return rn(n.data)},get isSeen(){const t=Ie(["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,o=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,a=new Date(e.expiresAt).getTime();return Math.max(r,o)>=a}})},storyTarget:rn,message:e=>{const t=qt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return an(e).readCount},get deliveredCount(){return an(e).deliveredCount},markRead:()=>un(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ie(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return tn(n)}}),channel:e=>Object.assign(Object.assign({},e),{markAsRead:()=>hn(e.channelInternalId)})},fn=e=>{var t;const n=e.messagePreviewId?Qt(e.channelId):null,r=null===(t=Ie(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,o=n?Object.assign(Object.assign({},n),{user:r?pn.user(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:o})},gn=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:o,messageFeedId:a,data:s,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:o,subChannelId:a,data:s,dataType:i,isDeleted:c,segment:l,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}})(t))))&&void 0!==n?n:[]};Bt(r)},mn=e=>{var t,n;return null!==(n=null===(t=Ie(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},yn=e=>{var t;const n=e.messagePreviewId?mn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Ie(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},vn=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:o,messageFeedId:a,messageId:s,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:s,channelId:o,subChannelId:a,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Bt(r)};function bn(e){const t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,n),t}function wn(e,t,n){_e(["subChannel","get",e],Object.assign(bn(t),n))}const Cn=async e=>{var t,n,r,o;const{channelId:a,messageId:s,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Ie(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(n=Ie(["subChannel","get",h]))||void 0===n?void 0:n.data;_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:a,creatorId:i,messagePreviewId:s,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),wn(e.subChannelId,t,{messagePreviewId:s})}const m=null===(r=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(o=Ie(["subChannel","get",h]))||void 0===o?void 0:o.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:a,creatorId:i,messagePreviewId:s,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},In=async e=>{var t,n,r,o;const{channelId:a,messageId:s,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Ie(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(n=Ie(["subChannel","get",h]))||void 0===n?void 0:n.data;wn(e.subChannelId,t,{messagePreviewId:s}),_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:a,creatorId:i,messagePreviewId:s,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(r=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(o=Ie(["subChannel","get",h]))||void 0===o?void 0:o.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:a,creatorId:i,messagePreviewId:s,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},_n=async e=>{var t,n,r,o;const{channelId:a,subChannelId:s}=e,i=null===(t=Ie(["messagePreviewChannel","get",a]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===s){const e=null===(n=Ie(["subChannel","get",s]))||void 0===n?void 0:n.data;_e(["messagePreviewChannel","get",a],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Ie(["messagePreviewSubChannel","get",s]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(o=Ie(["subChannel","get",s]))||void 0===o?void 0:o.data;_e(["messagePreviewSubChannel","get",s],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Sn=(e,t)=>{var n,r,o,a,s;const i=be();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ie(["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!==(s=null!==(o=null==t?void 0:t.unreadCount)&&void 0!==o?o:null===(a=(e=>{var t;const n={entityId:e,userId:ze()._id};return null===(t=Ie(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===a?void 0:a.unreadCount)&&void 0!==s?s:0},kn=(e,t)=>{var n,r,o,a;const s=be();return s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ie(["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!==(a=null===(o=(e=>{var t;const n={entityId:e,userId:ze()._id};return null===(t=Ie(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===o?void 0:o.hasMentioned)&&void 0!==a&&a},En=["broadcast","conversation","community"],An=({type:e})=>En.includes(e);function Tn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const o=null===(n=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==o?void 0:o.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=o.messagePreviewId),Object.assign(Object.assign({get unreadCount(){return Sn(e)},get hasMentioned(){return kn(e)},get isMentioned(){return kn(e)},get subChannelsUnreadCount(){return Sn(e)}},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:An(e),messagePreviewId:r})}const Mn=(e,t={isMessagePreviewUpdated:!0})=>{Bt({channels:e.channels.map((e=>Tn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},On=async(e,t={isMessagePreviewUpdated:!0})=>{const n=be(),r=await n.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&gn(e);const o=e.channels.filter(An).map((({channelInternalId:e})=>e));if(o.length>0){Mn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=be();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:o}=n,a=zt(r),s=t.cache&&Date.now();return t.cache&&Bt({userEntityMarkers:a,userMarkers:o},{cachedAt:s}),Xe("local.channelMarker.fetched",{userEntityMarkers:a}),Xe("local.userMarker.fetched",{userMarkers:o}),{data:a,cachedAt:s}})(o)}catch(e){}}const a=e.channels.map((e=>Tn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=Lt(e.channelUsers),i=qt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{channels:a,channelUsers:s})},Pn=async e=>{const t=be();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Xe("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Rn=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,o={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};Bt({subChannelUnreadInfo:[o]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{sn(e)}))}},Un=async e=>{const t=be(),n=await Pn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:o}=n;Rn({feedMarkers:r,userFeedMarkers:o}),t.log("channel/prepareUnreadCountInfo",e.channels)},xn=async e=>{const t=be();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=>{Q(null==t?void 0:t.code)&&Ft("channel",e)})),t}const o=await On(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Un(r);const a=t.cache&&Date.now();return t.cache&&Bt(o,{cachedAt:a}),Xe("local.channel.fetched",o.channels),{data:o.channels.map((e=>pn.channel(e))),cachedAt:a}};xn.locally=e=>{var t,n;const r=be();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const o=null===(t=Ce(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!o||(null==o?void 0:o.length)<e.length)return;const a=o.map((({data:e})=>e)),s=null===(n=o.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:a.map((e=>pn.channel(e))),cachedAt:s.cachedAt}};const jn=async()=>{const e=be();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&&Bt({userMarkers:n},{cachedAt:r}),Xe("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}},Dn=e=>!0===e&&void 0;function Nn(e,t,n){var r,o;if(n)return n.hasMentioned;const a=be();if(a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()){const e=null===(r=Ie(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const s={entityId:e,feedId:t,userId:ze()._id},i=null===(o=Ie(["subChannelMarker","get",de("subChannelMarker")(s)]))||void 0===o?void 0:o.data;return!!i&&i.hasMentioned}const Bn=["broadcast","conversation","community"],Fn=({channelType:e})=>Bn.includes(e);function qn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:o,creatorId:a,creatorPublicId:s,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=qt(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,o;if(n)return n.unreadCount;const a=be();if(a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()){const e=null===(r=Ie(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const s={entityId:e,feedId:t,userId:ze()._id},i=null===(o=Ie(["subChannelMarker","get",de("subChannelMarker")(s)]))||void 0===o?void 0:o.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return Nn(t,l)},get isMentioned(){return Nn(t,l)}},u),{channelId:n,creatorId:s,displayName:d,lastActivity:c,latestMessageId:i,messageCount:o,subChannelId:l,isUnreadCountSupport:Fn({channelType:r})})}function Ln(e,t,n){var r;const{channelPublicId:o,childCount:a,creatorPublicId:s,mentionedUsers:i,messageFeedId:c,myReactions:l,reactionCount:d,reactions:u,referenceId:h,segment:p,messageId:f,creatorId:g}=e,m=qt(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let y;h&&(y=Ie(["message","get",h])),y||(y=Ie(["message","get",f]));const v=Object.assign(Object.assign({},m),{messageId:f,channelId:o,channelSegment:p,childrenNumber:a,creatorId:s,creatorPrivateId:e.creatorId,reactions:null!=u?u:{},myReactions:l||(null!==(r=null==y?void 0:y.data.myReactions)&&void 0!==r?r:[]),reactionsCount:d,subChannelId:c,uniqueId:y?y.data.uniqueId:f,referenceId:h});return i&&(v.mentionees=i.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=be(),o=Ie(["message","get",e.messageId]),a=(null==o?void 0:o.data.myReactions)||[];Object.assign(e,{myReactions:a});const s=t[0];s&&s.userId===r.userId&&("message.reactionAdded"!==n||a.includes(s.reactionName)||Object.assign(e,{myReactions:[...a,s.reactionName]}),"message.reactionRemoved"===n&&a.includes(s.reactionName)&&Object.assign(e,{myReactions:a.filter((e=>e!==s.reactionName))}))})(v,t,n),v}const $n={},Kn=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Bt({messages:(r=e).messages.map((e=>Ln(e,r.reactions)))});const t=n.join("");$n[t]&&clearTimeout($n[t]),$n[t]=setTimeout((()=>{try{(async e=>{const t=be();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:o,userMarkers:a}=n,s=t.cache&&Date.now();t.cache&&Bt({contentMarkers:r,feedMarkers:o,userMarkers:a},{cachedAt:s}),Xe("local.feedMarker.fetched",{feedMarkers:o}),Xe("local.messageMarker.fetched",{contentMarkers:r}),Xe("local.userMarker.fetched",{userMarkers:a})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:o}=e,a=qt(e,["messageFeeds"]);return o&&o.length>0&&(null==o||o.forEach((e=>{var t,n;const r=null!==(n=null===(t=Ie(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},o=qt(qn(e),["unreadCount","hasMentioned","isMentioned"]);wn(e.messageFeedId,r,o)}))),Object.assign(Object.assign({},a),{messages:e.messages.map((n=>Ln(n,e.reactions,t)))})};function zn(e){var{subChannelId:t,mentionees:n,dataType:r,data:o}=e,a=qt(e,["subChannelId","mentionees","dataType","data"]);return r===O.IMAGE||r===O.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},o)},a):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:o},a)}function Vn(e){var{sortBy:t,subChannelId:n,tags:r,includingTags:o,excludingTags:a,includeDeleted:s,aroundMessageId:i,limit:c,type:l}=e,d=qt(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const u=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:Dn(s),options:{sortBy:t,limit:c||U,around:i}});return r&&(u.includeTags=r),o&&(u.includeTags=o),l&&(u.dataType=l),a&&(u.excludeTags=a),u}const Qn=["broadcast","conversation","community"],Hn=({channelType:e})=>Qn.includes(e),Wn=async e=>{const t=e.messageFeeds.filter(Hn).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Bt({messageFeeds:e.messageFeeds.map((e=>qn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=be();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Y(t,"skiplimit")}}}),{paging:o}=r,a=qt(r,["paging"]),{userEntityMarkers:s,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=a;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&Rn({feedMarkers:l,userFeedMarkers:i});const d=zt(s),u=Vt(i),h=n.cache&&Date.now();n.cache&&Bt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Xe("local.channelMarker.fetched",{userEntityMarkers:d}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:u}),Xe("local.userMarker.fetched",{userMarkers:c});const p=X(o.next);return{data:u,cachedAt:h,prevPage:X(o.previous),nextPage:p}})(t)}catch(e){}}vn(e);const n=e.messageFeeds.map(qn),r=e.messages.map((e=>Ln(e)));return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r})};class Gn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let Jn;var Yn=()=>(Jn||(Jn=new Gn),Jn);const Xn=e=>Yn().onSessionStateChange(e),Zn=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},er=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},tr=(e,t)=>{const{log:n,cache:r}=be(),o=[e,q,t];if(!r)return;n("cache/api/isInTombstone",o);const a=Ie(o),{lifeSpan:s}=se("cache_then_server",18e4);if(a&&oe(a.data,s))throw new fe("Item not found!",400400,"error")},nr=async e=>{const t=be();t.log("channel/getSubChannel",e),tr("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Wn(n.data),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),Xe("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:o}}catch(t){throw Q(null==t?void 0:t.code)&&Ft("subChannel",e),t}};nr.locally=e=>{const t=be();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Ie(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};let rr=!1,or=[];const ar={},sr=async()=>{const e=Object.entries(ar).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=be();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:a,userMarkers:s}=n,i=zt(r),c=Vt(o),l=t.cache&&Date.now();return t.cache&&Bt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:s},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:a}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:s}),!0})(e)},ir=()=>{rr=!1},cr=()=>(rr=!0,Xn((e=>{"notLoggedIn"===e&&ir()})),()=>{ir()}),lr=async e=>{const t=await(async e=>{const t=nr.locally(e);if(t)return t.data.channelId;const{data:n}=await nr(e);return n.channelId})(e),n=st({channelId:t,subChannelId:e});or.push(ht(n))};Zn((async()=>{rr&&await sr()}),3e4);const dr=async e=>{const t=be();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Wn(n.data),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),Xe("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:o}};dr.locally=e=>{var t;const n=be();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Ie(["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 ur=async(e=!0)=>{var t;const n=null===(t=Ie(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var o;return(o=r).messagePreview.enabled?o.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},hr=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},pr=(e,t)=>{var n;const r=null===(n=Ie(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},fr=e=>{const{userId:t}=be();return{currentUser:()=>pr(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const o=null===(r=Ie(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!o&&(!!o.permissions.some((e=>e===t))||pr(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const o=null===(r=Ie(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!o&&(!!o.permissions.some((e=>e===t))||pr(e,t))})(t,e,n)}},gr=async e=>{const t=be();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},mr=async e=>{const t=be();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},yr=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},vr={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},br=e=>{const t=be();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>vr[e].includes(t))(n,e))throw new pe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,Yn().setSessionState(e),!0},wr=async e=>{const t=be();br("establishing");const{accessToken:n,users:r,expiresAt:o,issuedAt:a}=await(async e=>{const t=be();t.log("client/api/getToken",e);const n=xt(),{data:r}=await t.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:n}),{headers:{"X-API-Key":t.apiKey}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:o,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:a,expiresAt:o},br("established"),{accessToken:n,users:r}},Cr=e=>{const t=Ce(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{_e(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ir=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Ie(n))||void 0===t?void 0:t.data)&&Ee(n)},_r=e=>{const t=be();return Ye(t,"onChannelDeleted","channel.deleted",(async n=>{const r=await On(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.channels.forEach((e=>{Cr(e.channelId),Ir(e.channelId)})),Bt(r),e(r.channels[0])}))},Sr=e=>{const t=be();return Ye(t,"onChannelMemberBanned","channel.banned",(async n=>{const r=await On(n),{channels:o,channelUsers:a}=r,s=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&r.channels.forEach((e=>{Cr(e.channelId),Ir(e.channelId)})),Bt(r),e(o[0],a.find((e=>"banned"===e.membership)))}))},kr=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{n.cache&&Bt(e),t(e.users[0])}))},Er=e=>kr("user.deleted",e);class Ar{constructor(){this.TIMER_INTERVAL_MS=N,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(er((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{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=>{const{data:t}=await xn(e);Xe("local.channel.resolved",t)})(e),t.length>0&&(async e=>{const t=await Pn(e),{feedMarkers:n,userFeedMarkers:r}=t;Rn({feedMarkers:n,userFeedMarkers:r}),Xe("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 Tr=null;var Mr=()=>(Tr||(Tr=new Ar),Tr);const Or=async()=>{const e=be();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&br("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},Pr=e=>{const t=be();br("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,Or()},Rr=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Ur=e=>{const t=be(),n=Rr.map((n=>Ye(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new pe(t.message,t.code,"fatal"):new me(n);e(r)}))));return()=>{n.forEach((e=>e()))}},xr=e=>{const t=be();return Ye(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},jr=e=>{const t=de("channelMarker")({userId:ze()._id,entityId:e.channelId});Ee(["channelMarker","get",t],!0)},Dr=e=>{const t=be();return Ye(t,"onChannelCreated","channel.created",(async t=>{const n=await On(t);Bt(n),e(n.channels[0])}))},Nr=e=>{const t=be(),n=[Ye(t,"onChannelUpdated","channel.updated",(async t=>{const n=await On(t);Bt(n),e(n.channels[0])})),Ye(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{n.forEach((e=>e()))}},Br=e=>{const t=be();return Ye(t,"onChannelJoined","channel.joined",(async t=>{const n=await On(t),{channels:r,channelUsers:o}=n;Bt(n),e(r[0],o[0])}))},Fr=e=>{const t=be();return Ye(t,"onChannelLeft","channel.left",(async n=>{const{userId:r}=be(),{channelUsers:o}=n,a=o.some((e=>e.userId===r)),s=await On(n,{isMessagePreviewUpdated:a});t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a&&s.channels.forEach((e=>{Cr(e.channelId),Ir(e.channelId)}));const{channels:i,channelUsers:c}=s;Bt(s),e(i[0],c[0])}))},qr=e=>{const t=be();return Ye(t,"onChannelMuted","channel.setMuted",(async t=>{const n=await On(t);Bt(n),e(n.channels[0])}))},Lr=e=>{const t=be();return Ye(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const n=await On(t),{channels:r,channelUsers:o}=n;Bt(n),e(r[0],o.find((e=>"member"===e.membership)))}))},$r=e=>{const t=be();return Ye(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const n=await On(t),{channels:r,channelUsers:o}=n;Bt(n),e(r[0],o[0])}))},Kr=e=>{const t=be();return Ye(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const n=await On(t),{channels:r,channelUsers:o}=n;Bt(n),e(r[0],o.find((e=>"none"===e.membership)))}))},zr=e=>{const t=be();return Ye(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))},Vr=e=>{const t=be();return Ye(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))},Qr=e=>{const t=be();return Ye(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Bt(t),e(t.feedMarkers[0])}))},Hr=e=>{const t=be(),n=ze(),r=[Ye(t,"message/onMessageCreated","message.created",(async r=>{const o=await Kn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=be(),r=["subChannelUnreadInfo","get",e.messageFeedId],o=null===(t=Ie(r))||void 0===t?void 0:t.data;if(!o)return;const a=o.lastSegment<e.segment?e.segment:o.lastSegment,s=a-o.readToSegment;let{lastMentionSegment:i}=o;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(i=e.segment)}));const c=Object.assign(Object.assign({},o),{lastMentionSegment:i,lastSegment:a,isMentioned:!(o.readToSegment>=i),unreadCount:Math.max(s,0)});_e(r,c)})(e),sn(e.channelId)})),Bt(o),o.messages.forEach((t=>{t.creatorPrivateId===n._id&&un(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Wr=e=>{const t=be(),n=[Ye(t,"message/onMessageCreated","local.message.created",(t=>t.messages.forEach((t=>{e(t)}))))];return()=>{n.forEach((e=>e()))}},Gr=e=>{const t=be();return Ye(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Wn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:o}=e,a={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:o};_e(["subChannelUnreadInfo","get",a.subChannelId],a)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Bt(r),e(r.messageFeeds[0])}))},Jr=e=>{const t=be(),n=[Ye(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Wn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Ie(n))||void 0===t?void 0:t.data;r&&_e(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),sn(e.channelId)})),Bt(r),e(r.messageFeeds[0])})),Ye(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Yr=async e=>{const t=be();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:a,userMarkers:s}=n,i=zt(r),c=Vt(o),l=t.cache&&Date.now();return t.cache&&Bt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:s},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:a}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:s}),{data:n,hasMore:n.feedMarkers.length>0}},Xr=()=>{const e=be();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new pe("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)};let Zr=!1,eo=[],to=!1,no=!0,ro=null;const oo=e=>{null!=e&&(!ro||e.getTime()>ro.getTime())&&(ro=e)},ao=async()=>{const{data:e}=await jn();null!=e&&oo(new Date(e.lastSyncAt))};let so=[];const io=e=>{so=e},co=e=>so.push(e),lo=async()=>{if(!to&&0!==so.length)try{to=!0,so=[];const e=await Yr((null==ro?new Date:ro).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);oo(t),e.hasMore&&so.push("has_more")}catch(e){}finally{to&&(to=!1)}},uo=()=>{eo.length>0||eo.push(er((()=>{so.push("resume")})),Hr((e=>{const t=be();Hn(e)&&e.creatorId!==t.userId&&so.push("new message")})),Dr((()=>so.push("subchannel is created"))),_r((()=>so.push("subchannel is deleted"))),Br((()=>so.push("subchannel is joined"))),Fr((()=>so.push("subchannel is left"))),Gr((()=>so.push("subchannel is created"))),Jr((()=>setTimeout((()=>so.push("subchannel is deleted")),2e3))),Qr((()=>so.push("feed marker updated"))),(e=>{const t=be();return Ye(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:n,userEntityMarkers:r,userFeedMarkers:o}=t,a=qt(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),s=zt(r),i=Vt(o);Bt(Object.assign({userMarkers:n,userEntityMarkers:s,userFeedMarker:i},a)),e(n[0])}))})((()=>so.push("feed marker updated"))),(e=>{const t=be();return Ye(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{t.feedMarkers.forEach((t=>{e(t)}))}))})((()=>so.push("feed marker updated"))))},ho=()=>{eo.forEach((e=>e())),eo=[]},po=async()=>(await ao(),co("start syncing"),no=!0,Zr=!0,uo(),ho),fo=()=>{Zr=!1,io([]),ho()};Zn((async()=>{Zr&&await lo()}),2e3);const go=()=>no;let mo=[];const yo=async(e,t,n)=>{const r=be();let o;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await Or(),mo.forEach((e=>e())),mo=[]);const a=await Ut();try{const{users:n}=await wr(Object.assign(Object.assign({},e),{displayName:(null==e?void 0:e.displayName)||e.userId,deviceId:(null==e?void 0:e.deviceId)||a})),c=n.find((t=>t.userId===e.userId));if(null==c)throw new pe(`${e.userId} has not been founded`,8e5,"error");if(c.isDeleted)return Pr("userDeleted"),!1;if(c.isGlobalBanned)return Pr("globalBan"),!1;s=r.ws,i=r.emitter,Ge.forEach((e=>{s.on(e,(t=>{i.emit(e,t)}))})),r.ws.open(),r.userId=c.userId,r.sessionHandler=t,o=r.accessTokenExpiryWatcher(t),Ve(c)}catch(e){throw br("notLoggedIn"),e}var s,i;if(!0!==(null==n?void 0:n.disableRTE)&&async function(){await tt()}(),await(async()=>{var e;const t=await ur();if(t===(null===(e=Ie(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;_e(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Ce(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Ee(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=Ce(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Ee(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await xn(n),0!==r.length&&await dr(r)}})(),0===mo.length){mo.push(xr((e=>{Pr("globalBan"),mo.forEach((e=>e())),o()})),(e=>{const t=be();return Ye(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{Pr(),mo.forEach((e=>e())),o()})),Er((e=>{e.userId===r.userId&&(Pr("userDeleted"),mo.forEach((e=>e())),o())})),(e=>{const t=be();return Ye(t,"client/onTokenExpired","tokenExpired",e)})((e=>{br(e),Or(),mo.forEach((e=>e()))})),_r(jr),Sr(jr),cr(),(()=>{const e=en();return e.established(),Xn((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=dn();return e.startSyncReadReceipt(),Xn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Mr();return e.startResolver(),Xn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await po();mo.push(e)}return!0},vo=()=>{let e,t=!1;const n=be();n.log("initiating access token renewal");const r=async r=>{const{userId:o,displayName:a}=ze(),s={userId:o,displayName:a,authToken:r,deviceId:await Ut()};"tokenExpired"===n.sessionState&&n.sessionHandler?await yo(s,n.sessionHandler):await wr(s),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(vo())}),F)}}},bo=3e5,wo=e=>{const t=setInterval((()=>{const t=be();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-bo)(r))return Xe("tokenExpired","tokenExpired"),void We((()=>e.sessionWillRenewAccessToken(vo())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),o=Date.parse(n),a=Date.now();return a>o+.8*(r-o-bo)&&a<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(vo())}),F);return()=>clearInterval(t)},Co=e=>{const t=be();return Ye(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Io=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},_o=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},So=e=>{const t=be();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},ko=e=>{const t=be();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},Eo=e=>{const t=be();return Ye(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Ao=e=>{const t=be();return Ye(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,o;Bt(t);const a=Ce(["message","collection"]),{contentMarkers:s,feedMarkers:i}=t;if(a&&(null==a?void 0:a.length)>0&&(null==i?void 0:i.length)>0){const e=a.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)===i[0].feedId}));if(e.length>0&&(null==s?void 0:s.length)>0){(null!==(o=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Ie(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==o?o:[]).forEach((e=>{var t,n;const r=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],o=null===(t=Ie(r))||void 0===t?void 0:t.data;if(!o)return;const a=s[0].feedId===o.feedId,i=s[0].readCount>o.readCount,c=(null===(n=s[0])||void 0===n?void 0:n.deliveredCount)>o.deliveredCount;if(a){const e=Object.assign(Object.assign({},o),{readCount:i?s[0].readCount:o.readCount,deliveredCount:c?s[0].deliveredCount:o.deliveredCount});_e(r,e)}}))}}e(t.contentMarkers[0])}))};function To(e){return"object"==typeof e&&null!==e}const Mo=e=>{if(!To(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)},Oo=e=>{if(!To(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};function Po(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(!Po(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=>Po(e[n],t[n])))}const Ro=(e,t,n,r,o,a)=>{const{forceDispatch:s,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},a),{cache:l}=be();let d;l||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],p=e=>{const{data:n}=e,r=qt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Mo(n)};return h.push(...o.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&Po(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,s)))))),(()=>{const t=ae(r,e,!0);ie(t,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{-5===o?(p({data:t,origin:r,loading:!1,error:new fe(D,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Uo=Object.freeze({__proto__:null,getActiveClient:be,getActiveUser:ze,setActiveUser:Ve,createClient:(e,t=yt.SG,{debugSession:n="amity",apiEndpoint:r}={})=>{var o,a;const s=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!mt,n=f.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);s("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const i=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:bt("http",t),c=null!==(a=null==r?void 0:r.mqtt)&&void 0!==a?a:bt("mqtt",t),l=_t(i),d=(e=>{const t=y.default(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(i),u=Nt(c),h=p.default(),g={version:`${R}`,apiKey:e,log:s,cache:{data:{}},http:l,ws:d,mqtt:u,emitter:h,sessionState:"notLoggedIn",accessTokenExpiryWatcher:wo,sessionHandler:undefined,hasPermission:fr,validateUrls:gr,validateTexts:mr,getFeedSettings:yr,getSocialSettings:hr,getMessagePreviewSetting:ur,use:()=>we(g),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:go};try{const t=be();if(t.apiKey===e)return t;we(g)}catch(e){we(g)}return g},login:yo,logout:Or,secureLogout:async()=>{const e=be(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Or()},isConnected:()=>{var e,t;const n=be();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)&&n.ws.connected)},getFeedSettings:yr,renewal:vo,markerSync:Yr,enableUnreadCount:Xr,registerPushNotification:async e=>{const t=be();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new ye("Unsupported platform");n=l.Platform.OS;const r=Ut(),{data:{status:o,error:a}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(a)throw new fe(a,5e5,"error");return"success"===o},unregisterPushNotification:async()=>{const e=be(),t=Ut(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new fe(r,5e5,"error");return"success"===n},onConnectionError:Ur,onClientDisconnected:e=>Ur((({code:t})=>{800211===t&&e()})),onClientBanned:xr,onSessionStateChange:Xn,getTotalUnreadCount:e=>{const{_id:t}=ze();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");return Ro(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await jn();return{data:e,cachedAt:t}}),[ko],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=ze();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=be();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const o=[];let a,s=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;a=r?Mo(r):r,e({data:r?Object.assign(Object.assign({},r),{hasMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return o.push(So((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),o=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),s={unreadCount:null!==(n=null==o?void 0:o.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};Po(a,s)||i({loading:!1,data:s})})(e)))),(()=>{const e=ae(jn);ie(e,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(-5===a?(i({data:t,origin:r,loading:!1,error:new fe(D,800800,"error")}),s=!0,o.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&o.forEach((e=>e())))}))})(),()=>{o.forEach((e=>e()))}},getMarkerSyncEvents:()=>so,setMarkerSyncEvents:io,pushMarkerSyncEvent:co,markerSyncTrigger:lo,startMarkerSync:po,startUnreadSync:async()=>{await ao(),co("start syncing"),Xr(),no=!1,Zr=!0,uo()},stopUnreadSync:fo,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),fo()),getMarkerSyncConsistentMode:go});const xo=async e=>{const t=be();let n={};if(e){const{token:t,limit:r}=e;n={limit:r,token:t}}t.log("user/queryBlockedUsers");const{data:r}=await t.http.get("/api/v4/me/user-blocks",{params:n}),{paging:o}=r,a=qt(r,["paging"]),{users:s}=a,i=t.cache&&Date.now();if(t.cache){Bt(a,{cachedAt:i});_e(["blockedUsers","query",n],{users:s.map(de("user")),paging:o})}const{next:c,previous:l,total:d}=o,u=Z(c);return{data:s,prevPage:Z(l),nextPage:u,total:d,cachedAt:i}};xo.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryBlockedUsers.locally"),!o.cache)return;let a={};if(e){const{token:t,limit:n}=e;a={token:t,limit:n}}const s=["blockedUsers","query",a],{data:i,cachedAt:c}=null!==(t=Ie(s))&&void 0!==t?t:{},l=null!==(n=null==i?void 0:i.users.map((e=>Ie(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],d=Z(null==i?void 0:i.paging.next),u=Z(null==i?void 0:i.paging.previous);return l.length>0&&l.length===(null===(r=null==i?void 0:i.users)||void 0===r?void 0:r.length)?{data:l,nextPage:d,prevPage:u,total:null==i?void 0:i.paging.total,cachedAt:c}:void 0};const jo=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getBlockedUsers(tmpid: ${a}) > listen`);const{limit:s}=e,i=null!=s?s:U,{policy:c=x}=null!=n?n:{},l=[],d=["blockedUsers","collection",{}],u=(e=!1)=>{var n,r;const o=null===(n=Ie(d))||void 0===n?void 0:n.data,a=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null==o?void 0:o.params.page))return;const s=ae(xo,{limit:i,token:Y(e||null==o?void 0:o.params.page,"afterbeforeraw")});ie(s,(({data:e,loading:n,error:r,nextPage:o,total:s})=>{const i={loading:n,error:r,params:{page:o,total:s},data:a};e&&(i.data=[...new Set([...a,...e.map(de("user"))])]),_e(d,i),(e=>{var n,r;const o=null!==(n=e.data.map((e=>Ie(["user","get",e]))).filter(Boolean).map((({data:e})=>pn.user(e))))&&void 0!==n?n:[];t({onNextPage:u,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})})(i)}),se(c,L))};return l.push((()=>{})),u(!0),()=>{r(`getCategories(tmpid: ${a}) > dispose`),l.forEach((e=>e())),Ee(d)}},Do=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{var r,o;if(n.cache){Bt(e);[...null!==(r=Ce(["followers","query"]))&&void 0!==r?r:[],...null!==(o=Ce(["followings","query"]))&&void 0!==o?o:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>ke(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},No=e=>Do("follow.created",e),Bo=e=>Do("follow.unfollowed",e),Fo=e=>Do("follow.followerDeleted",e),qo=e=>Do("follow.requested",e),Lo=e=>Do("follow.requestCanceled",e),$o=e=>Do("follow.accepted",e),Ko=e=>Do("follow.requestDeclined",e),zo=async e=>{var t,n;const r=be();r.log("follow/getFollowInfo",e);const{data:o}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),a=r.cache&&Date.now(),s="follows"in o?Object.assign(Object.assign({},o.followCounts[0]),{status:null===(n=null===(t=o.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):o.followCounts[0];return r.cache&&_e(["followInfo","get",e],s,{cachedAt:a}),{data:s,cachedAt:a}};zo.locally=e=>{const t=be();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Ie(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vo=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([zo(t.from),zo(t.to)]);e(n),e(r)},n=[Do("follow.created",t),Do("follow.requested",t),Do("follow.accepted",t),Do("follow.unfollowed",t),Do("follow.requestCanceled",t),Do("follow.requestDeclined",t),Do("follow.followerDeleted",t)];return()=>{n.forEach((e=>e()))}},Qo=async(e,t)=>{const n=be();n.log(`follow/queryF${e.substring(1)}`,t);const{userId:r,page:o}=t,a=qt(t,["userId","page"]),{data:s}=await n.http.get(n.userId===r?`/api/v4/me/${e}`:`/api/v4/users/${r}/${e}`,{params:Object.assign(Object.assign({},a),{token:Y(o,"afterbeforeraw")})}),{paging:i}=s,c=qt(s,["paging"]),{follows:l}=c,d=n.cache&&Date.now();if(n.cache){Bt(c,{cachedAt:d});const t=["follow","query",Object.assign(Object.assign({},a),{userId:r,options:Object.assign({},o),type:e})];_e(t,{follows:l.map(de("follow")),paging:i})}const u=Z(i.next);return{data:l,cachedAt:d,prevPage:Z(i.previous),nextPage:u}};Qo.locally=(e,t)=>{var n,r;const o=be();if(o.log(`follow/queryF${e.substring(1)}.locally`,t),!o.cache)return;const{page:a}=t,s=qt(t,["page"]),i=["follow","query",Object.assign(Object.assign({},s),{options:Object.assign({},a),type:e})],{data:c,cachedAt:l}=null!==(n=Ie(i))&&void 0!==n?n:{};if(!(null==c?void 0:c.follows.length))return;const d=c.follows.map((e=>Ie(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),u=Z(null==c?void 0:c.paging.previous),h=Z(null==c?void 0:c.paging.next);return d.length===(null===(r=null==c?void 0:c.follows)||void 0===r?void 0:r.length)?{data:d,cachedAt:l,prevPage:u,nextPage:h}:void 0};const Ho=async e=>Qo("followers",e);Ho.locally=e=>Qo.locally("followers",e);const Wo=async e=>Qo("following",e);Wo.locally=e=>Qo.locally("following",e);var Go=Object.freeze({__proto__:null,blockUser:async e=>{const t=be();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:a}=n,s={follows:o};return t.cache&&(Bt(s,{cachedAt:r}),ke(["followInfo","get",e],a[0],{cachedAt:r})),Xe("follow.unfollowed",s),n},unBlockUser:async e=>{const t=be();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:a}=n,s={follows:o};return t.cache&&(Bt(s,{cachedAt:r}),ke(["followInfo","get",e],a[0],{cachedAt:r})),Xe("follow.created",s),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),jo(e,t,n)),follow:async e=>{const t=be();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();return t.cache&&Bt(n,{cachedAt:r}),Xe("accepted"===n.follows[0].status?"follow.created":"follow.requested",n),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=be();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Bt(n),Xe("follow.unfollowed",n),!0},acceptFollower:async e=>{const t=be();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Bt(n),Xe("follow.accepted",n),!0},acceptMyFollower:async e=>{const t=be();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Bt(n),Xe("follow.accepted",n),!0},declineFollower:async e=>{const t=be();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Bt(n),Xe("follow.requestDeclined",n),!0},declineMyFollower:async e=>{const t=be();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Bt(n),Xe("follow.requestDeclined",n),!0},onUserFollowed:No,onUserUnfollowed:Bo,onFollowerDeleted:Fo,onFollowerRequested:qo,onFollowRequestCanceled:Lo,onFollowRequestAccepted:$o,onFollowRequestDeclined:Ko,onFollowInfoUpdated:Vo,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeFollowInfo(tmpid: ${o}) > listen`);const a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=[];return s.push(Vo((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&a(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),ie(ae(zo,e),(e=>(e.data||e.error)&&a(e,"onFetch")),se(n)),()=>{r(`observeFollowInfo(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const o=[],a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(o=t[n])||void 0===o||o.call(t,e)};return o.push(qo((e=>a(e,"onRequested"))),$o((e=>a(e,"onAccepted"))),Ko((e=>a(e,"onDeclined"))),Lo((e=>a(e,"onCanceled"))),No((e=>a(e,"onFollowed"))),Bo((e=>a(e,"onUnfollowed"))),Fo((e=>a(e,"onDeleted")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const o=[],a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(o=t[n])||void 0===o||o.call(t,e)};return o.push(qo((e=>a(e,"onRequested"))),$o((e=>a(e,"onAccepted"))),Ko((e=>a(e,"onDeclined"))),Lo((e=>a(e,"onCanceled"))),No((e=>a(e,"onFollowed"))),Bo((e=>a(e,"onUnfollowed"))),Fo((e=>a(e,"onDeleted")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`getFollowers(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["follow","collection",{userId:e.userId,type:"follower"}],h=n=>{var r,o;let a=null!==(r=n.data.map((e=>Ie(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(a=Ae(a,"status",e.status)),t({onNextPage:f,data:a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},p=t=>n=>{var r;const o=null===(r=Ie(u))||void 0===r?void 0:r.data;e.userId===n.to&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==de("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([de("follow")(n),...o.data])]),_e(u,o),h(o))},f=(e=!1)=>{var t,n,r,o;const a=null===(t=Ie(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null===(r=null==a?void 0:a.params)||void 0===r?void 0:r.page))return;const d=ae(Ho,Object.assign(Object.assign({},i),{page:null!==(o=e||null==a?void 0:a.params.page)&&void 0!==o?o:{limit:c}}));ie(d,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(de("follow"))])]),_e(u,o),h(o)}),se(l))};return d.push(qo(p("onRequested")),$o(p("onAccepted")),Ko(p("onDeclined")),Lo(p("onCanceled")),No(p("onFollowed")),Bo(p("onUnfollowed")),Fo(p("onDeleted"))),f(!0),()=>{r(`getFollowers(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`getFollowings(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["follow","collection",{userId:e.userId,type:"following"}],h=n=>{var r,o;let a=null!==(r=n.data.map((e=>Ie(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(a=Ae(a,"status",e.status)),t({onNextPage:f,data:a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},p=t=>n=>{var r;const o=null===(r=Ie(u))||void 0===r?void 0:r.data;e.userId===n.from&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==de("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([de("follow")(n),...o.data])]),_e(u,o),h(o))},f=(e=!1)=>{var t,n,r,o;const a=null===(t=Ie(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null===(r=null==a?void 0:a.params)||void 0===r?void 0:r.page))return;const d=ae(Wo,Object.assign(Object.assign({},i),{page:null!==(o=e||null==a?void 0:a.params.page)&&void 0!==o?o:{limit:c}}));ie(d,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(de("follow"))])]),_e(u,o),h(o)}),se(l))};return d.push(qo(p("onRequested")),$o(p("onAccepted")),Ko(p("onDeclined")),Lo(p("onCanceled")),No(p("onFollowed")),Bo(p("onUnfollowed")),Fo(p("onDeleted"))),f(!0),()=>{r(`getFollowings(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}},getFollowInfo:(e,t)=>Ro(e,t,"userId",zo,[Vo],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=ze();return Ro(t,e,"userId",zo,[Vo],{forceDispatch:!0})}});const Jo=async e=>{const t=be();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}}),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),Xe("user.fetched",r),{data:r.users.map((e=>pn.user(e))),cachedAt:o}};Jo.locally=e=>{var t;const n=be();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Ie(["user","get",e]))).filter(Boolean),o=r.map((({data:e})=>pn.user(e))),a=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:o,cachedAt:a.cachedAt}};const Yo=e=>kr("user.updated",e),Xo=e=>kr("user.flagged",e),Zo=e=>kr("user.unflagged",e),ea=e=>kr("user.flagCleared",e),ta=e=>kr("user.fetched",e),na=async e=>{const t=be();let n;t.log("user/getUser",e),tr("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw Q(null==t?void 0:t.code)&&Ft("user",e),t}const r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{users:o}=n;return Xe("user.fetched",n),{data:o.find((t=>t.userId===e)),cachedAt:r}};na.locally=e=>{const t=be();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ie(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ra=async(e={})=>{const t=be();t.log("user/queryUsers",e);const{page:n,limit:r=10,displayName:o,filter:a="all",sortBy:s="displayName"}=e,i=qt(e,["page","limit","displayName","filter","sortBy"]),{data:c}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},i),{keyword:o,filter:a,sortBy:s,options:n?{token:n}:{limit:r}})}),{paging:l}=c,d=qt(c,["paging"]),{users:u}=d,h=t.cache&&Date.now();if(t.cache){Bt(d,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:r,token:n}})];_e(t,{users:u.map(de("user")),paging:l})}return Xe("user.fetched",c),{data:u,cachedAt:h,paging:l}};ra.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryUsers.locally",e),!o.cache)return;const{limit:a=10,page:s}=null!=e?e:{},i=["user","query",Object.assign(Object.assign({},e),{options:{limit:a,token:s}})],{data:c,cachedAt:l}=null!==(t=Ie(i))&&void 0!==t?t:{},d=null!==(n=null==c?void 0:c.users.map((e=>Ie(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];return d.length>0&&d.length===(null===(r=null==c?void 0:c.users)||void 0===r?void 0:r.length)?{data:d,cachedAt:l,paging:null==c?void 0:c.paging}:void 0};const oa=(e,t)=>{let n=Te(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":n=n.sort(Ne);break;case"lastCreated":n=n.sort(Fe);break;default:n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(je)}return n},aa=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`liveUsers(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["user","collection",Pt()],h=(n,r=!1)=>{var o,a;const s=null!==(o=n.data.map((e=>Ie(["user","get",e]))).filter(Boolean).map((({data:e})=>pn.user(e))))&&void 0!==o?o:[];t({onNextPage:f,data:r?oa(s,e):s,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})},p=e=>e=>{var t;const n=null===(t=Ie(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],_e(u,n),h(n,!0))},f=(e=!1)=>{var t,n;const r=null===(t=Ie(u))||void 0===t?void 0:t.data,o=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null==r?void 0:r.params.page))return;const a=e?{limit:c}:{page:null==r?void 0:r.params.page},s=ae(ra,Object.assign(Object.assign({},i),a));ie(s,(({data:t,error:n,loading:r,paging:a})=>{const s={loading:r,error:n,params:{page:null==a?void 0:a.next},data:o};t&&(s.data=e?t.map(de("user")):[...new Set([...o,...t.map(de("user"))])]),_e(u,s),h(s)}),se(l))};return d.push(Yo(p()),Er(p()),Xo(p()),Zo(p()),ea(p())),f(!0),()=>{r(`liveUsers(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}},sa=async e=>{const t=be();let n;t.log("user/getUser",e),tr("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw Q(null==t?void 0:t.code)&&Ft("user",e),t}const r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{users:o}=n;return Xe("user.fetched",n),{data:pn.user(o.find((t=>t.userId===e))),cachedAt:r}};sa.locally=e=>{const t=be();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ie(["user","get",e]);return n?{data:pn.user(n.data),cachedAt:n.cachedAt}:void 0};const ia=async({viewId:e,viewedType:t,limit:n,token:r})=>{const o=be(),a={};r?a.token=r:a.limit=n;const s=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await o.http.get(s,{params:a});return Bt(i.data),i.data};var ca=Object.freeze({__proto__:null,Relationship:Go,getUserByIds:Jo,updateUser:async(e,t)=>{const n=be();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})),o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o});const{users:a}=r;return Xe("user.updated",r),{data:a.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=be();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Bt(n),Xe("user.flagged",n),!!n},unflagUser:async e=>{const t=be();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Bt(n),Xe("user.unflagged",n),!!n},isUserFlaggedByMe:async e=>{const t=be();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:Yo,onUserDeleted:Er,onUserFlagged:Xo,onUserUnflagged:Zo,onUserFlagCleared:ea,getUser:(e,t)=>Ro(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?pn.user(e.data):e.data}))),"userId",na,[ta,Yo,Er,Xo,Zo,ea]),getUsers:aa,observeUser:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,a,s;if((null===(o=n.data)||void 0===o?void 0:o.userId)!==e)return;const i=Object.assign(Object.assign({},n),{data:pn.user(n.data)});if(t instanceof Function)return t(i);"onFetch"!==r&&(null===(a=t.onEvent)||void 0===a||a.call(t,r,i)),null===(s=t[r])||void 0===s||s.call(t,i)},a=[];return a.push(Yo((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Er((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),Xo((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Zo((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),ea((e=>o({data:e,loading:!1,origin:"event"},"onFlagCleared")))),ie(ae(sa,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),a.forEach((e=>e()))}},getBlockedUsers:jo,searchUserByDisplayName:(e,t,n)=>aa(Object.assign(Object.assign({},e),{filter:"all"}),t,n),getViewedUsers:(e,t)=>{const{log:n,cache:r}=be(),o=["postViewedUsers","collection",{postId:e.postId}];r||console.log(j);const a=Date.now();n(`getViewedUsers(tmpid: ${a}) > listen`);const{limit:s,postId:i}=e,c=(e=!1)=>{var n,r,a;const l=null===(n=Ie(o))||void 0===n?void 0:n.data,d=null!==(r=null==l?void 0:l.data)&&void 0!==r?r:[];if(!e&&d.length>0&&!(null==l?void 0:l.params.page))return;const u=ae(ia,{viewId:i,viewedType:"post",limit:s||10,token:e||null===(a=null==l?void 0:l.params.page)||void 0===a?void 0:a.next});ie(u,(e=>{var n,r,a,s,i;let l=null!==(a=null===(r=null===(n=Ie(o))||void 0===n?void 0:n.data)||void 0===r?void 0:r.data)&&void 0!==a?a:[];(null===(s=e.data)||void 0===s?void 0:s.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(i=e.data)||void 0===i?void 0:i.paging},data:l||[]};_e(o,d),(e=>{var n,r;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>Ie(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:c,data:o,hasNextPage:!!(null===(r=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(d)}),se(x,L))};return c(!0),()=>{n(`getViewedUsers(tmpid: ${a}) > dispose`),Ee(o)}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:o}=be(),a=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];o||console.log(j);const s=Date.now();r(`getReachUsers(tmpid: ${s}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,o,s;const d=null===(r=Ie(a))||void 0===r?void 0:r.data,u=null!==(o=null==d?void 0:d.data)&&void 0!==o?o:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ae(ia,{viewId:c,viewedType:l,limit:i||10,token:e||null===(s=null==d?void 0:d.params.page)||void 0===s?void 0:s.next});ie(h,(e=>{var r,o,s,i,c;let l=null!==(s=null===(o=null===(r=Ie(a))||void 0===r?void 0:r.data)||void 0===o?void 0:o.data)&&void 0!==s?s:[];(null===(i=e.data)||void 0===i?void 0:i.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:l||[]};_e(a,d),(e=>{var r,o;let a=[];(null==e?void 0:e.data)&&(a=e.data.map((e=>Ie(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:a,hasNextPage:!!(null===(o=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===o?void 0:o.next),loading:e.loading||!1})})(d)}),se(x,L))},n(!0),()=>{r(`getReachUsers(tmpid: ${s}) > dispose`),Ee(a)}}});const la=async e=>{const t=be();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Bt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};la.locally=e=>{const t=be();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Ie(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const da=async(e,t,n)=>{const r=be();r.log("file/uploadVideo",e);const o=e.getAll("files");if(!o.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",o[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Bt({files:s},{cachedAt:i}),{data:s,cachedAt:i}},ua=async(e,t)=>{const n=be();n.log("file/uploadImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Bt({files:a},{cachedAt:s}),{data:a,cachedAt:s}};var ha=Object.freeze({__proto__:null,getFile:la,uploadFile:async(e,t)=>{const n=be();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Bt({files:a},{cachedAt:s}),{data:a,cachedAt:s}},deleteFile:async e=>{const t=be();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Ee(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:da,uploadImage:ua,createImage:async(e,t)=>{const n=be();n.log("file/createImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Bt({files:a},{cachedAt:s}),{data:a,cachedAt:s}},createFile:async(e,t)=>{const n=be();n.log("file/createFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Bt({files:a},{cachedAt:s}),{data:a,cachedAt:s}},createVideo:async(e,t,n)=>{const r=be();r.log("file/createVideo",e);const o=e.getAll("files");if(!o.length)throw new Error("The formData object must have a `files` key.");e.append("preferredFilename",o[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Bt({files:s},{cachedAt:i}),{data:s,cachedAt:i}},observeFile:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return ie(ae(la,e),(n=>n.data&&((n,r)=>{var o,a,s;if((null===(o=n.data)||void 0===o?void 0:o.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(a=t.onEvent)||void 0===a||a.call(t,r,n)),null===(s=t[r])||void 0===s||s.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const pa=async e=>{const t=be();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r,limit:o=10,queryToken:a,displayName:s,sortBy:i}=n,c=qt(n,["page","limit","queryToken","displayName","sortBy"]),l=a?{token:a}:o?{limit:o}:r?{token:Y(r,"skiplimit")}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},c),{keyword:s,sortBy:i,options:l})}),{paging:u}=d,h=qt(d,["paging"]),{roles:p}=h,f=t.cache&&Date.now();t.cache&&Bt(h,{cachedAt:f});const g=X(u.next);return{data:p,cachedAt:f,prevPage:X(u.previous),nextPage:g,paging:u}};pa.locally=e=>{be().log("role/queryRoles.locally",e)};const fa=async e=>{const t=be();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Bt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};fa.locally=e=>{const t=be();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Ie(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ga=(e,t)=>{"message"===e?Xe("local.message.updated",{messages:[t]}):"post"===e?Xe("post.updated",{posts:[t]}):"comment"===e?Xe("comment.updated",{comments:[t]}):"story"===e&&Xe("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},ma=async(e,t=!1)=>{const n=be();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),tr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Kn(t)}catch(t){throw Q(null==t?void 0:t.code)&&Ft("message",e),t}const o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o});const{messages:a}=r;return Xe("local.message.fetched",{messages:a}),{data:a.find((t=>t.messageId===e)),cachedAt:o}};ma.locally=e=>{const t=be();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ie(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ya=async e=>{const t=be();let n;t.log("post/getPost",e),tr("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Q(null==t?void 0:t.code)&&Ft("post",e),t}const r=$t(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{posts:a}=r,s=a.find((t=>t.postId===e));return{data:pn.post(s),cachedAt:o}};ya.locally=e=>{const t=be();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ie(["post","get",e]);return n?{data:pn.post(n.data),cachedAt:n.cachedAt}:void 0};const va=async e=>{const t=be();let n;t.log("comment/getComment",e),tr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Q(null==t?void 0:t.code)&&Ft("comment",e),t}const r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{comments:o}=n;return{data:pn.comment(o.find((t=>t.commentId===e))),cachedAt:r}};function ba(e,t){return e.map((e=>{const n=t.some((t=>function(e,t){const{userId:n}=ze();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}))}va.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ie(["comment","get",e]);return n?{data:pn.comment(n.data),cachedAt:n.cachedAt}:void 0};const wa=(e,t)=>{var n,r;let o,a;if("post"===t)a="post",o=e.posts[0].postId;else if("comment"===t)a="comment",o=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");a="story",o=e.stories[0].referenceId}return(null===(r=null===(n=Ie([a,"get",o]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Ca=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Ia=(e,t,n,r=[])=>{const o=e.split(".")[1];let a=r;if(be().userId===t)if(["addReaction","reactionAdded"].includes(o))a.includes(n)||a.push(n);else{if(!["removeReaction","reactionRemoved"].includes(o))throw new Error(`Unknown event type: ${o}`);a=a.filter((e=>e!==n))}return a},_a=(e,t)=>{const n=e.split(".")[0],r=wa(t,n),o=Ia(e,t.reactor.userId,t.reactor.reactionName,r);return Ca(t,`${n}s`,o)},Sa=(e,t)=>{var n,r;const o=e.split(".")[0];let a=wa(t,o);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(a=Ia(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,a));const s=Ca(t,"stories",a);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return s;const i=ba(t.communities,t.communityUsers);return Object.assign(Object.assign({},s),{communities:i})},ka=async(e,t,n)=>{const r=be();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),r.cache){const n=Ie([e,"get",t]);(null==n?void 0:n.data)&&_e([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};ka.optimistically=(e,t,n)=>{var r,o,a,s,i;const c=be();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ie([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 d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(o=l.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(a=l.data.reactions[n])&&void 0!==a?a:0)+1})});return ke([e,"get",t],d,{cachedAt:-5}),ga(e,d),null!==(i=null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n))&&void 0!==i&&i};const Ea=async(e,t,n)=>{const r=be();if(r.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),r.cache){const n=Ie([e,"get",t]);(null==n?void 0:n.data)&&_e([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};Ea.optimistically=(e,t,n)=>{var r,o,a,s,i;const c=be();if(c.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ie([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 d=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(o=l.data.myReactions)&&void 0!==o?o:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(a=l.data.reactions[n])&&void 0!==a?a:0)-1)})});return ke([e,"get",t],d,{cachedAt:-5}),ga(e,d),null!==(i=!(null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n)))&&void 0!==i&&i};const Aa=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{var o;if(n.cache){const{communities:a}=r,s=qt(r,["communities"]),i=$t(s,"communityUsers");if(Bt(i),(null==a?void 0:a[0])&&!["post.updated"].includes(e)&&Xe("community.updated",{communities:a,categories:[],communityUsers:i.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:o}=r.posts[0];try{tr("post",e)}catch(e){return}return o!==n.userId&&Ft("post",e),t(r.posts[0])}const c=Ie(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(o=Ce(["post","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===c.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})=>ke(e,t,{cachedAt:-1})))}t(c.data)}else t(r.posts[0])}))},Ta=e=>Aa("post.created",e),Ma=e=>Aa("post.updated",e),Oa=e=>Aa("post.deleted",e),Pa=e=>Aa("post.approved",e),Ra=e=>Aa("post.declined",e),Ua=e=>Aa("post.flagged",e),xa=e=>Aa("post.unflagged",e),ja=e=>{const t=be();return Ye(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=qt(_a("post.addReaction",n),["reactor"]);Bt(t);const r=Ie(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Da=e=>{const t=be();return Ye(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=qt(_a("post.removeReaction",n),["reactor"]);Bt(t);const r=Ie(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Na=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{var o;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=wa(e,"comment");return Ca(e,"comments",t)})(r):r;Bt(n);const{comments:a}=n;if(a.length>0){const n=Ie(["comment","get",a[0].commentId]);if(["comment.created"].includes(e)){if(a[0].parentId){const e=Ie(["comment","get",a[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(a[0].commentId)||_e(["comment","get",a[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,a[0].commentId])]})))}const e=null===(o=Ce(["comment","query"]))||void 0===o?void 0:o.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})=>ke(e,t,{cachedAt:-1})))}t(pn.comment(n.data))}}else t(pn.comment(r.comments[0]))}))},Ba=e=>Na("comment.created",e),Fa=e=>Na("comment.updated",e),qa=e=>Na("comment.deleted",e),La=e=>Na("comment.flagged",e),$a=e=>Na("comment.unflagged",e),Ka=e=>{const t=be();return Ye(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=qt(_a("comment.addReaction",n),["reactor"]);Bt(t);const r=Ie(["comment","get",n.comments[0].commentId]);e(pn.comment(r.data))}else e(pn.comment(n.comments[0]))}))},za=e=>{const t=be();return Ye(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=qt(_a("comment.removeReaction",n),["reactor"]);Bt(t);const r=Ie(["comment","get",n.comments[0].commentId]);e(pn.comment(r.data))}else e(pn.comment(n.comments[0]))}))},Va=(e,t,n)=>{const r=be(),o=(r,o,a)=>{r===e&&o===t&&n(a)};if("message"===e){return Ye(r,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Kn(e);t.reactions[0]&&(Bt(t),o("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=qt(e,["reactor"]);Bt(n),Bt({reactions:[t]}),o("post",e.posts[0].postId,t)}))}if("story"===e){return Ye(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=qt(e,["reactions"]);Bt(n),Bt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&o("story",e.stories[0].storyId,e.reactions[0])}))}return Ye(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=qt(e,["reactor"]);Bt(n),Bt({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Qa=(e,t,n)=>{const r=be(),o=(r,o,a)=>{r===e&&o===t&&n(a)};if("message"===e){return Ye(r,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Kn(e);t.reactions[0]&&(Bt(t),o("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=qt(e,["reactor"]);Bt(n),Bt({reactions:[t]}),o("post",e.posts[0].postId,t)}))}if("story"===e){return Ye(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=qt(e,["reactions"]);Bt(n),Bt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&o("story",e.stories[0].storyId,e.reactions[0])}))}return Ye(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=qt(e,["reactor"]);Bt(n),Bt({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Ha=async e=>{be().log("reaction/queryReactor",e);const t=await(async e=>{const t=be();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,o=qt(n,["page"]),{data:a}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},o),{referenceVersion:5,options:{token:Y(r,"afterbeforeraw")}})}),{paging:s}=a,i=qt(a,["paging"]),{reactions:c}=i;Bt(Object.assign(Object.assign({},i),{reactions:c})),Bt(Object.assign(Object.assign({},i),{reactors:c[0].reactors}));const l=Z(s.next);return{data:c,prevPage:Z(s.previous),nextPage:l}})(e),{data:n}=t,r=qt(t,["data"]);return Object.assign(Object.assign({},r),{data:n[0].reactors})};var Wa=Object.freeze({__proto__:null,addReaction:ka,removeReaction:Ea,onReactionAdded:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await Kn(e),o=Ie(["message","get",n.messages[0].messageId]),a=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Bt(n),a&&r(n.messages[0])};return Ye(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?ja(r):Ka(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await Kn(e),o=Ie(["message","get",n.messages[0].messageId]),a=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Bt(n),a&&r(n.messages[0])};return Ye(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Da(r):za(r)},onReactorAdded:Va,onReactorRemoved:Qa,getReactions:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`liveReactions(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],h=e=>{var n,r;const o=null!==(n=e.data.map((e=>Ie(["reactor","get",e]))).filter(Boolean).map((({data:e})=>pn.reactor(e))))&&void 0!==n?n:[];t({onNextPage:f,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},p=e=>t=>{var n;const r=null===(n=Ie(u))||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))),_e(u,r),h(r))},f=(e=!1)=>{var t,n,r,o;const a=null===(t=Ie(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null===(r=null==a?void 0:a.params)||void 0===r?void 0:r.page))return;const d=ae(Ha,Object.assign(Object.assign({},i),{page:null!==(o=e||null==a?void 0:a.params.page)&&void 0!==o?o:{limit:c}}));ie(d,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(de("reactor"))])]),_e(u,o),h(o)}),se(l))};return d.push(Va(i.referenceType,i.referenceId,p("onAdded")),Qa(i.referenceType,i.referenceId,p("onRemoved"))),f(!0),()=>{r(`liveReactions(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}}),Ga={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const Ja=async e=>{const t=be();let n;t.log("channel/getChannel",e),tr("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await On(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Un(r)}catch(t){throw Q(null==t?void 0:t.code)&&Ft("channel",e),t}const r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{channels:o}=n;return{data:o.find((t=>t.channelId===e)),cachedAt:r}};Ja.locally=e=>{var t;const n=be();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Ce(["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 Ya=(e,t,n)=>r=>e((e=>{var o;if(!e)return e;const a=[n,"get",`${e[t]}`],s=null===(o=Ie(a))||void 0===o?void 0:o.data;return s?r(s):void 0})),Xa=e=>{const t=be(),n=[Ye(t,"onMessageUpdated","message.updated",(async t=>{const n=await Kn(t);Bt(n),e(n.messages[0])})),Ye(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Za=e=>{const t=be(),n=[Ye(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Kn(t);Bt(n),e(n.messages[0])})),Ye(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},es=e=>{const t=be(),n=[Ye(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Wn(t);Bt(n),e(n.messageFeeds[0])})),Ye(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function ts(e,t){_e(["channel","get",e.channelId],Object.assign(bn(e),t))}const ns=e=>{const t=be();return Ye(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},rs=async(e,t=!1)=>{const n=be(),r=await nr(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:he(r.data.updatedAt)});return t?setTimeout((()=>{Ft("subChannel",e)}),0):ke(["subChannel","get",e],o),Xe("local.message-feed.deleted",{messageFeeds:[o]}),o},os=e=>Ye(be(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),as=async e=>{const t=be();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await Kn(n),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{messages:a}=r;return Xe("local.message.fetched",{messages:a}),{data:a.map((e=>pn.message(e))),cachedAt:o}};as.locally=e=>{var t;const n=be();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>Ie(["message","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),a=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:o,cachedAt:a.cachedAt}};const ss=()=>`LOCAL_${Pt()}`;let is;const cs=async e=>{const t=be();t.log("message/createMessage",e);const n=e.referenceId||is||ss();is=void 0;const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},zn(e)),{referenceId:n})),o=await Kn(r),{messages:a}=o,s=t.cache&&Date.now();return t.cache&&(Ee(["message","get",n]),Bt(o,{cachedAt:s})),Xe("local.message.created",{messages:a}),{data:pn.message(a[0]),cachedAt:s}};cs.optimistically=e=>{var t,n,{referenceId:r}=e,o=qt(e,["referenceId"]);const a=be();if(!a.cache)return;is=r||ss();const s=Object.assign({messageId:is,uniqueId:is},o);a.log("message/createMessage.optimistically",s);const i=Ie(["subChannel","get",o.subChannelId]);if(i&&(ke(["subChannel","get",o.subChannelId],Object.assign(Object.assign({},i.data),{messageCount:i.data.messageCount+1})),i.data.channelId===i.data.subChannelId)){const e=Ie(["channel","get",i.data.channelId]);(null==e?void 0:e.data)&&ke(["channel","get",i.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const c=(new Date).toISOString(),l=Object.assign({creatorId:a.userId,creatorPrivateId:ze()._id,channelSegment:(null!==(n=null==i?void 0:i.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:c,updatedAt:c},s);return _e(["message","get",l.messageId],l,{cachedAt:-5}),Xe("local.message.created",{messages:[l]}),{cachedAt:-5,data:pn.message(l)}};const ls=async(e,t)=>{const n=be();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)}`,zn(t)),o=await Kn(r),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{messages:s}=o;return Xe("local.message.updated",{messages:s}),{data:pn.message(s.find((t=>t.messageId===e))),cachedAt:a}};ls.optimistically=(e,t)=>{const n=be();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Ie(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return ke(["message","get",e],o,{cachedAt:-1}),Xe("local.message.updated",{messages:[o]}),{data:pn.message(o),cachedAt:-1}};const ds=async(e,t)=>{const n=be();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,zn(t)),o=await Kn(r),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{messages:s}=o;return Xe("local.message.updated",{messages:s}),{data:pn.message(s.find((t=>t.messageId===e))),cachedAt:a}};ds.optimistically=(e,t)=>{const n=be();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Ie(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return ke(["message","get",e],o,{cachedAt:-1}),Xe("local.message.updated",{messages:[o]}),{data:pn.message(o),cachedAt:-1}};const us=async e=>{const t=be();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await ma(e);return Xe("local.message.deleted",{messages:[n.data]}),pn.message(n.data)};us.optimistically=e=>{be().log("message/deleteMessage.optimistically",e);const t=Ie(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ke(["message","get",e],n,{cachedAt:-1}),Xe("local.message.deleted",{messages:[n]}),{data:pn.message(n),cachedAt:-1}};const hs=async e=>{const t=be();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await ma(e);return Xe("local.message.deleted",{messages:[n.data]}),pn.message(n.data)};hs.optimistically=e=>{be().log("message/softDeleteMessage.optimistically",e);const t=Ie(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ke(["message","get",e],n,{cachedAt:-1}),Xe("local.message.deleted",{messages:[n]}),{data:pn.message(n),cachedAt:-1}};const ps=async e=>{const t=be();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,o=qt(e,["page","messageId"]),{data:a}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},o),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=a,l=qt(a,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Bt(Object.assign(Object.assign({},l),{userFeedMarkers:Vt(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];_e(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await Jo(i));return{data:u,cachedAt:d,prevPage:X(s.previous),nextPage:X(s.next)}};ps.locally=e=>{var t;const n=be();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,o=qt(e,["page"]),a=["read-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=Ie(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==s?void 0:s.paging.previous),nextPage:X(null==s?void 0:s.paging.next)}};const fs=async e=>{const t=be();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,o=qt(e,["page","messageId"]),{data:a}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},o),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=a,l=qt(a,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Bt(Object.assign(Object.assign({},l),{userFeedMarkers:Vt(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];_e(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await Jo(i));return{data:u,cachedAt:d,prevPage:X(s.previous),nextPage:X(s.next)}};fs.locally=e=>{var t;const n=be();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,o=qt(e,["page"]),a=["delivered-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=Ie(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==s?void 0:s.paging.previous),nextPage:X(null==s?void 0:s.paging.next)}};const gs=e=>{const t=be();return Ye(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Kn(t);Bt(n),e(n.messages[0])}))},ms=e=>{const t=be();return Ye(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Kn(t);Bt(n),e(n.messages[0])}))},ys=e=>{const t=be();return Ye(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Kn(t);Bt(n),e(n.messages[0])}))},vs=e=>{const t=be();return Ye(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Kn(t,"message.reactionAdded");Bt(n),e(n.messages[0])}))},bs=e=>{const t=be();return Ye(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Kn(t,"message.reactionRemoved");Bt(n),e(n.messages[0])}))},ws=e=>{const t=be();return Ye(t,"message/onMessageFetched","local.message.fetched",(t=>{Bt(t),e(t.messages[0])}))};class Cs{constructor(e){const{http:t}=be();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,o;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let a;"prev"===e&&(a=this.previousToken),"next"===e&&(a=this.nextToken);const s=await this.getRequest(this.queryParams,a);return"first"===e&&(this.nextToken=null===(t=s.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=s.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=s.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(o=s.paging)||void 0===o?void 0:o.next),s}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Is extends Cs{async getRequest(e,t){const n=Vn(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 _s{constructor(e,t){this.query=e,this.cacheKey=t}}class Ss extends _s{constructor(e,t,n,r,o){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=o}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.messages.map(de("message")),query:this.query});else{const n=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(o=null==n?void 0:n.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...a,...e.messages.map(de("message"))])]:[...new Set([...e.messages.map(de("message")),...a])]}))}}reactor(e){return t=>{var n,r,o,a,s;if("onCreate"===e){const e=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;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.dataType&&this.query.dataType!==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.excludeTags&&(null===(o=this.query.excludeTags)||void 0===o?void 0:o.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===(a=this.query.includingTags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.tags&&!(null===(s=this.query.tags)||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([t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,t.messageId])]),_e(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ks{constructor(e){const{http:t}=be();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Es{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 ks?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 ks)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 ks)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(Mo).map(Oo);return!Po(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}class As extends Es{constructor(e,t){const n=w.default(e),r=["message","collection",n];super(new Is(e),n,r,t),this.query=e,this.queryStreamController=new Ss(this.query,this.cacheKey,this.notifyChange.bind(this),Kn,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Hr,action:"onCreate"},{fn:Za,action:"onDelete"},{fn:Xa,action:"onUpdate"},{fn:gs,action:"onFlagged"},{fn:ms,action:"onUnflagged"},{fn:ys,action:"onFlagCleared"},{fn:vs,action:"onReactionAdded"},{fn:bs,action:"onReactionRemoved"},{fn:Ya(Eo,"contentId","message"),action:"onUpdate"},{fn:Ya(Ao,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["message","get",e]))).filter(Boolean).map((({data:e})=>e)).map((e=>pn.message(e))))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>!this.query.tags||this.query.tags.find((t=>!!e.tags&&e.tags.includes(t))))),t=t.filter((e=>!this.query.excludeTags||(this.query.excludeTags||[]).find((t=>!e.tags||!e.tags.includes(t))))),this.query.includeDeleted||(t=Ae(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}}const Ts=async(e,t=!1)=>{const n=be();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),tr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Kn(t)}catch(t){throw Q(null==t?void 0:t.code)&&Ft("message",e),t}const o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o});const{messages:a}=r;return Xe("local.message.fetched",{messages:a}),{data:pn.message(a.find((t=>t.messageId===e))),cachedAt:o}};Ts.locally=e=>{const t=be();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ie(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var Ms=Object.freeze({__proto__:null,getMessageByIds:as,createMessage:cs,updateMessage:ls,editMessage:ds,deleteMessage:us,softDeleteMessage:hs,markAsDelivered:async(e,t)=>{const n=be();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:o,userEntityMarkers:a,userFeedMarkers:s}=r,i=qt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Bt(Object.assign({userMarkers:o,userEntityMarkers:zt(a),userFeedMarkers:Vt(s)},i),{cachedAt:c}),!0},getReadUsers:ps,getDeliveredUsers:fs,flagMessage:async e=>{const t=be();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Kn(n);Bt(e)}return Xe("message.flagged",n),!!n},unflagMessage:async e=>{const t=be();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Kn(n);Bt(e)}return Xe("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=be();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Hr,onMessageCreatedLocal:Wr,onMessageUpdated:Xa,onMessageDeleted:Za,onMessageFlagged:gs,onMessageUnflagged:ms,onMessageFlagCleared:ys,onMessageReactionAdded:vs,onMessageReactionRemoved:bs,onMessageFetched:ws,getMessage:(e,t)=>Ro(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?pn.message(e.data):n}))}),"messageId",ma,[ws,Xa,Za,gs,ms,ys,vs,bs,Ya(Eo,"contentId","message"),Ya(Ao,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getMessages(tmpid: ${a}) > listen`);const s=new As(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{Ee(c)})),()=>{r(`getMessages(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeMessage(tmpid: ${o}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const a=(n,r)=>{var o,a,s;if((null===(o=n.data)||void 0===o?void 0:o.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(a=t.onEvent)||void 0===a||a.call(t,r,n)),null===(s=t[r])||void 0===s||s.call(t,n)}},s=[];return s.push(Xa((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onUpdate"))),Za((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onDelete"))),Ya(Eo,"contentId","message")((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onUpdate"))),Ya(Ao,"contentId","message")((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==n&&ie(ae(Ts,e),(e=>e.data&&a(e,"onFetch")),se(n)),()=>{r(`observeMessages(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const o=[],a=(n,r)=>{var o,a,s;if((null===(o=n.data)||void 0===o?void 0:o.subChannelId)===e){if(t instanceof Function)return t(n);null===(a=t.onEvent)||void 0===a||a.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(Hr((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onCreate"))),Wr((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onCreate"))),Xa((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onUpdate"))),Za((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onDelete"))),Ya(Eo,"contentId","message")((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onCreate"))),Ya(Ao,"contentId","message")((e=>a({data:pn.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:Ln,prepareMessagePayload:Kn,convertParams:zn,convertQueryParams:Vn});const Os=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class Ps extends Cs{async getRequest(e,t){var n;const{limit:r=U}=e,o=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=qt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(qt(e,["limit"])))&&void 0!==n?n:{},{channelId:a,includeDeleted:s}=o,i=qt(o,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${a}`,{params:Object.assign(Object.assign({},i),{isDeleted:Dn(s),options:c})});return l}}class Rs extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(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=Ie(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])]),_e(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Us extends Es{constructor(e,t){const n=w.default(e),r=["subChannel","collection",n];super(new Ps(e),n,r,t),this.query=e,this.queryStreamController=new Rs(this.query,this.cacheKey,this.notifyChange.bind(this),Wn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:os,action:"onCreate"},{fn:Gr,action:"onCreate"},{fn:Jr,action:"onDelete"},{fn:e=>es((async t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!r||!r.data.includes(t.subChannelId))return;const o=be();if("no-message-preview"!==await o.getMessagePreviewSetting(!1)){const e=mn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&_e(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Hr((async t=>{var n,r;const o=Ie(["subChannel","get",t.subChannelId]);if(!o)return;const a=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!a||!a.data.includes(t.subChannelId))return;await(async e=>{const t=be();"no-message-preview"!==await t.getMessagePreviewSetting(!1)&&Cn(e)})(t);const s=null===(r=Ie(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;s&&(wn(t.subChannelId,s,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},o.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>Wr((async t=>{var n,r;const o=Ie(["subChannel","get",t.subChannelId]);if(!o)return;const a=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!a||!a.data.includes(t.subChannelId))return;const s=be();if("no-message-preview"===await s.getMessagePreviewSetting(!1))return;Cn(t);const i=null===(r=Ie(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;i&&(wn(t.subChannelId,i,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},o.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>_o((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Ie(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Ya(Io,"feedId","subChannel"),action:"onUpdate"},{fn:Ya((e=>Xa((async t=>{var n;const r=be();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const o=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;o&&o.data.includes(t.subChannelId)&&(In(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ya((e=>Za((async t=>{var n;const r=be(),o=await r.getMessagePreviewSetting(!1);if("no-message-preview"===o)return;const a=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===o?await nr(t.subChannelId):await In(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ya(Os,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(yn))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ae(e,"isDeleted",!1)),t.sort($e),t}}const xs={},js=async e=>{const t=await(async e=>{const t=nr.locally(e);if(t)return t.data.channelId;const{data:n}=await nr(e);return n.channelId})(e),n=st({channelId:t,subChannelId:e});xs[e]=ht(n)};var Ds=Object.freeze({__proto__:null,getSubChannelByIds:dr,createSubChannel:async e=>{const t=be();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Wn(n.data),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),Xe("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:o}},updateSubChannel:async(e,t)=>{const n=be();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),o=await Wn(r.data),a=n.cache&&Date.now();return n.cache&&Bt(o,{cachedAt:a}),Xe("message-feed.updated",r.data),{data:o.messageFeeds[0],cachedAt:a}},deleteSubChannel:rs,hardDeleteSubChannel:async e=>{be().log("channel/hardDeleteSubChannel",e);return await rs(e,!0)},softDeleteSubChannel:async e=>{be().log("channel/softDeleteSubChannel",e);return await rs(e,!1)},onSubChannelCreated:Gr,onSubChannelUpdated:es,onSubChannelDeleted:Jr,getSubChannel:(e,t)=>{const n=be();let r;return Ro(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:yn(e.data)}),o=qt(n,["origin"]);return Po(r,o)?void 0:(r=o,t(n))}),"subChannelId",nr,[os,t=>es((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(_n(r),r.subChannelId===e&&t(r))})),Jr,Ya(Io,"feedId","subChannel"),t=>_o((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const o=null===(r=Ie(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&t(o)})),Ya((t=>Hr((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Cn(t),t.subChannelId!==e)return;const o=null===(r=Ie(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&wn(t.subChannelId,o,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),Ya((t=>Wr((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Cn(t),t.subChannelId!==e)return;const o=null===(r=Ie(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&wn(t.subChannelId,o,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),Ya((t=>Xa((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(In(r),t(r))}))),"subChannelId","subChannel"),Ya((t=>Za((async r=>{const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&r.subChannelId===e&&("message-preview-include-deleted"===o&&await In(r),"message-preview-not-include-deleted"===o&&await nr(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Ya(Os,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:o}=be(),a=Date.now();r(`getSubChannels(tmpid: ${a}) > listen`),o||console.log(j);const s=new Us(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{Ee(c)})),()=>{r(`getSubChannels(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:cr,startReading:async e=>{ar[e]=!0,0===or.length&&(or.length>0||or.push(er((()=>{sr()}))),lr(e));try{return await(async e=>{const t=be();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:a,userMarkers:s}=n,i=zt(r),c=Vt(o),l=t.cache&&Date.now();return t.cache&&Bt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:s},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:a}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:s}),!0})(e)}catch(t){return ar[e]=!1,!1}},stopReading:e=>(ar[e]=!1,or.forEach((e=>e())),or=[],(async e=>{const t=be();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:a,userMarkers:s}=n,i=zt(r),c=Vt(o),l=t.cache&&Date.now();return t.cache&&Bt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:s},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:a}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:s}),!0})(e)),startMessageReceiptSync:async e=>(await js(e),!0),stopMessageReceiptSync:e=>(xs[e]&&xs[e](),!0)});const Ns=e=>{const t=be();return Ye(t,"channelMarker/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Bs extends Cs{async getRequest(e,t){const{limit:n=U,displayName:r,membership:o}=e,a=qt(e,["limit","displayName","membership"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},a),{keyword:r,filter:o,options:s})});return i}}class Fs extends ks{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class qs extends _s{constructor(e,t,n,r,o){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=o}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Fs)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolve"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(de("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ls=(e,t)=>{const n=be();if(n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()){Mr().resolve(e.channelId,"userMessageFeedMarker")}else t(e)},$s=e=>{const t=be();return Ye(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class Ks extends Es{constructor(e,t){const n=w.default(e),r=["channel","collection",n],o=Ks.getPaginationController(e);super(o,n,r,t),this.query=e,this.queryStreamController=new qs(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=be();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Un(e)}catch(e){console.error("Error while preparing unread count info",e)}return On(e)}),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let s=null!==(o=a.data.map((e=>Ie(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(fn).map(pn.channel))&&void 0!==o?o:[];this.paginationController instanceof Bs&&(s=this.applyFilter(s)),(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Bs?()=>this.loadPage({direction:"next"}):void 0,data:s,hasNextPage:this.paginationController instanceof Bs&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;switch(n=Ae(n,"isDeleted",this.query.isDeleted),n=Ae(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=Oe(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ne);break;case"lastCreated":n=n.sort(Fe);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(je);break;default:n=n.sort($e)}return n}shouldAbort(e){var t,n;const r=null===(t=Ie(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 be().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Fs(e):new Bs(e)}getSubscriptions(){const e=[{fn:Ya((e=>Hr((t=>{var n;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;if(r)ts(r,{lastActivity:t.createdAt}),e(t);else{Mr().resolve(t.channelId,"channel")}}))),"messageId","channel"),action:"onUpdate"},{fn:Ya((e=>Wr((t=>{var n;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(ts(r,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:_r,action:"onDelete"},{fn:Nr,action:"onUpdate"},{fn:qr,action:"onMute"},{fn:e=>Br((t=>{Ls(t,e)})),action:"onJoin"},{fn:e=>Fr(((t,n)=>{var r,o;const{userId:a}=be();if("member"===this.query.membership&&a===n.userId){const e=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;_e(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(o=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==o?o:[]}))}return e(t)})),action:"onLeft"},{fn:Lr,action:"onMemberAdded"},{fn:$r,action:"onMemberRemoved"},{fn:Ya(Co,"entityId","channel"),action:"onUpdate"},{fn:Ya(ns,"entityId","channel"),action:"onUpdate"},{fn:Ya((e=>Hr((async t=>{var n;if("no-message-preview"===await Ks.getMessagePreviewSetting())return;if(Cn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(ts(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya((e=>Wr((async t=>{var n;if("no-message-preview"===await Ks.getMessagePreviewSetting())return;if(Cn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(ts(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya((e=>Xa((async t=>{"no-message-preview"!==await Ks.getMessagePreviewSetting()&&(In(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya((e=>Za((async t=>{const n=await Ks.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await In(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Ja(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya((e=>Jr((async t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Qt(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Ja(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya((e=>es((async t=>{var n;if("no-message-preview"===await Ks.getMessagePreviewSetting())return;(null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data)&&(await _n(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya(Gr,"channelId","channel"),action:"onUpdate"},{fn:$s,action:"onResolve"},{fn:e=>(e=>{const t=be();return Ye(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=[...new Set(t.feedMarkers.map((e=>e.entityId)))].map((e=>{var t;return null===(t=Ie(["channel","get",e]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"onResolve"},{fn:Ya(Ns,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Cs?[...e,{fn:e=>Dr((t=>{Ls(t,e)})),action:"onCreate"}]:e}}class zs extends Cs{async getRequest(e,t){const{limit:n=U}=e,r=qt(e,["limit"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v4/channels/${encodeURIComponent(r.channelId)}/users`,{params:Object.assign(Object.assign({},r),{options:o})});return a}}class Vs extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const o=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==o)):r.data.includes(o)||(r.data=[o,...r.data]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Qs extends Es{constructor(e,t){const n=w.default(e),r=["channelUsers","collection",n];super(new zs(e),n,r,t),this.query=e,this.queryStreamController=new Vs(this.query,this.cacheKey,this.notifyChange.bind(this),On),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:Br,action:"onJoin"},{fn:Fr,action:"onLeft"},{fn:Lr,action:"onMemberAdded"},{fn:$r,action:"onMemberRemoved"},{fn:Sr,action:"onChannelMemberBanned"},{fn:Kr,action:"onChannelMemberUnbanned"},{fn:zr,action:"onChannelMemberRoleAdded"},{fn:Vr,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(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))}))),this.query.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),t=xe(t,this.query.search));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?Fe:Ne),t}}const Hs=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const s=new Qs(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{Ee(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}};var Ws=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();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=>Xe("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await On(r);n.cache&&Bt(o);const{channelUsers:a}=o;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=be();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=>Xe("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await On(r);n.cache&&Bt(o);const{channelUsers:a}=o;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership)))),t.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Ne),n},getMembers:Hs,searchMembers:(e,t,n)=>Hs(e,t)});var Gs=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=be();r.log("channel/addRole",e,t,n);const{data:o}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),a=await On(o);r.cache&&Bt(a),Xe("local.channel-moderator.role-added",a);const{channelUsers:s}=a;return!!s.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=be();r.log("channel/removeRole",e,t,n);const{data:o}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),a=await On(o);r.cache&&Bt(a),Xe("local.channel-moderator.role-removed",a);const{channelUsers:s}=a;return!!s.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=be();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),o=await On(r),{channelUsers:a}=o,s=n.cache&&Date.now();return n.cache&&Bt(o,{cachedAt:s}),{data:null==a?void 0:a.filter((e=>"banned"===e.membership)),cachedAt:s}},unbanMembers:async(e,t)=>{const n=be();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),o=await On(r),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{channelUsers:s}=o;return{data:null==s?void 0:s.filter((e=>"member"===e.membership)),cachedAt:a}},muteMembers:async(e,t,n=-1)=>{const r=be();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:a}=o;return a},unmuteMembers:async(e,t)=>{const n=be();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=r;return o}}),Js=Object.freeze({__proto__:null,Membership:Ws,Moderation:Gs,getChannelByIds:xn,createChannel:async e=>{const t=be();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,o=qt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},o),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await On(n.data),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{channels:a}=r;return{data:a[0],cachedAt:o}},updateChannel:async(e,t)=>{const n=be();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),o=await On(r),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{channels:s}=o;return{data:s.find((t=>t.channelId===e)),cachedAt:a}},deleteChannel:async e=>{const t=be();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await Ja(e)).data},joinChannel:async e=>{const t=be();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await On(n);t.cache&&Bt(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=be();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await On(n);t.cache&&Bt(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=be();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new pe("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:o}=r;return o},unmuteChannel:async e=>{const t=be();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},markAsRead:hn,onChannelCreated:Dr,onChannelUpdated:Nr,onChannelDeleted:_r,onChannelJoined:Br,onChannelLeft:Fr,onChannelMuted:qr,onChannelMemberAdded:Lr,onChannelMemberRemoved:$r,onChannelMemberBanned:Sr,onChannelMemberUnbanned:Kr,onChannelMemberRoleAdded:zr,onChannelMemberRoleRemoved:Vr,observeChannel:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,a,s;if((null===(o=n.data)||void 0===o?void 0:o.channelId)===e){if(t instanceof Function)return t(Object.assign(Object.assign({},n),{data:pn.channel(n.data)}));"onFetch"!==r&&(null===(a=t.onEvent)||void 0===a||a.call(t,r,Object.assign(Object.assign({},n),{data:pn.channel(n.data)}))),null===(s=t[r])||void 0===s||s.call(t,Object.assign(Object.assign({},n),{data:pn.channel(n.data)}))}},a=[];return a.push(Nr((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),_r((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),Br((e=>o({data:e,loading:!1,origin:"event"},"onJoin"))),Fr((e=>o({data:e,loading:!1,origin:"event"},"onLeft"))),qr((e=>o({data:e,loading:!1,origin:"event"},"onMute"))),Lr((e=>o({data:e,loading:!1,origin:"event"},"onMemberAdded"))),$r((e=>o({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),Ya(Co,"entityId","channel")((e=>o({data:e,loading:!1,origin:"event"},"onUpdate")))),ie(ae(Ja,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),a.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=be(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],o=(t,n)=>{var r,o;if(e instanceof Function)return e(pn.channel(t));null===(r=e.onEvent)||void 0===r||r.call(e,n,pn.channel(t)),null===(o=e[n])||void 0===o||o.call(e,pn.channel(t))};return r.push(Dr((e=>o(e,"onCreate"))),Nr((e=>o(e,"onUpdate"))),_r((e=>o(e,"onDelete"))),Br((e=>o(e,"onJoin"))),Fr((e=>o(e,"onLeft"))),qr((e=>o(e,"onMute"))),Lr((e=>o(e,"onMemberAdded"))),$r((e=>o(e,"onMemberRemoved"))),Ya(Co,"entityId","channel")((e=>o(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>{const n=be();let r;return Ro(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:pn.channel(fn(e.data))}),o=qt(n,["origin"]);return Po(r,o)?void 0:(r=o,t(n))}),"channelId",Ja,[Nr,_r,Br,Fr,Lr,$r,Sr,Kr,qr,Ya(Co,"entityId","channel"),Ya(ns,"entityId","channel"),Ya((t=>Hr((async r=>{await(async r=>{var o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Cn(r),r.channelId!==e)return;const a=null===(o=Ie(["channel","get",e]))||void 0===o?void 0:o.data;a&&(ts(a,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Ya((t=>Wr((async r=>{var o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Cn(r),r.channelId!==e)return;const a=null===(o=Ie(["channel","get",e]))||void 0===o?void 0:o.data;a&&(ts(a,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Ya((t=>Xa((async r=>{var o;const a=null===(o=Ie(["channel","get",e]))||void 0===o?void 0:o.data;if(!a||a.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await In(r),t(r))}))),"channelId","channel"),Ya((t=>Za((async r=>{var o;const a=null===(o=Ie(["channel","get",e]))||void 0===o?void 0:o.data;if(!a||a.messagePreviewId!==r.messageId)return;const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&("message-preview-not-include-deleted"===s?(Ee(["messagePreviewChannel","get",e]),await Ja(r.channelId)):await In(r),t(r))}))),"channelId","channel"),Ya((e=>Jr((async t=>{var r,o;const{channelId:a,subChannelId:s}=t,i=null===(r=Ie(["messagePreviewChannel","get",a]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==s)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Ja(a);(null===(o=Ie(["channel","get",a]))||void 0===o?void 0:o.data)&&e(t)}))),"channelId","channel"),Ya((t=>es((async r=>{var o,a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;_n(r);const s=null===(o=Ie(["messagePreviewChannel","get",e]))||void 0===o?void 0:o.data;if(!s||s.subChannelId!==r.subChannelId)return;(null===(a=Ie(["channel","get",e]))||void 0===a?void 0:a.data)&&t(r)}))),"channelId","channel"),Ya(Gr,"channelId","channel"),Ya(Ns,"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:o,userId:a}=be();o||console.log(j);const s=Date.now();r(`getChannels(tmpid: ${s}) > listen`);const i=new Ks(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ee(l)})),()=>{r(`getChannels(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:En,isUnreadCountSupport:An,convertFromRaw:Tn,preUpdateChannelCache:Mn,prepareChannelPayload:On});const Ys=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));_e(["communityUsers","collection",e],n)}))},Xs=e=>{var t;return null!==(t=Object.keys(A).find((t=>e.needApprovalOnPostCreation===A[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===A[t].onlyAdminCanPost)))&&void 0!==t?t:T},Zs=e=>{if(!e)return e;const t={};return e.forEach((e=>{t[`${e.userId}#${e.communityId}`]=e})),t},ei=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=qt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Xs({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)})),n=t.reduce(((e,{communityId:t})=>{var n;const r=null===(n=Ie(["communityUsers","collection",t]))||void 0===n?void 0:n.data;return r?Object.assign(Object.assign({},Zs(r)),e):e}),Zs(e.communityUsers)),r=Lt(Object.values(n)),o=ba(t,r);return Object.assign(Object.assign({},e),{communities:o,communityUsers:r})},ti=e=>{const{postSetting:t,storySetting:n}=e,r=qt(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?A[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},ni=async e=>{const t=be();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=ei(n),o=t.cache&&Date.now();return t.cache&&(Bt(r,{cachedAt:o}),Ys(r.communities,r.communityUsers)),{data:r.communities,cachedAt:o}};ni.locally=e=>{var t;const n=be();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Ie(["community","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),a=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:o,cachedAt:a.cachedAt}};const ri=async e=>{const t=be();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=ei(n),o=t.cache&&Date.now();t.cache&&(Bt(r,{cachedAt:o}),Ys(r.communities,r.communityUsers));const{communities:a}=r;return{data:a.find((t=>t.communityId===e)),cachedAt:o}};ri.locally=e=>{const t=be();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Ie(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const oi=async e=>{const t=be();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),o=ei(r),{communities:a}=o,s=t.cache&&Date.now();if(t.cache){Bt(o,{cachedAt:s});_e(["community","top-trending",{params:{options:{limit:n}}}],{communities:a.map(de("community"))})}return{data:a,cachedAt:s}};oi.locally=e=>{var t,n;const r=be();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},a=["community","top-trending",{params:{options:{limit:o}}}],{data:s,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{};if(!(null==s?void 0:s.communities.length))return;const c=s.communities.map((e=>Ie(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==s?void 0:s.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:i}:void 0};const ai=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{const r=ei(e);if(n.cache){Bt(r);const e=Ie(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},si=e=>ai("community.created",e),ii=e=>ai("community.updated",e),ci=e=>ai("community.deleted",e);function li(e){return null!=e}function di(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function ui(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"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=>!di(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!di(e,t,"ADD_COMMUNITY_USER")))}const hi=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{const o=ei(r),{communities:a,communityUsers:s}=o,i=ba(a,s);if(o.communities=i,n.cache){Bt(o);const n=Ie(["community","get",o.communities[0].communityId]),r=ui(e,o).map((e=>{const t=Ie(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(li);t(n.data,r)}else t(o.communities[0],ui(e,o))}))},pi=e=>hi("community.userAdded",e),fi=e=>hi("community.userRemoved",e),gi=e=>hi("community.userBanned",e),mi=e=>hi("community.userChanged",e),yi=e=>hi("community.userUnbanned",e),vi=e=>hi("community.roleAdded",e),bi=e=>hi("community.roleRemoved",e),wi=e=>hi("community.joined",e),Ci=e=>hi("community.left",e);class Ii extends Cs{async getRequest(e,t){const{limit:n=U}=e,r=qt(e,["limit"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:Dn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:o})});return a}}class _i extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Si,ki;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Si||(Si={})),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"}(ki||(ki={}));class Ei extends Cs{async getRequest(e,t){const{limit:n=U}=e,r=qt(e,["limit"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v3/communities/${r.communityId}/users`,{params:Object.assign(Object.assign({},r),{options:o})});return a}}class Ai extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(t,n)=>{var r;const o=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;o&&(e===ki.OnCommunityUserRoleAdded&&"displayName"===this.query.sortBy||(n.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?o.data=o.data.filter((e=>e!==t)):o.data.includes(t)||(o.data=[t,...o.data])})),_e(this.cacheKey,o),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ti extends Es{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new Ei(e),n,r,t),this.query=e,this.queryStreamController=new Ai(this.query,this.cacheKey,this.notifyChange.bind(this),ei),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:wi,action:ki.OnCommunityJoined},{fn:Ci,action:ki.OnCommunityLeft},{fn:gi,action:ki.OnCommunityUserBanned},{fn:mi,action:ki.OnCommunityUserChanged},{fn:vi,action:ki.OnCommunityUserRoleAdded},{fn:bi,action:ki.OnCommunityUserRoleRemoved},{fn:yi,action:ki.OnCommunityUserUnbanned}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["communityUsers","get",e]))).filter(li).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);switch(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),this.query.sortBy){case"firstCreated":t=t.sort(Ne);break;case"displayName":t=t.sort(((e,t)=>{var n,r,o,a;return(null===(n=null==e?void 0:e.user)||void 0===n?void 0:n.displayName)&&(null===(r=null==t?void 0:t.user)||void 0===r?void 0:r.displayName)?null===(o=null==e?void 0:e.user)||void 0===o?void 0:o.displayName.localeCompare(null===(a=null==t?void 0:t.user)||void 0===a?void 0:a.displayName):0}));break;default:t=t.sort(Fe)}return t}}class Mi extends Cs{async getRequest(e,t){const{limit:n=U}=e,r=qt(e,["limit"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get(`/api/v3/communities/${r.communityId}/users`,{params:Object.assign(Object.assign({},r),{options:o})});return a}}class Oi extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Bt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Pi;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Pi||(Pi={}));class Ri extends Es{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new Mi(e),n,r,t),this.query=e,this.queryStreamController=new Oi(this.query,this.cacheKey,this.notifyChange.bind(this),ei),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:wi,action:Pi.OnCommunityJoined},{fn:Ci,action:Pi.OnCommunityLeft},{fn:gi,action:Pi.OnCommunityUserBanned},{fn:mi,action:Pi.OnCommunityUserChanged},{fn:bi,action:Pi.OnCommunityUserRoleRemoved},{fn:yi,action:Pi.OnCommunityUserUnbanned}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["communityUsers","get",e]))).filter(li).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),t}}var Ui=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Xe("community.userAdded",r);const o=$t(r,"communityUsers");n.cache&&Bt(o);const{communityUsers:a}=o;return!!a.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=be();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Xe("community.userRemoved",r);const o=$t(r,"communityUsers");n.cache&&Bt(o);const{communityUsers:a}=o;return!!a.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Ne),n},getMembers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const s=new Ti(e,(e=>{console.log("resp",e),t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{Ee(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const s=new Ri(e,(e=>{t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{Ee(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:pi,onCommunityUserRemoved:fi,onCommunityUserBanned:gi,onCommunityUserChanged:mi,onCommunityUserUnbanned:yi,onCommunityUserRoleAdded:vi,onCommunityUserRoleRemoved:bi,onCommunityJoined:wi,onCommunityLeft:Ci});class xi extends Es{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new Ii(e),n,r,t),this.query=e,this.queryStreamController=new _i(this.query,this.cacheKey,this.notifyChange.bind(this),ei),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:ci,action:Si.OnCommunityDeleted},{fn:ii,action:Si.OnCommunityUpdated},{fn:wi,action:ki.OnCommunityJoined},{fn:Ci,action:ki.OnCommunityLeft},{fn:mi,action:ki.OnMemberCountChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;return this.query.includeDeleted&&(n=Ae(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=Re(n,this.query.membership,t)),n}}class ji extends Cs{async getRequest(e,t){const{limit:n=U}=e,r=qt(e,["limit"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:Dn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:o})});return a}}var Di;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Di||(Di={}));class Ni extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&(Bt(t,{cachedAt:r}),Ys(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&(this.query.displayName&&e===Di.OnCommunityCreated||(r.data=[...new Set([t.communityId,...r.data])],_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bi extends Es{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new ji(e),n,r,t),this.query=e,this.queryStreamController=new Ni(this.query,this.cacheKey,this.notifyChange.bind(this),ei),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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:si,action:Di.OnCommunityCreated},{fn:ci,action:Di.OnCommunityDeleted},{fn:ii,action:Di.OnCommunityUpdated},{fn:wi,action:ki.OnCommunityJoined},{fn:Ci,action:ki.OnCommunityLeft},{fn:mi,action:ki.OnMemberCountChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(null!==(o=a.data.map((e=>Ie(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;if(this.query.includeDeleted&&(n=Ae(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=Re(n,this.query.membership,t)),!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Ne;case"lastCreated":default:return Fe;case"displayName":return je}})();n=n.sort(e)}return n}}const Fi=async e=>{const t=be();t.log("community/getTrendingCommunities",e);const{limit:n=U}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),o=ei(r),{communities:a}=o,s=t.cache&&Date.now();return t.cache&&Bt(o,{cachedAt:s}),{data:a,cachedAt:s}},qi=(e,t,n)=>{let r=e;r=Ae(r,"displayName",t.displayName),t.includeDeleted||(r=Ae(r,"isDeleted",!1)),t.categoryId&&(r=r.filter((e=>{var n;return null===(n=e.categoryIds)||void 0===n?void 0:n.includes(t.categoryId)}))),t.tags&&(r=r.filter((e=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))}))),t.membership&&n&&(r=Re(r,t.membership,n));const o=t.sortBy||"lastCreated";return"lastCreated"!==o&&"firstCreated"!==o||(r=r.sort("lastCreated"===o?Fe:Ne)),"displayName"===o&&(r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(je)),r},Li=async e=>{const t=be();t.log("community/getRecommendedCommunities",e);const{limit:n=U}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:n}}}),o=ei(r),{communities:a}=o,s=t.cache&&Date.now();return t.cache&&Bt(o,{cachedAt:s}),{data:a,cachedAt:s}};var $i=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/addRoles",e,t,n);const{data:o}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),a=$t(o,"communityUsers");r.cache&&Bt(a);const{communityUsers:s}=a;return!!s.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/removeRoles",e,t,n);const{data:o}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),a=$t(o,"communityUsers");r.cache&&Bt(a);const{communityUsers:s}=a;return!!s.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=be();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),o=$t(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{communityUsers:s}=o;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:a}},unbanMembers:async(e,t)=>{const n=be();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),o=$t(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a});const{communityUsers:s}=o;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:a}}}),Ki=Object.freeze({__proto__:null,Moderation:$i,Membership:Ui,getCommunityByIds:ni,createCommunity:async e=>{const t=be();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",ti(e));Xe("community.created",n);const r=ei(n),o=t.cache&&Date.now();t.cache&&(Bt(r,{cachedAt:o}),Ys(r.communities,r.communityUsers));const{communities:a}=r;return{data:a[0],cachedAt:o}},updateCommunity:async(e,t)=>{const n=be();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,ti(t));Xe("community.updated",r);const o=ei(r),a=n.cache&&Date.now();n.cache&&(Bt(o,{cachedAt:a}),Ys(o.communities,o.communityUsers));const{communities:s}=o;return{data:s.find((t=>t.communityId===e)),cachedAt:a}},deleteCommunity:async e=>{const t=be();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await ri(e);return Xe("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=be();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Xe("community.joined",n);const r=ei(n),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{communityUsers:a}=r;return!!a.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=be();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Xe("community.left",n);const r=ei(n),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{communityUsers:a}=r;return!!a.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:oi,onCommunityCreated:si,onCommunityUpdated:ii,onCommunityDeleted:ci,observeCommunity:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const o=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&o(t,n)},s=[];return s.push(ii((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),ci((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),wi((e=>a({data:e,loading:!1,origin:"event"},"onJoin"))),Ci((e=>a({data:e,loading:!1,origin:"event"},"onLeft"))),pi((e=>a({data:e,loading:!1,origin:"event"},"onUserAdded"))),fi((e=>a({data:e,loading:!1,origin:"event"},"onUserRemoved"))),gi((e=>a({data:e,loading:!1,origin:"event"},"onUserBanned"))),yi((e=>a({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),ie(ae(ri,e),(e=>(e.data||e.error)&&o(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},searchCommunities:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`searchCommunities(tmpid: ${a}) > listen`);const s=new xi(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>Ee(c))),()=>{r(`searchCommunities(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getCommunities(tmpid: ${a}) > listen`);const s=new Bi(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>Ee(c))),()=>{r(`getCommunities(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Ro(e,t,"communityId",ri,[ii,ci,wi,Ci,gi,yi,mi]),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:o,userId:a}=be();o||console.log(j);const s=Date.now();r(`getTrendingCommunities(tmpid: ${s}) > listen`);const{limit:i}=e,c=null!=i?i:U,{policy:l=x}=null!=n?n:{},d=[],u=["community","top-trending",{params:{options:{limit:c}}}],h=(n,r=!1)=>{var o,s;const i=null!==(o=n.data.map((e=>Ie(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[];t({onNextPage:p,data:r?qi(i,e,a):i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},p=(t=!1)=>{var n,r;const o=null===(n=Ie(u))||void 0===n?void 0:n.data,a=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];if(!t&&a.length>0&&!(null==o?void 0:o.params.page))return;const s=ae(Fi,e);ie(s,(({data:t,error:n,loading:r})=>{const o={loading:r,error:n,params:e,data:a};t&&(o.data=[...new Set([...a,...t.map(de("community"))])]),_e(u,o),h(o)}),se(l,L))};return d.push(mi((e=>{var t;const n=null===(t=Ie(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],_e(u,n),h(n))}))),p(!0),d.push((()=>Ee(u))),()=>{r(`getTrendingCommunities(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:o,userId:a}=be();o||console.log(j);const s=Date.now();r(`getRecommendedCommunities(tmpid: ${s}) > listen`);const{limit:i}=e;qt(e,["limit"]);const c=null!=i?i:U,{policy:l=x}=null!=n?n:{},d=[],u=["community","recommended",{params:{options:{limit:c}}}],h=(n,r=!1)=>{var o,s;const i=null!==(o=n.data.map((e=>Ie(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[];t({onNextPage:p,data:r?qi(i,e,a):i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},p=(t=!1)=>{var n,r;const o=null===(n=Ie(u))||void 0===n?void 0:n.data,a=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];if(!t&&a.length>0&&!(null==o?void 0:o.params.page))return;const s=ae(Li,e);ie(s,(({data:t,error:n,loading:r})=>{const o={loading:r,error:n,params:e,data:a};t&&(o.data=[...new Set([...a,...t.map(de("community"))])]),_e(u,o),h(o)}),se(l,L))};return d.push(mi((e=>{var t;const n=null===(t=Ie(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],_e(u,n),h(n))}))),p(!0),d.push((()=>Ee(u))),()=>{r(`getRecommendedCommunities(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const zi=async e=>{const t=be();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&&Bt(n,{cachedAt:r});const{categories:o}=n;return{data:pn.category(o.find((t=>t.categoryId===e))),cachedAt:r}};zi.locally=e=>{const t=be();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Ie(["category","get",e]);return n?{data:pn.category(n.data),cachedAt:n.cachedAt}:void 0};const Vi=async e=>{const t=be();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:o,includeDeleted:a}=n,s=qt(n,["page","limit","includeDeleted"]),i=r?{token:r}:o?{limit:o}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},s),{isDeleted:Dn(a),options:i})}),{paging:l}=c,d=qt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Bt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},s),{includeDeleted:a,options:i})];_e(e,{categories:u.map(de("category")),paging:l})}return{data:u,cachedAt:h,paging:l}};Vi.locally=e=>{var t,n;const r=be();if(r.log("category/queryCategories.locally",e),!r.cache)return;const o=null!=e?e:{},{page:a,limit:s=10}=o,i=qt(o,["page","limit"]),c=a?{token:a}:s?{limit:s}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Ie(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ie(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:p}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:p}:void 0};var Qi=Object.freeze({__proto__:null,getCategory:zi,getCategories:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getCategories(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,o;const a=null===(r=Ie(u))||void 0===r?void 0:r.data,s=null!==(o=null==a?void 0:a.data)&&void 0!==o?o:[];if(!n&&s.length>0&&!(null==a?void 0:a.params.page))return;const d=ae(Vi,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==a?void 0:a.params.page}));ie(d,(({data:n,error:r,loading:o,paging:a})=>{const i={loading:o,error:r,params:{page:null==a?void 0:a.next},data:s};n&&(i.data=[...new Set([...s,...n.map(de("category"))])]),_e(u,i),(n=>{var r,o;let a=null!==(r=n.data.map((e=>Ie(["category","get",e]))).filter(Boolean).map((({data:e})=>pn.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(a=Ae(a,"isDeleted",!1)),e.sortBy){case"firstCreated":a=a.sort(Ne);break;case"lastCreated":a=a.sort(Fe);break;default:a=a.sort(De)}t({onNextPage:h,data:a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})})(i)}),se(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const Hi=async e=>{const t=be();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:o,queryToken:a}=n,s=qt(n,["useCustomRanking","page","queryToken"]);r&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead'),o&&console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');const i=a?{token:a}:o?{token:Y(o,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{options:i})}),{paging:l}=c,d=qt(c,["paging"]),u=$t(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Bt(u);const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},o)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=X(l.next),g=X(l.previous);return{data:h.map(pn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};Hi.locally=e=>{var t,n;const r=be();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:a}=o,s=qt(o,["page"]),i=["globalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:c,cachedAt:l}=null!==(t=Ie(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Ie(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(pn.post),{paging:u}=c,h=X(null==c?void 0:c.paging.previous),p=X(null==c?void 0:c.paging.next);return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d,cachedAt:l,prevPage:h,nextPage:p,paging:u}:void 0};const Wi=async e=>{const t=be();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r,queryToken:o,limit:a}=n,s=qt(n,["page","queryToken","limit"]),i=o?{token:o}:r?{token:Y(r,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},s),{limit:o?void 0:a,options:i})}),{paging:l}=c,d=qt(c,["paging"]),u=$t(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Bt(u);const e=["customGlobalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=X(l.next),g=X(l.previous);return{data:h.map(pn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};Wi.locally=e=>{var t,n;const r=be();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:a}=o,s=qt(o,["page"]),i=["customGlobalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:c,cachedAt:l}=null!==(t=Ie(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Ie(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),u=X(null==c?void 0:c.paging.previous),h=X(null==c?void 0:c.paging.next),{paging:p}=c;return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d.map(pn.post),cachedAt:l,prevPage:u,nextPage:h,paging:p}:void 0};var Gi=Object.freeze({__proto__:null,queryGlobalFeed:Hi,getCustomRankingGlobalFeed:Wi});const Ji=async e=>{const t=be();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=>{Q(null==t?void 0:t.code)&&Ft("post",e)})),t}const o=$t(r,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Bt(o,{cachedAt:a}),{data:o.posts.map(pn.post),cachedAt:a}};Ji.locally=e=>{var t;const n=be();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Ie(["post","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),a=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:o.map(pn.post),cachedAt:a.cachedAt}};const Yi=async(e,t=!1)=>{var n;const r=be(),o=await ya(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===o.data.targetType){const e=await ri(o.data.targetId),t=(null!==(n=Ce(["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));Xe("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const a=Object.assign(Object.assign({},o.data),{isDeleted:!0});return Xe("post.deleted",{posts:[a],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Ft("post",e)}),0):ke(["post","get",e],{isDeleted:!0}),pn.post(a)},Xi=async e=>{const t=be();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=>{Q(null==t?void 0:t.code)&&Ft("comment",e)})),t}const o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),{data:r.comments.map((e=>pn.comment(e))),cachedAt:o}};Xi.locally=e=>{var t;const n=be();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Ie(["comment","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),a=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:o.map((e=>pn.comment(e))),cachedAt:a.cachedAt}};const Zi=(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})},ec=async e=>{const t=be();t.log("story/getStoryByStoryId",e);const n=Ie(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;tr("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Zi(n.data)}catch(t){throw Q(null==t?void 0:t.code)&&Ft("story",e),t}const o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),{data:r.stories[0],cachedAt:o}};ec.locally=e=>{const t=be();t.log("story/getStorybyStoryId",e);const n=Ie(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;tr("story",e)}const r=t.cache&&Date.now(),o=Ie(["story","get",e]);if(o)return{data:o.data,cachedAt:r}};const tc=async(e,t=!1)=>{const n=be(),r=await va(e);await n.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0});if("story"===r.data.referenceType){const e=await ec(r.data.referenceId);Xe("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=await ya(r.data.referenceId);Xe("local.post.updated",{posts:[e.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}return Xe("local.comment.deleted",{comments:[o],commentChildren:[],files:[],users:[],communityUsers:[]}),t?We((()=>Ft("comment",e))):ke(["comment","get",e],{isDeleted:!0}),o},nc=async e=>{const t=be();let n;t.log("comment/getComment",e),tr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Q(null==t?void 0:t.code)&&Ft("comment",e),t}const r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{comments:o}=n;return{data:o.find((t=>t.commentId===e)),cachedAt:r}};nc.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ie(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const rc=async e=>{const t=be();t.log("comment/queryComments",e);const{limit:n=10,includeDeleted:r}=e,o=qt(e,["limit","includeDeleted"]),a={type:o.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:s}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:Dn(r),options:a})}),{paging:i}=s,c=(e=>{const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})})(qt(s,["paging"])),{comments:l}=c,d=t.cache&&Date.now();if(t.cache){Bt(c,{cachedAt:d});const e=["comment","query",Object.assign(Object.assign({},o),{options:{limit:n}})];_e(e,{comments:l.map(de("comment")),paging:i})}return{data:l,cachedAt:d,paging:i}};var oc=Object.freeze({__proto__:null,getCommentByIds:Xi,createComment:async e=>{const t=be();t.log("comment/createComment",e);const{data:n}=await t.http.post("/api/v3/comments",e),{comments:r}=n;if(0===r.length)throw new Error("Comment not created");const o=t.cache&&Date.now();if(t.cache&&Bt(n,{cachedAt:o}),["post","content"].includes(e.referenceType)){const t=await ya(e.referenceId);Xe("local.post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=Ie(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ie(["story","get",t.data]);(null==e?void 0:e.data)&&Xe("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,r[0].commentId])]})],categories:[],comments:r,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return Xe("local.comment.created",n),{data:pn.comment(r[0]),cachedAt:o}},updateComment:async(e,t)=>{const n=be();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o}),Xe("comment.updated",r);const{comments:a}=r;return{data:pn.comment(a.find((t=>t.commentId===e))),cachedAt:o}},deleteComment:tc,softDeleteComment:async e=>{be().log("comment/softDeleteComment",e);return tc(e)},hardDeleteComment:async e=>{be().log("comment/hardDeleteComment",e);return tc(e,!0)},flagComment:async e=>{const t=be();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Bt(n),Xe("comment.flagged",n),!!n},unflagComment:async e=>{const t=be();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Bt(n),Xe("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=be();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Ba,onCommentUpdated:Fa,onCommentDeleted:qa,onCommentFlagged:La,onCommentUnflagged:$a,onCommentReactionAdded:Ka,onCommentReactionRemoved:za,observeComments:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const o=[],a=(n,r)=>{var o,a;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(a=t[r])||void 0===a||a.call(t,n)}};return o.push(Ba((e=>a(e,"onCreate"))),Fa((e=>a(e,"onUpdate"))),qa((e=>a(e,"onDelete"))),La((e=>a(e,"onFlagged"))),$a((e=>a(e,"onUnflagged"))),Ka((e=>a(e,"onReactionAdded"))),za((e=>a(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeComment(tmpid: ${o}) > listen`);const a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&a(t,n)},i=[];return i.push(Fa((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),qa((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),La((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),$a((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ka((e=>s({data:e,loading:!1,origin:"event"},"onReactionAdded"))),za((e=>s({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(ae(nc,e),(e=>(e.data||e.error)&&a(e,"onFetch")),se(n)),()=>{r(`observeComment(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getComment:(e,t)=>Ro(e,t,"commentId",nc,[qa,La,Ka,za,$a,Fa,t=>Ba((n=>{if(n.parentId!==e)return;const r=Ie(["comment","get",n.parentId]);(null==r?void 0:r.data)&&t(Object.assign(Object.assign({},r.data),{childrenNumber:r.data.childrenNumber+1,children:[...new Set([...r.data.children,n.commentId])]}))}))]),getComments:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`getComments(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),{policy:c=x}=null!=n?n:{},l=[],d=e.sortBy?e.sortBy:"lastCreated",u=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||"",sortBy:d}],h=n=>{var r,o;let a=null!==(r=n.data.map((e=>Ie(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>pn.comment(e))))&&void 0!==r?r:[];e.includeDeleted||(a=Ae(a,"isDeleted",!1)),a=a.sort("lastCreated"===d?Fe:Ne),t({onNextPage:f,data:a,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},p=t=>n=>{var r;const o=null===(r=Ie(u))||void 0===r?void 0:r.data;e.referenceId===n.referenceId&&e.referenceType===n.referenceType&&o&&("onCreate"===t?o.data=[...new Set([n.commentId,...o.data])]:"onDelete"===t&&(o.data=o.data.filter((e=>e!==n.commentId))),_e(u,o),h(o))},f=(e=!1)=>{var t,n,r;const o=null===(t=Ie(u))||void 0===t?void 0:t.data,a=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null===(r=null==o?void 0:o.params)||void 0===r?void 0:r.page))return;const l=ae(rc,Object.assign(Object.assign({},i),{limit:s,page:e||null==o?void 0:o.params.page}));ie(l,(({data:t,error:n,loading:r,paging:o})=>{const s={loading:r,error:n,params:{page:null==o?void 0:o.next},data:a};t&&(s.data=e?t.map(de("comment")):[...new Set([...a,...t.map(de("comment"))])]),_e(u,s),h(s)}),se(c,L))};return l.push(Ba(p("onCreate")),Fa(p("onUpdate")),qa(p("onDelete")),La(p("onFlagged")),$a(p("onUnflagged")),Ka(p("onReactionAdded")),za(p("onReactionRemoved"))),f(!0),l.push((()=>Ee(u))),()=>{r(`getComments(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});const ac=async e=>{const t=be();t.log("post/queryPosts",e);const{page:n,limit:r=10,includeDeleted:o}=e,a=qt(e,["page","limit","includeDeleted"]),{dataTypes:s,matchingOnlyParentPost:i}=a,c=n?{token:n}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},a),{isDeleted:Dn(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length),options:c})}),{paging:d}=l,u=qt(l,["paging"]),h=$t(u,"communityUsers"),{posts:p}=u,f=t.cache&&Date.now();if(t.cache){Bt(h,{cachedAt:f});const e=["post","query",Object.assign(Object.assign({},a),{options:c})];_e(e,{posts:p.map(de("post")),paging:d})}return{data:p.map(pn.post),cachedAt:f,paging:d}};var sc=Object.freeze({__proto__:null,getPostByIds:Ji,createPost:async e=>{const t=be();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);Xe("post.created",n);const r=$t(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Bt(r,{cachedAt:o});const{posts:a}=r;return{data:pn.post(a[0]),cachedAt:o}},updatePost:async(e,t)=>{const n=be();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=$t(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a}),Xe("local.post.updated",o);const{posts:s}=o;return{data:pn.post(s.find((t=>t.postId===e))),cachedAt:a}},editPost:async(e,t)=>{const n=be();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=$t(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Bt(o,{cachedAt:a}),Xe("local.post.updated",o);const{posts:s}=o;return{data:pn.post(s.find((t=>t.postId===e))),cachedAt:a}},deletePost:Yi,softDeletePost:async e=>{be().log("post/softDeletePost",e);const t=await Yi(e,!1);return pn.post(t)},hardDeletePost:async e=>{be().log("post/hardDeletePost",e);const t=await Yi(e,!0);return pn.post(t)},approvePost:async e=>{const t=be();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Xe("post.approved",n),"community"===n.posts[0].targetType&&Xe("community.updated",n);const r=$t(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),{data:pn.post(r.posts.find((t=>t.postId===e))),cachedAt:o}},declinePost:async e=>{const t=be();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Xe("community.updated",n),Xe("post.declined",n);const r=$t(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Bt(r,{cachedAt:o}),{data:pn.post(n.posts.find((t=>t.postId===e))),cachedAt:o}},flagPost:async e=>{const t=be();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Bt($t(n,"communityUsers")),Xe("post.flagged",n),!!n},unflagPost:async e=>{const t=be();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Bt($t(n,"communityUsers")),Xe("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=be();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Ta,onPostUpdated:Ma,onPostDeleted:Oa,onPostApproved:Pa,onPostDeclined:Ra,onPostFlagged:Ua,onPostUnflagged:xa,onPostReactionAdded:ja,onPostReactionRemoved:Da,observePosts:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const o=[],a=(n,r)=>{var o,a;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(pn.post(n));null===(o=t.onEvent)||void 0===o||o.call(t,r,pn.post(n)),null===(a=t[r])||void 0===a||a.call(t,pn.post(n))}};return o.push(Ta((e=>a(e,"onCreate"))),Ma((e=>a(e,"onUpdate"))),Oa((e=>a(e,"onDelete"))),Pa((e=>a(e,"onApproved"))),Ra((e=>a(e,"onDeclined"))),Ua((e=>a(e,"onFlagged"))),xa((e=>a(e,"onUnflagged"))),ja((e=>a(e,"onReactionAdded"))),Da((e=>a(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePost(tmpid: ${o}) > listen`);const a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&a(Object.assign(Object.assign({},t),{data:t.data&&pn.post(t.data)}),n)},i=[];return i.push(Ma((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Oa((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Pa((e=>s({data:e,loading:!1,origin:"event"},"onApproved"))),Ra((e=>s({data:e,loading:!1,origin:"event"},"onDeclined"))),Ua((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),xa((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),ja((e=>s({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Da((e=>s({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(ae(ya,e),(e=>(e.data||e.error)&&a(Object.assign(Object.assign({},e),{data:e.data&&pn.post(e.data)}),"onFetch")),se(n)),()=>{r(`observePosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPost:(e,t)=>Ro(e,t,"postId",ya,[Pa,Ra,t=>Oa((n=>{var r;let o=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Ie(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),_e(["post","get",e.postId],e),o=e)}t(o)})),Ua,e=>ja((t=>{e(pn.post(t))})),e=>Da((t=>{e(pn.post(t))})),xa,Ma,Ya((t=>Ba((async n=>{n.referenceId===e&&(await ya(e),t(n))}))),"referenceId","post"),Ya((t=>qa((async n=>{n.referenceId===e&&(await ya(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getPosts(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["post","collection",{targetId:e.targetId,targetType:e.targetType}],h=n=>{var r,o,a;let s=null!==(r=n.data.map((e=>Ie(["post","get",e]))).filter(Boolean).map((({data:e})=>pn.post(e))))&&void 0!==r?r:[];const i=e.sortBy?e.sortBy:"lastCreated";s=s.sort("lastCreated"===i?Fe:Ne),e.includeDeleted||(s=Ae(s,"isDeleted",!1)),e.tags&&(s=s.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(s=Pe(s,e.feedType)),(null===(o=e.dataTypes)||void 0===o?void 0:o.length)&&(s=Ue(s,e.dataTypes)),t({onNextPage:f,data:s,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})},p=t=>n=>{var r,o;const a=null===(r=Ie(u))||void 0===r?void 0:r.data;if(a){if(n.parentPostId&&n.isDeleted){const t=null===(o=Ie(["post","get",n.parentPostId]))||void 0===o?void 0:o.data;if(!t||(null==t?void 0:t.targetId)!==e.targetId)return;t.children=t.children.filter((e=>e!==n.postId)),_e(["post","get",t.postId],t)}else{if(e.targetId!==n.targetId)return;if(e.targetType!==n.targetType)return}a.data="onDeclined"===t?a.data.filter((e=>e!==n.postId)):[...new Set([n.postId,...a.data])],_e(u,a),h(a)}},f=(e=!1)=>{var t,n,r;const o=null===(t=Ie(u))||void 0===t?void 0:t.data,a=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null===(r=null==o?void 0:o.params)||void 0===r?void 0:r.page))return;const s=ae(ac,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==o?void 0:o.params.page}));ie(s,(({data:t,error:n,loading:r,paging:o})=>{const s={loading:r,error:n,params:{page:null==o?void 0:o.next},data:a};t&&(s.data=e?t.map(de("post")):[...new Set([...a,...t.map(de("post"))])]),_e(u,s),h(s)}),se(l,L))};return d.push(Ta(p("onCreate")),Pa(p("onApproved")),Ra(p("onDeclined")),Oa(p("onDelete")),Ma(p("onUpdate")),Ua(p("onFlagged")),xa(p("onUnflagged")),ja(p("onReactionAdded")),Da(p("onReactionRemoved")),Ya((e=>Ba((async t=>{var n;const r=null===(n=Ie(u))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await ya(t.referenceId),e(t))}))),"referenceId","post")(p("onUpdate")),Ya((e=>qa((async t=>{var n;const r=null===(n=Ie(u))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await ya(t.referenceId),e(t))}))),"referenceId","post")(p("onUpdate"))),f(!0),d.push((()=>Ee(u))),()=>{r(`getPosts(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const ic=async e=>{const t=be();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}};ic.locally=e=>{const t=be();if(t.log("stream/getStream",e),!t.cache)return;const n=Ie(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const cc=e=>{const t=be();return Ye(t,"stream/onStreamStarted","v3.video-streaming.didStart",(t=>{Bt(t),e(t.videoStreamings[0])}))},lc=e=>{const t=be();return Ye(t,"stream/onStreamStropped","v3.video-streaming.didStop",(t=>{Bt(t),e(t.videoStreamings[0])}))},dc=e=>{const t=be();return Ye(t,"stream/onStreamRecorded","v3.video-streaming.didRecord",(t=>{Bt(t),e(t.videoStreamings[0])}))},uc=(e,t)=>Ro(e,t,"streamId",ic,[dc,cc,lc]);uc.locally=e=>{const t=be();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Ie(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const hc=async e=>{const t=be();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:o}=n,a=qt(n,["page","limit"]),s=r?{token:r}:o?{limit:o}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},a),{options:s})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Bt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var pc=Object.freeze({__proto__:null,createStream:async e=>{const t=be();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o[0],cachedAt:r}},updateStream:async(e,t)=>{const n=be();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o});const{videoStreamings:a}=r;return{data:a.find((t=>t.streamId===e)),cachedAt:o}},deleteStream:async e=>{const t=be();t.log("stream/deleteStream",e);const n=await ic(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:o}=r,a=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ke(["stream","get",e],a),o},disposeStream:async e=>{const t=be();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&&Bt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}},queryStreams:async e=>{const t=be();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r}=n,o=qt(n,["page"]),{data:a}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:{token:Y(r,"skiplimit")}})}),{paging:s,results:i}=a,{videoStreamings:c}=i,l=t.cache&&Date.now();t.cache&&Bt(i,{cachedAt:l});const d=X(s.next);return{data:c,cachedAt:l,prevPage:X(s.previous),nextPage:d}},getStream:ic,onStreamStarted:cc,onStreamStopped:lc,onStreamRecorded:dc,getStreamById:uc,getStreams:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(j);const a=Date.now();r(`getStreams(tmpid: ${a}) > listen`);const{limit:s}=e,i=qt(e,["limit"]),c=null!=s?s:U,{policy:l=x}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Ae(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Fe:Ne),n},p=(e,n=!1)=>{var r,o;const a=null!==(r=e.data.map((e=>Ie(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:g,data:n?h(a):a,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Ie(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],_e(u,n),p(n,!0))},g=(e=!1)=>{var t,n;const r=null===(t=Ie(u))||void 0===t?void 0:t.data,o=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null==r?void 0:r.params.page))return;const a=ae(hc,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ie(a,(({data:e,error:t,loading:n,paging:r})=>{const a={loading:n,error:t,params:{page:null==r?void 0:r.next},data:o};e&&(a.data=[...new Set([...o,...e.map(de("stream"))])]),_e(u,a),p(a)}),se(l))};return d.push(dc(f()),cc(f()),lc(f())),g(!0),()=>{r(`getStreams(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const fc=async e=>{const t=be();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}};fc.locally=e=>{const t=be();if(t.log("poll/getPoll",e),!t.cache)return;const n=Ie(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const gc=e=>{const t=be();return Ye(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Bt(n),e(n.polls[0])}))},mc=e=>{const t=be();return Ye(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Bt(n),e(n.polls[0])}))};var yc=Object.freeze({__proto__:null,createPoll:async e=>{const t=be();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Bt(n,{cachedAt:r});const{polls:o}=n;return{data:o[0],cachedAt:r}},closePoll:async e=>{const t=be();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&&Bt(n,{cachedAt:r}),Xe("poll.updated",n);const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=be();t.log("poll/deletePoll",e);const n=await fc(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:o}=r,a=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ke(["poll","get",e],a),Xe("poll.deleted",{polls:[a],users:[]}),o},votePoll:async(e,t)=>{const n=be();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),o=n.cache&&Date.now();n.cache&&Bt(r,{cachedAt:o});const{polls:a}=r;return Xe("poll.updated",r),{data:a.find((t=>t.pollId===e)),cachedAt:o}},onPollUpdated:gc,onPollDeleted:mc,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePoll(tmpid: ${o}) > listen`);const a=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&a(t,n)},i=[];return i.push(gc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),mc((e=>s({data:e,loading:!1,origin:"event"},"onDelete")))),ie(ae(fc,e),(e=>(e.data||e.error)&&a(e,"onFetch")),se(n)),()=>{r(`observePoll(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPoll:(e,t)=>Ro(e,t,"pollId",fc,[gc,mc])});const vc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function bc(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function wc(e){const n=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(t.atob(n));return crypto.subtle.importKey("pkcs8",r,vc,!1,["sign"])}async function Cc({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const o=e();if(o.length)try{const n=(new Date).toISOString(),a=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=b.default.v4(),o=`nonceStr=${r}&timestamp=${e}&data=${n}==`,a=(new TextEncoder).encode(o),s=await wc("-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----");return{signature:bc(await crypto.subtle.sign(vc,s,a)),nonceStr:r}}({timestamp:n,streams:o});if(!a||!a.signature)throw new Error("Signature is undefined");const s={signature:a.signature,nonceStr:a.nonceStr,timestamp:n,streams:o},i=be();return await i.http.post("/api/v3/user-event/video-streaming",s),t().length||e().length||r(),!0}catch(e){return o.forEach((e=>n(e))),!1}}class Ic{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((()=>{Cc({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let _c=null;class Sc{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=_c||(_c=new Ic,_c),this._usageCollector.registerStream(e.id),this._sessionId=String(b.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_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 kc=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(!C.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await ic(t),{watcherUrl:r,status:o,recordings:a=[],resolution:s}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const i=document.createElement("video");i.id=t,i.controls=!0;const c=new C.default;if(c.attachMedia(i),"recorded"!==o){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=a.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new Sc(i,s).registerEvents(),i}});const Ec=e=>{const t=(e=>{var t;const n=be(),r=new Date,o=r.getTime()+31536e6,a=new Date(o).toISOString();let s=null===(t=Ie(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return s||(s={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:a,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Bt({storyTargets:[s]})),{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(o).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Bt(t),t},Ac=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const o=t.getAll("files")[0]||void 0;if(!o)return;const a=new FileReader;a.readAsDataURL(o),a.onload=()=>r(Ec(n?Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,videoFileId:{original:void 0},fileData:null==a?void 0:a.result})}):Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:null==a?void 0:a.result})})))}return r(Ec(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},Tc=async e=>{const t=be();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Zi(n.data);t.cache&&Bt(r),_e(["story-sync-state",e.targetId],"synced"),Xe("local.story.created",r);const o=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:o}},Mc=e=>e?Ie(["story","get",e]):{data:void 0,cachedAt:void 0},Oc=async(e,t=!1)=>{const n=be();let r;if(n.log("story/deleteStory",e),n.cache&&(r=Mc(e),null==r?void 0:r.data)){const{data:e}=r;Xe("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await n.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Pc=e=>{const t=be(),n=[Ye(t,"onStoryUpdated","story.updated",(async t=>{const n=Zi(t);Bt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Rc=e=>{const t=be(),n=[Ye(t,"onStoryUpdated","local.story.updated",(async t=>{Bt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Uc=e=>{const t=be(),n=[Ye(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=qt(t,["reactions"]),o=Zi(r),a=Sa("story.reactionAdded",Object.assign(Object.assign({},o),{reactions:n}));Bt(a),e(a.stories)}))];return()=>{n.forEach((e=>e()))}},xc=e=>{const t=be(),n=[Ye(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Bt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},jc=e=>{const t=be(),n=[Ye(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=qt(t,["reactions"]),o=Zi(r),a=Sa("story.reactionRemoved",Object.assign(Object.assign({},o),{reactions:n}));Bt(a),e(a.stories)}))];return()=>{n.forEach((e=>e()))}},Dc=e=>{const t=be(),n=[Ye(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Bt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Nc=e=>{e.forEach((e=>{const t=Ie(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||_e(["story-expire",e.targetId],n.toISOString())}))},Bc=e=>{e.forEach((e=>{_e(["story-reference",e.storyId],e.referenceId)}))},Fc=async({targetType:e,targetId:t,options:n})=>{const r=be();r.log("story/getActiveStoriesByTarget");const o=r.cache&&Date.now(),a=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"}}}),s=Zi(a.data);return r.cache&&(Bt(s),Nc(s.stories),Bc(s.stories)),{data:s.stories,cachedAt:o,paging:{next:void 0,previous:void 0}}},qc=e=>{const t=be(),n=[Ye(t,"onStoryCreated","story.created",(async t=>{const n=Zi(t,!0);Bt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Lc=e=>{const t=be(),n=[Ye(t,"onStoryCreated","local.story.created",(async t=>{Bt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},$c=e=>{const t=be(),n=[Ye(t,"onStoryDeleted","story.deleted",(async t=>{const n=Zi(t);Bt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Kc=e=>{const t=be(),n=[Ye(t,"onStoryDeleted","local.story.deleted",(async t=>{Bt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},zc=e=>{const t=be();return Ye(t,"onStoryError","local.story.error",(async t=>{Bt(t),e(t.stories)}))},Vc=e=>t=>e((e=>t(e[0]))),Qc=async e=>{const t=be();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Bt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class Hc extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=be(),n=t.cache&&Date.now(),r=Zi(e);t.cache&&(Bt(r,{cachedAt:n}),Nc(r.stories),Bc(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(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=Ie(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])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Wc extends ks{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Gc extends Es{constructor(e,t){const n=w.default(e),r=["story-target-ids","collection",n],o=new Wc(e);super(o,n,r,t),this.query=e,this.queryStreamController=new Hc(this.query,this.cacheKey,this.notifyChange.bind(this),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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 o=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let a=o.data.map((e=>Ie(["story","get",e]))).filter(Boolean).map((e=>pn.story(e.data)));(this.shouldNotify(a)||"event"!==e)&&(a=this.applyFilter(a),this.callback({onNextPage:void 0,data:a,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(Ne):r.sort(Fe)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qc,action:"onCreate"},{fn:Pc,action:"onUpdate"},{fn:$c,action:"onDelete"},{fn:zc,action:"onError"}])}}const Jc=(e,t)=>{var n,r;const o=null===(n=Ie(e))||void 0===n?void 0:n.data,a=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];_e(e,Object.assign(Object.assign({},o),{data:[...new Set([...a,...t])]}))};class Yc extends _s{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=e=>e}saveToMainDB(e){const t=be(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Bt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?_e(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Jc(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Jc(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 Xc extends Cs{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:o="unseen"}=e,a=await this.createRequest({seenState:"smart"===o?this.smartFilterState:o,limit:r,token:t});if(null===(n=a.paging)||void 0===n?void 0:n.next)return a;if("smart"!==o)return a;if("seen"===this.smartFilterState)return a;this.smartFilterState="seen";const s=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=s,{categories:(i=a).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}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 Zc extends Es{constructor(e,t){const n=w.default(e),r=["story-global-feed","collection",n],o=new Xc(e);super(o,n,r,t),this.query=e,this.queryStreamController=new Yc(this.query,this.cacheKey,this.notifyChange.bind(this),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||_e(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 o=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let a=o.data.map((e=>Ie(["storyTarget","get",e]))).filter(Boolean).map((e=>pn.storyTarget(e.data)));(this.shouldNotify(a)||"event"!==e)&&(a=this.applyFilter(a).map((e=>qt(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,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(Be);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(Be)||[],r=t.unseen.sort(Be)||[],o=t.seen.sort(Be)||[];return n.concat(r,o)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qc,action:"onCreate"},{fn:Pc,action:"onUpdate"},{fn:$c,action:"onDelete"},{fn:Lc,action:"onCreate"},{fn:Rc,action:"onUpdate"},{fn:Kc,action:"onDelete"},{fn:zc,action:"onError"}])}}var el=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},o="fit",a=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let s={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:o},syncState:"syncing",referenceId:Pt(),dataType:"image",items:a,targetType:e,targetId:t,metadata:r};const i=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),Ac({payload:s,formData:n},(e=>{Xe("local.story.created",e)}));try{const{data:e}=await ua(n);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t})}),Ac({payload:s,formData:n},(e=>{Xe("local.story.created",e)}));const r=await Tc(s);return r.data?Object.assign(Object.assign({},r),{data:pn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),Ac({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n},(e=>{Xe("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},o=[])=>{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},syncState:"syncing",referenceId:Pt(),dataType:"video",items:o,targetType:e,targetId:t,metadata:r};const s=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(s.setFullYear(s.getFullYear()+1))),Ac({payload:a,formData:n,isVideo:!0},(e=>{Xe("local.story.created",e)}));try{const{data:e}=await da(n,M.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t,videoFileId:{original:t}})}),Ac({payload:a,formData:n,isVideo:!0},(e=>{Xe("local.story.created",e)}));const r=await Tc(a);return r.data?Object.assign(Object.assign({},r),{data:pn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),Ac({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Xe("local.story.error",e)})),e}},hardDeleteStory:async e=>await Oc(e,!0),softDeleteStory:async e=>await Oc(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=be(),o=[],a=["story-target","collection",e],s=Date.now();n(`getActiveStoriesByTarget(tmpid: ${s}) > listen`),r||console.log(j);const i=t=>{var n,r;const o=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",a=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===o?"asc"===a?t.sort(Ne):t.sort(Fe):"asc"===a?t.sort(qe):t.sort(Le)},c=e=>{var n;const r=e.data.map((e=>{const t=Mc(e);if(null==t?void 0:t.data)return pn.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),o=[];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=i(e.get("error")||[]);o.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);o.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);o.push(...t)}}t({onNextPage:()=>!1,data:o||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(e,t,n=!1,r=!1,o=!1)=>{const s=Ie(a),i={loading:r,error:o,params:{page:void 0},data:(null==s?void 0:s.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));i.data=i.data.filter((e=>!t.includes(e)))||[]}else i.data=n?e.map(de("story")):[...new Set([...i.data,...e.map(de("story"))])];_e(a,i.data),c(i)},d=e=>t=>{l(t,e)};return(t=>{const n=ae(Fc,e);ie(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),o.push(qc(d("onCreate")),Pc(d("onUpdate")),$c(d("onDelete")),Uc(d("onReactionAdded")),jc(d("onReactionRemoved")),zc(d("onError")),Lc(d("onCreate")),Rc(d("onUpdate")),Kc(d("onDelete")),xc(d("onReactionAdded")),Dc(d("onReactionRemoved")),(e=>{const t=be();return Ye(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ie(a);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)||[]};c(n)})),(()=>Ee(a))),()=>{n(`getActiveStoriesByTarget(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Ro(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:pn.story(e.data)})):t(e)}),"storyId",ec,[Vc(Pc),Vc($c),Vc(Uc),Vc(jc),Vc(zc),Vc(Rc),Vc(Kc),Vc(xc),Vc(Dc)]),getTargetById:(e,t)=>Ro(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:pn.storyTarget(e.data[0])})):t(e)}),"query",(e=>Qc([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=be(),o=[],a=["storyTargets","collection",e],s=Date.now();n(`getTargetsByTargetIds(tmpid: ${s}) > listen`),r||console.log(j);const i=(e,n=!1,r=!1,o=!1)=>{const s=Ie(a),i={loading:r,error:o,params:{page:void 0},data:[]};e&&(i.data=n?e.map(de("storyTarget")):[...new Set([...(null==s?void 0:s.data)||[],...e.map(de("storyTarget"))])]),_e(a,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Ie(["storyTarget","get",e]);if(null==t?void 0:t.data)return pn.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})})(i)};return(t=>{const n=ae(Qc,e);ie(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),o.push((()=>Ee(a))),()=>{n(`getTargetsByTargetIds(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:o,userId:a}=be();o||console.log(j);const s=Date.now();r(`getStoriesByTargetIds(tmpid: ${s}) > listen`);const i=new Gc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ee(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:o,userId:a}=be();o||console.log(j);const s=Date.now();r(`getGlobalStoryTarget(tmpid: ${s}) > listen`);const i=new Zc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ee(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}}});return e.API_REGIONS=yt,e.CategoryRepository=Qi,e.ChannelRepository=Js,e.Client=Uo,e.CommentRepository=oc,e.CommunityPostSettingMaps=A,e.CommunityPostSettings=E,e.CommunityRepository=Ki,e.ContentFeedType=M,e.DefaultCommunityPostSetting=T,e.FeedRepository=Gi,e.FileRepository=ha,e.FileType=I,e.LiveStreamPlayer=kc,e.MessageContentType=O,e.MessageRepository=Ms,e.PollRepository=yc,e.PostContentType=P,e.PostRepository=sc,e.ReactionRepository=Wa,e.StoryRepository=el,e.StreamRepository=pc,e.SubChannelRepository=Ds,e.UserRepository=ca,e.VERSION=R,e.VideoResolution=_,e.VideoSize=k,e.VideoTranscodingStatus=S,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:o}=be();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const a=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(a).length&&(localStorage&&await localStorage.setItem(`${e}#${o}`,JSON.stringify(a)),!0)},e.createQuery=ae,e.createReport=async(e,t)=>{const n=be();n.log("report/createReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=Ga[e];return`/api/v3/${n}/${encodeURIComponent(t)}/flag`})());if(n.cache)if("message"===e){const e=await Kn(r);Bt(e)}else Bt("post"===e?$t(r,"communityUsers"):r);return Xe(`${e}.flagged`,r),!!r},e.createUserToken=async(e,t,n)=>{const r=await Ut(),o=xt(),a=_t(bt("http",t)),{data:s}=await a.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},o),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:s.accessToken}},e.deleteReport=async(e,t)=>{const n=be();n.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=Ga[e];return`/api/v3/${n}/${encodeURIComponent(t)}/unflag`})());if(n.cache)if("message"===e){const e=await Kn(r);Bt(e)}else Bt("post"===e?$t(r,"communityUsers"):r);return Xe(`${e}.unflagged`,r),!!r},e.disableCache=()=>{const e=be();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Ee,e.enableCache=(e={},t)=>{const n=be();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Oe,e.filterByCommunityMembership=Re,e.filterByFeedType=Pe,e.filterByPostDataTypes=Ue,e.filterByPropEquality=Ae,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Me,e.filterBySearchTerm=xe,e.filterByStringComparePartially=Te,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=ze();return`${ot(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>rt(t,n),e.getMarkedMessageTopic=st,e.getMarkerUserFeedTopic=it,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=ze();return`${ot(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=ze();return`${ot(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=ct,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=fa,e.getSmartFeedChannelTopic=lt,e.getSmartFeedMessageTopic=ut,e.getSmartFeedSubChannelTopic=dt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=ze();return`${ot(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=at,e.isAfterBefore=W,e.isAfterBeforeRaw=G,e.isCachable=re,e.isFetcher=ee,e.isFresh=oe,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=ne,e.isPaged=J,e.isReportedByMe=async(e,t)=>{var n;const r=be();r.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:o}=Ga[e];if("message"===e){const{data:e}=await r.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{data:a}=await r.http.get(`/api/v3/${o}/${t}/isflagbyme`),{result:s,isFlagByMe:i}=null!=a?a:{};return null!==(n=null!=s?s:i)&&void 0!==n&&n},e.isSkip=H,e.mergeInCache=Se,e.onChannelMarkerFetched=Co,e.onFeedMarkerFetched=e=>{const t=be();return Ye(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=Qr,e.onMessageMarked=Ao,e.onMessageMarkerFetched=Eo,e.onSubChannelMarkerFetched=Io,e.onSubChannelMarkerUpdated=_o,e.onUserMarkerFetched=So,e.onUserMarkerFetchedLegacy=ko,e.pullFromCache=Ie,e.pushToCache=_e,e.queryCache=Ce,e.queryOptions=se,e.queryRoles=pa,e.restoreCache=async(e="amitySdk")=>{var t;const n=be();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 o={};try{o=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},o),n.cache.data),!0},e.runQuery=ie,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=je,e.sortByFirstCreated=Ne,e.sortByFirstUpdated=qe,e.sortByLastActivity=$e,e.sortByLastCreated=Fe,e.sortByLastUpdated=Le,e.sortByLocalSortingDate=Be,e.sortByName=De,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ht,e.toPage=X,e.toPageRaw=Z,e.toToken=Y,e.upsertInCache=ke,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=be();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,io,AsyncStorage,uuid$1,reactNative,hash,Hls);